Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // promise
- function login(req, res, callback) {
- User.findOne({email: req.body.email})
- .then(function(user) {
- return user.comparePassword(req.body.password)
- })
- .then(function(isMatch) {
- // have to throw in order to break Promise chain
- if (!isMatch) {
- res.status(401).send('Incorrect password')
- throw {earlyExit: true}
- }
- const payload = {id: user._id, email: user.email}
- return jwt.sign(payload, config.secret, {})
- })
- .then(function(token) {
- user.token = token
- return user.save()
- })
- .then(function() {
- res.json({token})
- })
- .catch(function(err) {
- if (!err.earlyExit) callback(err)
- })
- }
- // async
- async function login(req, res, callback) {
- try {
- const user = await User.findOne({email: req.body.email})
- const isMatch = await user.comparePassword(req.body.password)
- if (!isMatch) return res.status(401).send('Incorrect password')
- const payload = {id: user._id, email: user.email}
- const token = await jwt.sign(payload, config.secret, {})
- user.token = token
- const success = await user.save()
- res.json({token})
- } catch (err) {
- callback(err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement