/[sudobot]/branches/5.x/src/api/middleware/RequireAuthMiddleware.ts
ViewVC logotype

Annotation of /branches/5.x/src/api/middleware/RequireAuthMiddleware.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (hide annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 1815 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 rakinar2 577 import { NextFunction, Response } from "express";
2     import jwt from "jsonwebtoken";
3     import type Client from "../../core/Client";
4     import { log } from "../../utils/logger";
5     import Request from "../Request";
6    
7     export default async function RequireAuthMiddleware(
8     client: Client,
9     fetchUser: boolean = true,
10     request: Request,
11     response: Response,
12     next: NextFunction
13     ) {
14     if (!request.headers.authorization) {
15     response.status(401).json({
16     error: "No authorization header found in the request"
17     });
18    
19     return;
20     }
21    
22     const [type, token] = request.headers.authorization.split(/\s+/);
23    
24     if (type.toLowerCase() !== "bearer") {
25     response.status(401).json({
26     error: "Only bearer tokens are supported"
27     });
28    
29     return;
30     }
31    
32     try {
33     const info = jwt.verify(token, process.env.JWT_SECRET!, {
34     issuer: process.env.JWT_ISSUER ?? "SudoBot",
35     subject: "Temporary API token for authenticated user",
36     complete: true
37     });
38    
39     const payload = info.payload as {
40     userId: number;
41     };
42    
43     log(info, payload);
44    
45     if (!payload?.userId) {
46     throw new Error("ID not found");
47     }
48    
49     if (!fetchUser) {
50     request.userId = payload.userId;
51     next();
52     return;
53     }
54    
55     const user = await client.prisma.user.findFirst({
56     where: {
57     id: payload.userId,
58     token
59     }
60     });
61    
62     if (!user) {
63     throw new Error();
64     }
65    
66     request.userId = user.id;
67     request.user = user;
68     next();
69     } catch (e) {
70     log(e);
71    
72     response.status(401).json({
73     error: "Invalid API token"
74     });
75    
76     return;
77     }
78     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26