|
| 1 | +import { ForbiddenError } from '@application/errors/ForbiddenError'; |
| 2 | +import { AuthenticateInterface } from '@application/interfaces/use-cases/authentication/AuthenticateInterface'; |
| 3 | +import { AuthTokenNotProvidedError } from '@infra/http/errors/AuthTokenNotProvidedError'; |
| 4 | +import { InvalidAuthTokenError } from '@infra/http/errors/InvalidAuthTokenError'; |
| 5 | +import { forbidden, ok } from '@infra/http/helpers/http'; |
| 6 | +import { HttpRequest } from '@infra/http/interfaces/HttpRequest'; |
| 7 | +import { HttpResponse } from '@infra/http/interfaces/HttpResponse'; |
| 8 | +import { BaseMiddleware } from '@infra/http/middlewares/BaseMiddleware'; |
| 9 | + |
| 10 | +export class AuthMiddleware extends BaseMiddleware { |
| 11 | + constructor(private readonly authenticate: AuthenticateInterface) { |
| 12 | + super(); |
| 13 | + } |
| 14 | + |
| 15 | + async execute( |
| 16 | + httpRequest: AuthMiddleware.Request |
| 17 | + ): Promise<AuthMiddleware.Response> { |
| 18 | + const authHeader = httpRequest.headers?.authorization; |
| 19 | + if (!authHeader) { |
| 20 | + return forbidden(new AuthTokenNotProvidedError()); |
| 21 | + } |
| 22 | + const [, authToken] = authHeader.split(' '); |
| 23 | + const userIdOrError = await this.authenticate.execute(authToken); |
| 24 | + if (userIdOrError instanceof ForbiddenError) { |
| 25 | + return forbidden(new InvalidAuthTokenError()); |
| 26 | + } |
| 27 | + return ok({ userId: userIdOrError }); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export namespace AuthMiddleware { |
| 32 | + export type Request = HttpRequest< |
| 33 | + undefined, |
| 34 | + undefined, |
| 35 | + { authorization: string } |
| 36 | + >; |
| 37 | + export type Response = HttpResponse< |
| 38 | + { userId: string } | AuthTokenNotProvidedError | InvalidAuthTokenError |
| 39 | + >; |
| 40 | +} |
0 commit comments