Created
January 17, 2025 17:11
-
-
Save bradley-pp/d6f52a4f9f1a05feabc0a09524ab66de to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| @Injectable() | |
| abstract class AuthGuard implements CanActivate { | |
| protected constructor( | |
| private readonly cls: ClsService, | |
| private readonly tokenValidator: Record<string, (token: string) => string | null>, | |
| ) {} | |
| canActivate( | |
| context: ExecutionContext, | |
| ): boolean { | |
| const request = context.switchToHttp().getRequest<Request>(); | |
| const [_, token] = request.get("Authorization").split(" ") | |
| const user = this.tokenValidator.validateToken(token); | |
| if (!user) { | |
| return false; | |
| } | |
| this.cls.set("userId", user); | |
| return true; | |
| } | |
| } | |
| @Injectable() | |
| class MeInterceptor implements NestInterceptor { | |
| constructor( | |
| private readonly cls: ClsService | |
| ) {} | |
| intercept(context: ExecutionContext, next: CallHandler) { | |
| const request = context.switchToHttp().getRequest<Request>(); | |
| const userIdParam = request.params.userId; | |
| if (!userIdParam || userIdParam.toLowerCase() !== "me") { | |
| return; | |
| } | |
| request.params.userId = this.cls.get("userId"); | |
| return next.handle(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment