Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // promise
  2. function login(req, res, callback) {
  3.   User.findOne({email: req.body.email})
  4.     .then(function(user) {
  5.       return user.comparePassword(req.body.password)
  6.     })
  7.     .then(function(isMatch) {
  8.       // have to throw in order to break Promise chain
  9.       if (!isMatch) {
  10.         res.status(401).send('Incorrect password')
  11.         throw {earlyExit: true}
  12.       }
  13.       const payload = {id: user._id, email: user.email}
  14.       return jwt.sign(payload, config.secret, {})
  15.     })
  16.     .then(function(token) {
  17.       user.token = token
  18.       return user.save()
  19.     })
  20.     .then(function() {
  21.       res.json({token})
  22.     })
  23.     .catch(function(err) {
  24.       if (!err.earlyExit) callback(err)
  25.     })
  26. }
  27. // async
  28. async function login(req, res, callback) {
  29.   try {
  30.     const user = await User.findOne({email: req.body.email})
  31.     const isMatch = await user.comparePassword(req.body.password)
  32.  
  33.     if (!isMatch) return res.status(401).send('Incorrect password')
  34.  
  35.     const payload = {id: user._id, email: user.email}
  36.     const token = await jwt.sign(payload, config.secret, {})
  37.  
  38.     user.token = token
  39.     const success = await user.save()
  40.  
  41.     res.json({token})
  42.   } catch (err) {
  43.     callback(err)
  44.   }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement