Skip to content

Commit 33ff85b

Browse files
committed
Refactor token group verification into separate method
1 parent 8472caf commit 33ff85b

File tree

2 files changed

+24
-15
lines changed

2 files changed

+24
-15
lines changed

.zed/debug.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Project-local debug tasks
2+
//
3+
// For more documentation on how to configure debug tasks,
4+
// see: https://zed.dev/docs/debugger
5+
[]

src/auth.guard.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
ExecutionContext,
55
Injectable,
66
Logger,
7-
UnauthorizedException,
87
} from '@nestjs/common';
98
import { Reflector } from '@nestjs/core';
109
import { Roles } from './auth.decorators';
@@ -27,16 +26,9 @@ export class AuthGuard implements CanActivate {
2726
canActivate(
2827
context: ExecutionContext,
2928
): boolean | Promise<boolean> | Observable<boolean> {
30-
const { pemCert, alg, rolesMapping } = this.options;
29+
// const { pemCert, alg, rolesMapping } = this.options;
3130
const ctx = context.switchToHttp();
3231
const request = ctx.getRequest<Request>();
33-
const accessToken = request
34-
.header('authorization')
35-
?.replace(/^Bearer\s+/i, '');
36-
37-
if (!accessToken) {
38-
throw new UnauthorizedException('Authorization header is missing');
39-
}
4032

4133
const roles: string[] | undefined = this.reflector.get(
4234
Roles,
@@ -48,12 +40,7 @@ export class AuthGuard implements CanActivate {
4840
}
4941

5042
try {
51-
const token = verify(accessToken, pemCert, {
52-
algorithms: [alg],
53-
});
54-
const grp: string[] =
55-
((token as JwtPayload)?.[rolesMapping] as unknown as string[]) || [];
56-
43+
const grp = this.getUserGroups(request);
5744
const anyRoleMatch = grp.find((tokenRole) =>
5845
roles.find((allowedRole) => allowedRole === tokenRole),
5946
);
@@ -63,4 +50,21 @@ export class AuthGuard implements CanActivate {
6350
return false;
6451
}
6552
}
53+
public getUserGroups(request: Request): string[] {
54+
const { pemCert, alg, rolesMapping } = this.options;
55+
const accessToken = request
56+
.header('authorization')
57+
?.replace(/^Bearer\s+/i, '');
58+
59+
if (!accessToken) {
60+
return [];
61+
}
62+
63+
const token = verify(accessToken, pemCert, {
64+
algorithms: [alg],
65+
});
66+
const grp: string[] =
67+
((token as JwtPayload)?.[rolesMapping] as unknown as string[]) || [];
68+
return grp;
69+
}
6670
}

0 commit comments

Comments
 (0)