-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthMiddleware.js
48 lines (43 loc) · 1.14 KB
/
authMiddleware.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
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const requireAuth = (req, res, next) => {
const token = req.cookies.jwt; //get the token from the cookies
//chech json web token exist & is verified
if(token){
jwt.verify(token, 'my secret', (err, decodedToken) => {
if(err){
console.log(err.message);
res.redirect('/login');
}
else {
next();
}
})
}
else{
res.redirect('/login');
}
}
//check current user
const checkUser = (req, res, next) => {
const token = req.cookies.jwt;
if (token){
jwt.verify(token, 'my secret', async (err, decodedToken) => {
if(err){
console.log(err.message);
res.local.user = null;
next();
}
else {
let user = await User.findById(decodedToken.id);
res.locals.user = user;
next();
}
})
}
else{
res.local.user = null;
next();
}
}
module.exports = { requireAuth, checkUser };