-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Guard for all authentication method
- Loading branch information
Showing
13 changed files
with
154 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
{ | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"type": "node", | ||
"request": "launch", | ||
"name": "Debug Nest Framework", | ||
"args": ["${workspaceFolder}/src/main.ts"], | ||
"runtimeArgs": [ | ||
"--nolazy", | ||
"-r", | ||
"ts-node/register", | ||
"-r", | ||
"tsconfig-paths/register" | ||
], | ||
"sourceMaps": true, | ||
"envFile": "${workspaceFolder}/.env", | ||
"cwd": "${workspaceRoot}", | ||
"console": "integratedTerminal", | ||
"protocol": "inspector" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
11 changes: 11 additions & 0 deletions
11
server/src/iam/authentication/decorators/active-user/active-user.decorator.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { ExecutionContext, createParamDecorator } from '@nestjs/common'; | ||
import { ActiveUserData } from '../../interfaces/active-user-data.interface'; | ||
import { REQUEST_USER_KEY } from 'src/iam/constants/iam.contant'; | ||
|
||
export const ActiveUser = createParamDecorator( | ||
(field: keyof ActiveUserData | undefined, ctx: ExecutionContext) => { | ||
const request = ctx.switchToHttp().getRequest(); | ||
const user: ActiveUserData | undefined = request[REQUEST_USER_KEY]; | ||
return field ? user && user?.[field] : user; | ||
}, | ||
); |
7 changes: 7 additions & 0 deletions
7
server/src/iam/authentication/decorators/auth/auth.decorator.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { SetMetadata } from '@nestjs/common'; | ||
import { AuthType } from '../../enums/auth-type.enum'; | ||
|
||
export const AUTH_TYPE_KEY = 'authType'; | ||
|
||
export const Auth = (...authTypes: AuthType[]) => | ||
SetMetadata(AUTH_TYPE_KEY, authTypes); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export enum AuthType { | ||
Bearer, | ||
None, | ||
} |
7 changes: 7 additions & 0 deletions
7
server/src/iam/authentication/guards/access-token/access-token.guard.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { AccessTokenGuard } from './access-token.guard'; | ||
|
||
describe('AccessTokenGuard', () => { | ||
it('should be defined', () => { | ||
expect(new AccessTokenGuard()).toBeDefined(); | ||
}); | ||
}); |
29 changes: 29 additions & 0 deletions
29
server/src/iam/authentication/guards/access-token/access-token.guard.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { | ||
CanActivate, | ||
ExecutionContext, | ||
Injectable, | ||
UnauthorizedException, | ||
} from '@nestjs/common'; | ||
import { AuthGuard } from '@nestjs/passport'; | ||
import { Observable } from 'rxjs'; | ||
import { ActiveUserData } from '../../interfaces/active-user-data.interface'; | ||
|
||
@Injectable() | ||
export class AccessTokenGuard extends AuthGuard('jwt') implements CanActivate { | ||
constructor() { | ||
super(); | ||
} | ||
canActivate( | ||
context: ExecutionContext, | ||
): boolean | Promise<boolean> | Observable<boolean> { | ||
return super.canActivate(context); | ||
} | ||
|
||
handleRequest(err: any, user: any, info: any) { | ||
// You can throw an exception based on either "info" or "err" arguments | ||
if (err || !user) { | ||
throw err || new UnauthorizedException('No access token found'); | ||
} | ||
return user; | ||
} | ||
} |
7 changes: 7 additions & 0 deletions
7
server/src/iam/authentication/guards/authentication/authentication.guard.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { AuthenticationGuard } from './authentication.guard'; | ||
|
||
describe('AuthenticationGuard', () => { | ||
it('should be defined', () => { | ||
expect(new AuthenticationGuard()).toBeDefined(); | ||
}); | ||
}); |
51 changes: 51 additions & 0 deletions
51
server/src/iam/authentication/guards/authentication/authentication.guard.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { AccessTokenGuard } from './../access-token/access-token.guard'; | ||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; | ||
import { AuthType } from '../../enums/auth-type.enum'; | ||
import { Reflector } from '@nestjs/core'; | ||
import { AUTH_TYPE_KEY } from '../../decorators/auth/auth.decorator'; | ||
|
||
@Injectable() | ||
export class AuthenticationGuard implements CanActivate { | ||
constructor( | ||
private readonly reflector: Reflector, | ||
private readonly accessTokenGuard: AccessTokenGuard, | ||
) {} | ||
private static readonly defaultAuthType = AuthType.Bearer; | ||
|
||
private readonly authTypeGuardMap: Record< | ||
AuthType, | ||
CanActivate | CanActivate[] | ||
> = { | ||
[AuthType.None]: { canActivate: () => true }, | ||
[AuthType.Bearer]: this.accessTokenGuard, | ||
}; | ||
|
||
async canActivate(context: ExecutionContext): Promise<boolean> { | ||
const authTypes = this.reflector.getAllAndOverride<AuthType[]>( | ||
AUTH_TYPE_KEY, | ||
[context.getHandler(), context.getClass()], | ||
) ?? [AuthenticationGuard.defaultAuthType]; | ||
|
||
const guards = authTypes | ||
.map((type: any) => this.authTypeGuardMap[type]) | ||
.flat(); | ||
|
||
const guardPromises = guards.map((guard: any) => | ||
guard.canActivate(context), | ||
); | ||
|
||
const results = await Promise.allSettled(guardPromises); //? return 'rejected' or 'fulfilled' | ||
|
||
const rejected = results.find((result: any) => { | ||
return result.status === 'rejected'; | ||
}); | ||
|
||
if (rejected) { | ||
throw rejected['reason']; | ||
} | ||
|
||
return results.some( | ||
(result: any) => result.status === 'fulfilled' && result.value, | ||
); | ||
} | ||
} |
2 changes: 1 addition & 1 deletion
2
...ation/interfaces/active-user.interface.ts → .../interfaces/active-user-data.interface.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
export interface ActiveUser { | ||
export interface ActiveUserData { | ||
sub: number; | ||
email: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export const REQUEST_USER_KEY = 'user'; |