-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
51 lines (47 loc) · 1.41 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const jwtSecret = 'your_jwt_secret';
const jwt = require('jsonwebtoken'),
passport = require('passport');
require('./passport');
/**
* Generate a JSON Web Token for a user.
* @name generateJWTToken
* @kind function
* @returns a JSON Web Token
*/
let generateJWTToken = (user) => {
return jwt.sign({"_id":user._id}, jwtSecret, {
subject: user.Username,
expiresIn: '7d',
algorithm: 'HS256'
});
}
/**
* POST to login for user authentication.
* @name userLogin
* @kind function
* @requires passport
* @returns a user object, and the associated JSON Web Token.
*/
module.exports = (router) => {
router.post('/login', (req, res) => {
passport.authenticate('local', {session:false}, (error, user, info) => {
if (error) {
return res.status(400).json({
message: 'Something isn\'t right.',
});
}
if (!user) {
return res.status(404).json({
message: 'Make sure you\'ve included a valid username and password to sign in.',
});
}
req.login(user, {session:false}, (error) => {
if (error) {
res.send(error);
}
let token = generateJWTToken(user.toJSON());
return res.json({user, token});
});
})(req, res);
});
}