Skip to content

Commit 4fad6de

Browse files
committed
feat: enhance JWT default guard with admin authentication validation
- Implemented comprehensive JWT validation for admin users - Added checks to verify admin user's identity and role - Integrated QueryBus to fetch and validate admin entity details - Improved security by cross-referencing JWT payload with database records
1 parent 7bfc7e8 commit 4fad6de

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed
Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,55 @@
1+
import { ExecutionContext, Injectable } from '@nestjs/common';
12
import { AuthGuard } from '@nestjs/passport';
3+
import { QueryBus } from '@nestjs/cqrs';
24

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

Comments
 (0)