-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
35 lines (30 loc) · 1.25 KB
/
auth.js
File metadata and controls
35 lines (30 loc) · 1.25 KB
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 jwt = require("jsonwebtoken");
const User = require("../models/user");
const authenticate = (req, res, next) => {
try {
const token = req.cookies.jwt_token;
//suppose if token not exist in browser cookies or someone delete it
if (!token) {
res.redirect('/');
}
// in this user a object is return with email and the userId
const user = jwt.verify(token, process.env.SECRET_KEY); //It give the binded data after matching with secret_key
//suppose someone edit or alter my token in browser cokkies or cookies is not match with my secret key or vrify unsuccessful.
if (!user) {
res.redirect('/');
}
User.findByPk(user.userId).then((user) => {
//suposse that if user is not in our db or not exist
if (!user) {
res.redirect('/');
}
req.user = user; //make a user property in req
next(); // it goes to next action, controller
});
} catch (err) {
// console.log(err);
// return res.status(401).json({ success: false });
res.send(`<script> document.cookie = "jwt_token=; max-age=-60"; window.location.href='/';</script>`);
}
};
module.exports = authenticate;