-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication.js
43 lines (35 loc) · 1.03 KB
/
authentication.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
require("dotenv").config();
const User = require("../models/User");
const jwt = require("jsonwebtoken");
const authenticateUser = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res
.status(401)
.json({ error: "You are not authorized to perform this action" });
}
const token = authHeader;
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.id);
if (!user) {
return res
.status(404)
.json({ error: "No user found with this id. Please try again" });
}
req.user = user;
} catch (error) {
if (error.name === "JsonWebTokenError") {
return res.status(401).json({ error: "Invalid token" });
}
if (error.name === "TokenExpiredError") {
return res.status(401).json({ error: "Token expired" });
}
console.error(error);
return res.status(500).json({ error: "Internal server error" });
}
next();
};
module.exports = {
authenticateUser,
};