-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
47 lines (40 loc) · 1.08 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
const jwt = require("jsonwebtoken"),
tokenSecret = 'secret',
bcrypt = require('bcrypt-nodejs');
function getToken(user) {
var token = jwt.sign({ _id: user._id }, tokenSecret, {
expiresIn: '24h'
});
return token;
}
function checkLogin(req, callbackFunc) {
if (!req.cookies.token) return;
var decoded = jwt.verify(req.cookies.token, tokenSecret);
if (decoded) {
return true;
}
return false;
}
function requireAuthentication(req, res, next) {
if (checkLogin(req)) {
next();
} else {
res.redirect('/login');
}
}
function hashPassword(plainPassword) {
var hashedPassword = bcrypt.hashSync(plainPassword);
return hashedPassword;
}
function login(req, res, user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
res.cookie('token', getToken(user));
res.cookie('userEmail', user.email);
return true;
}
return false;
}
exports.requireAuthentication = requireAuthentication;
exports.hashPassword = hashPassword;
exports.login = login;
exports.checkLogin = checkLogin;