forked from OPCODE-Open-Spring-Fest/PeerCall
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthMiddleware.ts
More file actions
46 lines (40 loc) · 1.21 KB
/
Copy pathauthMiddleware.ts
File metadata and controls
46 lines (40 loc) · 1.21 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
36
37
38
39
40
41
42
43
44
45
46
import type { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { Session } from "../models/sessionModel.js";
interface AuthRequest extends Request {
userId?: string;
}
export const protect = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.split(" ")[1];
if (!token) {
return res.status(401).json({
success: false,
message: "Not authorized — token missing",
});
}
const decoded = jwt.verify(token, process.env.JWT_ACCESS_SECRET as string) as { id: string };
const activeSession = await Session.findOne({ token });
if (!activeSession) {
return res.status(401).json({
success: false,
message: "Session expired or invalid",
});
}
// If expired then remove it
if (activeSession.expiresAt < new Date()) {
await Session.deleteOne({ token });
return res.status(401).json({
success: false,
message: "Session expired",
});
}
req.userId = decoded.id;
next();
} catch (error) {
return res.status(401).json({
success: false,
message: "Invalid or expired token",
});
}
};