-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
32 lines (27 loc) · 763 Bytes
/
auth.js
File metadata and controls
32 lines (27 loc) · 763 Bytes
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
const jwt = require("jsonwebtoken");
const Users = require("./model/userModel");
require("dotenv").config();
const authenticate = async (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(401).send("Token not found, please login.");
}
const { email } = await jwt.verify(
token,
process.env.AUTH_KEY,
(err, decoded) => {
if (err) {
throw Error("Failed to authenticate token");
}
return decoded;
}
);
const user = await Users.getByEmail(email);
if (!user) {
return res.status(404).send("No user found.");
}
req.id = user.id;
console.log(user, "in auth.js");
next();
};
module.exports = authenticate;