-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
49 lines (46 loc) · 1.75 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
/*
*********************************************************
Authentication logic:
- creating a new endpoint for registered users to log in
- authenticating users when log in with username + passsword
- generating JWT to authenticate future requests of users
*********************************************************
*/
var jwtSecret = 'your_jwt_secret'; // same key used in JWTStrategy, see passport.js
var jwt = require('jsonwebtoken');
const passport = require('passport');
require('./passport');
function generateJWTToken(user) {
return jwt.sign(user, jwtSecret, {
subject: user.Username, // Username encoding in JWT
expiresIn: '7d', // Token will expire in 7 days
algorithm: 'HS256' // Algorithm used to encode values of JWT
});
}
// POST login. Here login action is implemented.
module.exports = function(router) {
router.post('/login', function(req, res) {
/*Calling passport authentication function with local strategy.
Passed {session: false} in passport options to make sure that user isn't saved in session.*/
passport.authenticate('local', { session: false }, function(
error,
user,
info
) {
if (error || !user) {
return res.status(400).json({
message: 'Something is not right',
user: user
});
}
req.login(user, { session: false }, function(error) {
if (error) {
res.send(error);
}
// if username and password in request body exist in db, generateJWTToken creates a JWT based on username and password.
var token = generateJWTToken(user.toJSON());
return res.json({ user, token }); // ES6 shorthand for: res.json({user: user, token: token})
});
})(req, res);
});
};