Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. const jwt = require('jsonwebtoken');
  2. const User = require('mongoose').model('User');
  3. const PassportLocalStrategy = require('passport-local').Strategy;
  4. const config = require('../../config');
  5.  
  6. module.exports = new PassportLocalStrategy({
  7. usernameField: 'email',
  8. passwordField: 'password',
  9. session: false,
  10. passReqToCallback: true
  11. }, (req, email, password, done) => {
  12. const userData = {
  13. email: email.trim(),
  14. password: password.trim()
  15. };
  16.  
  17. // find a user by email address
  18. return User.findOne({ email: userData.email }, (err, user) => {
  19. if (err) { return done(err); }
  20.  
  21. if (!user) {
  22. const error = new Error('Incorrect email or password');
  23. error.name = 'IncorrectCredentialsError';
  24.  
  25. return done(error);
  26. }
  27.  
  28. // check if a hashed user's password is equal to a value saved in the database
  29. return user.comparePassword(userData.password, (passwordErr, isMatch) => {
  30. if (err) { return done(err); }
  31.  
  32. if (!isMatch) {
  33. const error = new Error('Incorrect email or password');
  34. error.name = 'IncorrectCredentialsError';
  35.  
  36. return done(error);
  37. }
  38.  
  39. const payload = {
  40. sub: user._id
  41. };
  42.  
  43. // create a token string
  44. const token = jwt.sign(payload, config.jwtSecret);
  45. const data = {
  46. name: user.name
  47. };
  48.  
  49. return done(null, token, data);
  50. });
  51. });
  52. });
  53.  
  54.  
  55. // then, in index.js, on server I use it:
  56. const localLoginStrategy = require('./server/passport/local-login');
  57. passport.use('local-login', localLoginStrategy);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement