Advertisement
EntropyStarRover

auth controller

Jun 21st, 2021
38
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const router = require('express').Router();
  2. const {body, validationResult} = require('express-validator');
  3. const {isGuest,isUser} = require('../middlewares/guards')
  4.  
  5. router.get('/register',isGuest(), (req, res) => {
  6. res.render('register');
  7. });
  8.  
  9. router.post('/register',isGuest(),
  10. body('username').isLength({min: 3}).withMessage('Username must be atleast 3 chars').bail()
  11. .isAlphanumeric().withMessage('Username must include alphanumeric chars only!'),
  12. body('rePassword').custom((value, {req}) => {
  13. if (value != req.body.password) {
  14. throw new Error('passwords dont match');
  15. }
  16. return true;
  17. }),
  18. async (req, res) => {
  19. console.log(req.body);
  20. const {errors}=validationResult(req);
  21.  
  22. try{
  23. if (errors.length>0){
  24. console.log(errors)
  25. throw new Error('Validation error')
  26. }
  27. await req.auth.register(req.body.username,req.body.password);
  28. console.log('user registered')
  29. res.redirect('/');
  30. } catch (err) {
  31. console.log(err)
  32. const ctx={
  33. errors,
  34. userData: {
  35. username:req.body.username
  36. }
  37. };
  38. res.render('register',ctx)
  39. }
  40.  
  41. })
  42.  
  43. router.get('/login',isGuest(), (req, res) => {
  44. res.render('login');
  45. });
  46.  
  47. router.post('/login',isGuest(), async (req, res) => {
  48. try{
  49. console.log(req.body.username, req.body.password)
  50. await req.auth.login(req.body.username, req.body.password);
  51. res.redirect('/');
  52.  
  53. } catch(err){
  54. console.log(err.message)
  55. const ctx={
  56. errors:[err.message],
  57. userData: {
  58. username:req.body.username
  59. }
  60. };
  61. res.render('login',ctx)
  62. }
  63. });
  64.  
  65. router.get('/logout', (req, res)=>{
  66. console.log('logging out')
  67. req.auth.logout();
  68. res.redirect('/')
  69. })
  70.  
  71. module.exports = router;
Advertisement
RAW Paste Data Copied
Advertisement