|
| 1 | +import { |
| 2 | + HttpException, |
| 3 | + Injectable, |
| 4 | + InternalServerErrorException, |
| 5 | + NestMiddleware, |
| 6 | + NotFoundException, |
| 7 | + UnauthorizedException, |
| 8 | +} from '@nestjs/common'; |
| 9 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 10 | +import Sentry from '@sentry/minimal'; |
| 11 | +import { NextFunction, Response } from 'express'; |
| 12 | +import jwt from 'jsonwebtoken'; |
| 13 | +import { Repository } from 'typeorm'; |
| 14 | +import { JwtScopesEnum } from '../entities/user/enums/jwt-scopes.enum.js'; |
| 15 | +import { UserEntity } from '../entities/user/user.entity.js'; |
| 16 | +import { EncryptionAlgorithmEnum } from '../enums/encryption-algorithm.enum.js'; |
| 17 | +import { TwoFaRequiredException } from '../exceptions/custom-exceptions/two-fa-required-exception.js'; |
| 18 | +import { Messages } from '../exceptions/text/messages.js'; |
| 19 | +import { Constants } from '../helpers/constants/constants.js'; |
| 20 | +import { Encryptor } from '../helpers/encryption/encryptor.js'; |
| 21 | +import { isObjectEmpty } from '../helpers/is-object-empty.js'; |
| 22 | +import { appConfig } from '../shared/config/app-config.js'; |
| 23 | +import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js'; |
| 24 | + |
| 25 | +/** |
| 26 | + * Authentication middleware that ALSO allows anonymous ("public") requests through. |
| 27 | + * |
| 28 | + * - A JWT cookie or an `x-api-key` header is authenticated exactly like AuthWithApiMiddleware and |
| 29 | + * populates `req.decoded`. |
| 30 | + * - When neither is present, the request is treated as public: `req.decoded` is left empty and the |
| 31 | + * request continues. Downstream guards then decide whether the connection's public policy grants |
| 32 | + * access. An invalid/expired credential still fails fast. |
| 33 | + * |
| 34 | + * This is applied only to read-capable pure CRUD routes; write routes keep AuthWithApiMiddleware. |
| 35 | + */ |
| 36 | +@Injectable() |
| 37 | +export class PublicOrAuthMiddleware implements NestMiddleware { |
| 38 | + public constructor( |
| 39 | + @InjectRepository(UserEntity) |
| 40 | + private readonly userRepository: Repository<UserEntity>, |
| 41 | + ) {} |
| 42 | + |
| 43 | + async use(req: IRequestWithCognitoInfo, _res: Response, next: NextFunction): Promise<void> { |
| 44 | + try { |
| 45 | + const tokenFromCookie = req.cookies?.[Constants.JWT_COOKIE_KEY_NAME]; |
| 46 | + let apiKey = req.headers?.['x-api-key']; |
| 47 | + if (Array.isArray(apiKey)) { |
| 48 | + apiKey = apiKey[0]; |
| 49 | + } |
| 50 | + |
| 51 | + if (tokenFromCookie) { |
| 52 | + await this.authenticateWithToken(tokenFromCookie, req); |
| 53 | + } else if (apiKey) { |
| 54 | + await this.authenticateWithApiKey(apiKey, req); |
| 55 | + } else { |
| 56 | + req.decoded = {}; |
| 57 | + } |
| 58 | + next(); |
| 59 | + } catch (error) { |
| 60 | + Sentry.captureException(error); |
| 61 | + if (error instanceof HttpException || error instanceof UnauthorizedException) { |
| 62 | + throw error; |
| 63 | + } |
| 64 | + throw new InternalServerErrorException(Messages.AUTHORIZATION_REJECTED); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private async authenticateWithToken(tokenFromCookie: string, req: IRequestWithCognitoInfo): Promise<void> { |
| 69 | + const jwtSecret = appConfig.auth.jwtSecret; |
| 70 | + if (!jwtSecret) { |
| 71 | + throw new UnauthorizedException('JWT verification failed'); |
| 72 | + } |
| 73 | + const data = jwt.verify(tokenFromCookie, jwtSecret) as jwt.JwtPayload; |
| 74 | + const userId = data.id; |
| 75 | + |
| 76 | + if (!userId) { |
| 77 | + throw new UnauthorizedException('JWT verification failed'); |
| 78 | + } |
| 79 | + |
| 80 | + const userExists = await this.userRepository.findOne({ where: { id: userId } }); |
| 81 | + if (!userExists) { |
| 82 | + throw new UnauthorizedException('JWT verification failed'); |
| 83 | + } |
| 84 | + |
| 85 | + if (userExists.suspended) { |
| 86 | + throw new UnauthorizedException(Messages.ACCOUNT_SUSPENDED); |
| 87 | + } |
| 88 | + |
| 89 | + const addedScope: Array<JwtScopesEnum> = data.scope; |
| 90 | + if (addedScope && addedScope.length > 0) { |
| 91 | + if (addedScope.includes(JwtScopesEnum.TWO_FA_ENABLE)) { |
| 92 | + throw new TwoFaRequiredException(); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + const payload = { |
| 97 | + sub: userId, |
| 98 | + email: data.email, |
| 99 | + exp: data.exp, |
| 100 | + iat: data.iat, |
| 101 | + }; |
| 102 | + if (!payload || isObjectEmpty(payload)) { |
| 103 | + throw new UnauthorizedException('JWT verification failed'); |
| 104 | + } |
| 105 | + req.decoded = payload; |
| 106 | + } |
| 107 | + |
| 108 | + private async authenticateWithApiKey(apiKey: string, req: IRequestWithCognitoInfo): Promise<void> { |
| 109 | + const apiKeyHash = await Encryptor.processDataWithAlgorithm(apiKey, EncryptionAlgorithmEnum.sha256); |
| 110 | + const foundUserByApiKey = await this.userRepository |
| 111 | + .createQueryBuilder('user') |
| 112 | + .innerJoinAndSelect('user.api_keys', 'api_key') |
| 113 | + .where('api_key.hash = :hash', { hash: apiKeyHash }) |
| 114 | + .getOne(); |
| 115 | + |
| 116 | + if (!foundUserByApiKey) { |
| 117 | + throw new NotFoundException(Messages.NO_AUTH_KEYS_FOUND); |
| 118 | + } |
| 119 | + |
| 120 | + if (foundUserByApiKey.suspended) { |
| 121 | + throw new UnauthorizedException(Messages.API_KEY_SUSPENDED); |
| 122 | + } |
| 123 | + |
| 124 | + req.decoded = { |
| 125 | + sub: foundUserByApiKey.id, |
| 126 | + email: foundUserByApiKey.email, |
| 127 | + }; |
| 128 | + } |
| 129 | +} |
0 commit comments