Guest User

Untitled

a guest
May 14th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.29 KB | None | 0 0
  1. Configuration:
  2. config/passport.js
  3. // Set up passport strategy
  4. // Local Strategy in this case
  5.  
  6. // Import modules
  7. const LocalStrategy = require('passport-local').Strategy;
  8. const bcrypt = require('bcryptjs');
  9. const User = require('../models/User');
  10.  
  11. module.exports = (passport) => {
  12. // Local strategy
  13. passport.use(new LocalStrategy(
  14. // Use form fields different from the default of "username" and "password"
  15. {
  16. usernameField: 'email',
  17. // passwordField: myPasswordField
  18. },
  19.  
  20. function(email, password, done) {
  21. // Find the user if they exist
  22. User.findOne({ email: email }, (err, user) => {
  23. if (err) {
  24. return done(err);
  25. }
  26. if (!user) {
  27. return done(null, false, { message: 'Incorrect email and/or password.' });
  28. }
  29. // Check user password
  30. bcrypt.compare(password, user.password, (err, res) => {
  31. if (err) {
  32. return done(err);
  33. }
  34. if (!res) {
  35. return done(null, false, { message: 'Incorrect email and/or password.' });
  36. }
  37. return done(null, user);
  38. });
  39. });
  40. }
  41. ));
  42.  
  43.  
  44. // Session configuration
  45. passport.serializeUser((user, done) => {
  46. done(null, user.id);
  47. });
  48.  
  49. passport.deserializeUser((id, done) => {
  50. User.findById(id, done);
  51. });
  52. };
  53.  
  54.  
  55. config/general.js
  56. // General configuration file for the project
  57. // Takes app as a parameter where app=express();
  58.  
  59. // import passport
  60. const passport = require('passport');
  61.  
  62. // Passport middleware
  63. app.use(passport.initialize());
  64. app.use(passport.session());
  65.  
  66.  
  67. app.js
  68. const passport = require('passport');
  69. require('./config/general')(app);
  70. // The general configuration file
  71. require('./config/passport')(passport);
  72. // Configuration for passport strategy and sessions
  73.  
  74. // ----------------------------
  75.  
  76. Routes:
  77. User registration:
  78. Example form validation and sanitization with express-validator:
  79. body('name', 'Name is required').trim().isLength({min: 1}),
  80. body('email').trim()
  81. .isLength({min: 1}).withMessage('Email is required')
  82. .isEmail().withMessage('Incorrect format for email'),
  83. body('password')
  84. .isLength({min: 1}).withMessage('Password is required')
  85. .matches(/[^\s]/).withMessage('Must not contain any whitespace characters')
  86. .matches(/[a-zA-Z]/).withMessage('Must contain at least one letter'),
  87. body('password2')
  88. .exists()
  89. .custom((val, {req}) => val === req.body.password).withMessage('Passwords do not match'),
  90. sanitizeBody('name').trim().escape(),
  91. sanitizeBody('email').trim().normalizeEmail(),
  92. sanitizeBody('password').escape()
  93.  
  94. Example errors and flash / page messages:
  95. // Get matched data from express-validator in variable user
  96. const user = matchedData(req);
  97. const errors = validationResult(req);
  98.  
  99. // Some view stuff with displaying errors and re-rendering the registration form
  100. if (!errors.isEmpty()) {
  101. return res.render('users/register', {errors: errors.array({onlyFirstError: true}), name: user.name, email: user.email})
  102. }
  103.  
  104. User registration POST route:
  105. // Check if email already exists
  106. User.findOne({email: user.email}, (err, registeredUser) => {
  107. if (err) {
  108. return next(err);
  109. }
  110. if (registeredUser) {
  111. req.flash('error_msg', 'This email has already been registered');
  112. return res.redirect('back');
  113. }
  114. let newUser = new User({
  115. name: user.name,
  116. email: user.email,
  117. });
  118. bcrypt.hash(user.password, 10, (err, hash) => {
  119. newUser.password = hash;
  120. newUser.save((err) => {
  121. if (err) {
  122. return next(err);
  123. }
  124. req.flash('success_msg', 'You are now registered');
  125. res.redirect('/users/login');
  126.  
  127. // or login immediately
  128. /*
  129. req.login(newUser, (err) => {
  130. if (err) {
  131. return next(err);
  132. }
  133. return res.redirect('/ideas');
  134. });
  135. */
  136. });
  137. });
  138. });
  139.  
  140. User login POST route:
  141. // Feel free to add form validation as in the register route
  142. app.post('/login', passport.authenticate('local', {
  143. successRedirect: '/ideas',
  144. failureRedirect: '/users/login',
  145. failureFlash: true
  146. });
  147.  
  148. User logout:
  149. app.get('/logout', (req, res) => {
  150. req.logout();
  151. res.redirect('/ideas');
  152. };
  153.  
  154. User login / register GET routes:
  155. Just render a form for login and registration.
Add Comment
Please, Sign In to add comment