-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
35 lines (31 loc) · 856 Bytes
/
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
const jwtSecret = 'your_jwt_secret';
const jwt = require('jsonwebtoken'),
passport = require('passport');
require('./passport.js');
let generateJWTToken = (user) => {
return jwt.sign(user, jwtSecret, {
subject: user.Username,
expiresIn: '7d',
algorithm: 'HS256',
});
};
// 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);
}
let token = generateJWTToken(user.toJSON());
return res.json({ user, token });
});
})(req, res);
});
};