-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
48 lines (44 loc) · 1.99 KB
/
middleware.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, Token, BannedUser } = require('./models');
const validateToken = async (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ status: "error", message: "Unauthorized: No token provided" });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);
if (!user) {
return res.status(401).json({ status: "error", message: "Unauthorized: Invalid session" });
}
if (user.activation_token) {
return res.status(403).json({ status: "error", message: "Forbidden: Account not activated. Please check your email for the activation link." });
}
const tokenExists = await Token.findOne({ token });
if (!tokenExists) {
return res.status(401).json({ status: "error", message: "Unauthorized: Invalid token" });
}
// Check if the user is banned
const activeBan = await BannedUser.findOne({
user_id: user._id,
active: true,
expires_at: { $gt: new Date() }
});
if (activeBan) {
return res.status(403).json({ status: "error", message: `Forbidden: User is banned until ${activeBan.expires_at.toISOString()} for ${activeBan.reason}` });
}
req.user = user;
next();
} catch (error) {
if (error.name === 'JsonWebTokenError') {
console.error("Error validating token:", error);
return res.status(401).json({ status: "error", message: "Unauthorized: Invalid token" });
}
if (error.name === 'TokenExpiredError') {
return res.status(401).json({ status: "error", message: "Unauthorized: Token expired" });
}
console.error("Error validating token:", error);
res.status(500).json({ status: "error", message: "Internal server error" });
}
};
module.exports = { validateToken };