-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthMiddleware.ts
More file actions
66 lines (58 loc) · 1.66 KB
/
Copy pathauthMiddleware.ts
File metadata and controls
66 lines (58 loc) · 1.66 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
import type { NextFunction, Request, Response } from "express";
import { SessionStatus } from "@prisma/client";
import AppError from "../errors/AppError";
import tokenService from "../services/tokenService";
import sessionRepository from "../repositories/sessionRepository";
import { extractBearerToken } from "../utils/bearerToken";
export default async function authMiddleware(
req: Request,
_res: Response,
next: NextFunction,
) {
const authorization = req.header("authorization");
if (!authorization) {
return next(
new AppError({
message: "authorization header is required",
code: "AUTHORIZATION_REQUIRED",
statusCode: 401,
}),
);
}
const token = extractBearerToken(authorization);
if (!token) {
return next(
new AppError({
message: "authorization header must use Bearer token",
code: "INVALID_AUTHORIZATION_HEADER",
statusCode: 401,
}),
);
}
try {
const identity = tokenService.verifyAccessToken(token);
const session = await sessionRepository.findById(identity.sessionId);
if (!session || session.userId !== identity.userId) {
throw new AppError({
message: "session not found",
code: "SESSION_NOT_FOUND",
statusCode: 401,
});
}
if (session.status !== SessionStatus.ACTIVE) {
throw new AppError({
message: "session is not active",
code: "SESSION_NOT_ACTIVE",
statusCode: 401,
});
}
req.auth = identity;
req.log = req.log.child({
userId: identity.userId,
sessionId: identity.sessionId,
});
return next();
} catch (error) {
return next(error);
}
}