Last active
April 26, 2019 22:51
-
-
Save AntonioErdeljac/c787327eab1c1bb4e216fabe0fb9d8c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose'); | |
const passport = require('passport'); | |
const router = require('express').Router(); | |
const auth = require('../auth'); | |
const Users = mongoose.model('Users'); | |
//POST new user route (optional, everyone has access) | |
router.post('/', auth.optional, (req, res, next) => { | |
const { body: { user } } = req; | |
if(!user.email) { | |
return res.status(422).json({ | |
errors: { | |
email: 'is required', | |
}, | |
}); | |
} | |
if(!user.password) { | |
return res.status(422).json({ | |
errors: { | |
password: 'is required', | |
}, | |
}); | |
} | |
const finalUser = new Users(user); | |
finalUser.setPassword(user.password); | |
return finalUser.save() | |
.then(() => res.json({ user: finalUser.toAuthJSON() })); | |
}); | |
//POST login route (optional, everyone has access) | |
router.post('/login', auth.optional, (req, res, next) => { | |
const { body: { user } } = req; | |
if(!user.email) { | |
return res.status(422).json({ | |
errors: { | |
email: 'is required', | |
}, | |
}); | |
} | |
if(!user.password) { | |
return res.status(422).json({ | |
errors: { | |
password: 'is required', | |
}, | |
}); | |
} | |
return passport.authenticate('local', { session: false }, (err, passportUser, info) => { | |
if(err) { | |
return next(err); | |
} | |
if(passportUser) { | |
const user = passportUser; | |
user.token = passportUser.generateJWT(); | |
return res.json({ user: user.toAuthJSON() }); | |
} | |
return status(400).info; | |
})(req, res, next); | |
}); | |
//GET current route (required, only authenticated users have access) | |
router.get('/current', auth.required, (req, res, next) => { | |
const { payload: { id } } = req; | |
return Users.findById(id) | |
.then((user) => { | |
if(!user) { | |
return res.sendStatus(400); | |
} | |
return res.json({ user: user.toAuthJSON() }); | |
}); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the 400 on line 78 should be a 401.