-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
60 lines (58 loc) · 1.48 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
52
53
54
55
56
57
58
59
60
var jwtSecret = 'your_jwt_secret'; // This has to be the same key used in the JWTStrategy
var jwt = require('jsonwebtoken');
const passport = require('passport');
require('./passport'); // Your local passport file
/**
* Generates JWT Token
* @function generateJWTToken
* @param object user
* @returns string Token
*/
function generateJWTToken(user) {
return jwt.sign(user, jwtSecret, {
subject: user.Username, // This is the username you’re encoding in the JWT
expiresIn: '7d', // This specifies that the token will expire in 7 days
algorithm: 'HS256' // This is the algorithm used to “sign” or encode the values of the JWT
});
}
/**
* Module exports user Tokens
* @exports exports
* @param object router
* @returns object user/Token
*/
/* POST login. */
module.exports = router => {
router.post('/login', (req, res) => {
passport.authenticate(
'local',
{
session: false
},
(error, user, _info) => {
if (error || !user) {
return res.status(400).json({
message: 'Something is not right',
user: user
});
}
req.login(
user,
{
session: false
},
error => {
if (error) {
res.send(error);
}
var token = generateJWTToken(user.toJSON());
return res.json({
user,
token
});
}
);
}
)(req, res);
});
};