|
| 1 | +import { ExecutionContext, Injectable } from '@nestjs/common'; |
1 | 2 | import { AuthGuard } from '@nestjs/passport'; |
| 3 | +import { QueryBus } from '@nestjs/cqrs'; |
2 | 4 |
|
3 | | -export class JwtDefaultGuard extends AuthGuard('registeredUserJWT') {} |
| 5 | +import { ICommandResponse } from '@common/types/command-response.type'; |
| 6 | +import { ROLE } from '@libs/contracts/constants'; |
| 7 | + |
| 8 | +import { GetAdminByUsernameQuery } from '@modules/admin/queries/get-admin-by-username/get-admin-by-username.query'; |
| 9 | +import { AdminEntity } from '@modules/admin/entities/admin.entity'; |
| 10 | +import { IJWTAuthPayload } from '@modules/auth/interfaces'; |
| 11 | + |
| 12 | +@Injectable() |
| 13 | +export class JwtDefaultGuard extends AuthGuard('registeredUserJWT') { |
| 14 | + constructor(private readonly queryBus: QueryBus) { |
| 15 | + super(); |
| 16 | + } |
| 17 | + |
| 18 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 19 | + const isJwtValid = await super.canActivate(context); |
| 20 | + if (!isJwtValid) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + const { user } = context.switchToHttp().getRequest<{ user: IJWTAuthPayload }>(); |
| 25 | + |
| 26 | + if (!user || !user.username || !user.role) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + if (user.role === ROLE.ADMIN) { |
| 31 | + const adminEntity = await this.getAdminByUsername({ |
| 32 | + username: user.username, |
| 33 | + role: user.role, |
| 34 | + }); |
| 35 | + |
| 36 | + if (!adminEntity.isOk || !adminEntity.response) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + if (adminEntity.response.uuid !== user.uuid) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return true; |
| 46 | + } |
| 47 | + |
| 48 | + private async getAdminByUsername( |
| 49 | + dto: GetAdminByUsernameQuery, |
| 50 | + ): Promise<ICommandResponse<AdminEntity>> { |
| 51 | + return this.queryBus.execute<GetAdminByUsernameQuery, ICommandResponse<AdminEntity>>( |
| 52 | + new GetAdminByUsernameQuery(dto.username, dto.role), |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
0 commit comments