4
4
ExecutionContext ,
5
5
Injectable ,
6
6
Logger ,
7
- UnauthorizedException ,
8
7
} from '@nestjs/common' ;
9
8
import { Reflector } from '@nestjs/core' ;
10
9
import { Roles } from './auth.decorators' ;
@@ -27,16 +26,9 @@ export class AuthGuard implements CanActivate {
27
26
canActivate (
28
27
context : ExecutionContext ,
29
28
) : boolean | Promise < boolean > | Observable < boolean > {
30
- const { pemCert, alg, rolesMapping } = this . options ;
29
+ // const { pemCert, alg, rolesMapping } = this.options;
31
30
const ctx = context . switchToHttp ( ) ;
32
31
const request = ctx . getRequest < Request > ( ) ;
33
- const accessToken = request
34
- . header ( 'authorization' )
35
- ?. replace ( / ^ B e a r e r \s + / i, '' ) ;
36
-
37
- if ( ! accessToken ) {
38
- throw new UnauthorizedException ( 'Authorization header is missing' ) ;
39
- }
40
32
41
33
const roles : string [ ] | undefined = this . reflector . get (
42
34
Roles ,
@@ -48,12 +40,7 @@ export class AuthGuard implements CanActivate {
48
40
}
49
41
50
42
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 ) ;
57
44
const anyRoleMatch = grp . find ( ( tokenRole ) =>
58
45
roles . find ( ( allowedRole ) => allowedRole === tokenRole ) ,
59
46
) ;
@@ -63,4 +50,21 @@ export class AuthGuard implements CanActivate {
63
50
return false ;
64
51
}
65
52
}
53
+ public getUserGroups ( request : Request ) : string [ ] {
54
+ const { pemCert, alg, rolesMapping } = this . options ;
55
+ const accessToken = request
56
+ . header ( 'authorization' )
57
+ ?. replace ( / ^ B e a r e r \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
+ }
66
70
}
0 commit comments