-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathadmin.ts
More file actions
67 lines (40 loc) · 1.33 KB
/
admin.ts
File metadata and controls
67 lines (40 loc) · 1.33 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { client } from "db/client";
import { type NextFunction, type Request, type Response } from "express"
import jwt from "jsonwebtoken"
interface authenticatedRequest extends Request {
userId?: string,
userRole?: string
}
export const adminMiddleware = async(
req: authenticatedRequest,
res: Response,
next: NextFunction
) => {
try {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) {
return res.status(401).json({ error: "Missing token"});
}
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as any;
if (!decoded) {
return res.status(401).json({ error: "Invalid token"});
}
const user = await client.user.findUnique({
where: {
id: decoded.userId
},
select: {
role: true,
id: true
}
})
if (!user || user.role !== "Admin"){
return res.status(401).json({ error: "Unauthorized"});
}
req.userId = user.id;
req.userRole = user.role;
next();
} catch (error) {
res.status(401).json({ error: "Invalid token"});
}
}