-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
33 lines (30 loc) · 932 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
const jwt = require('jsonwebtoken');
const passport = require('passport');
require('dotenv').config();
require('./passport');
const generateJWTToken = (user) => jwt.sign(user, process.env.JWT_SECRET, {
subject: user.username,
expiresIn: '7d',
algorithm: 'HS256',
});
// Endpoint 19: Allow users to log in the website.
module.exports = (router) => {
router.post('/login', (req, res) => {
// eslint-disable-next-line consistent-return
passport.authenticate('local', { session: false }, (err, user) => {
if (err || !user) {
return res.status(400).json({
message: 'Oops! Username or password wrong. Please try again.',
user,
});
}
req.login(user, { session: false }, () => {
if (err) {
res.send(err);
}
const token = generateJWTToken(user.toJSON());
return res.json({ user, token });
});
})(req, res);
});
};