Created
September 26, 2022 14:03
-
-
Save hakimkal/bfba8a58dc54268b397cf51f6863e56e to your computer and use it in GitHub Desktop.
authentication guard for JWT
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
| import { ExecutionContext, Inject, Injectable } from '@nestjs/common'; | |
| import { User } from '@/users/entities/user.entity'; | |
| import { AuthGuard, IAuthGuard } from '@nestjs/passport'; | |
| import { AuthHelper } from '@/users/auth/auth.helper'; | |
| @Injectable() | |
| export class JwtAuthGuard extends AuthGuard('jwt') implements IAuthGuard { | |
| @Inject(AuthHelper) helper: AuthHelper; | |
| public async canActivate(context: ExecutionContext): Promise<boolean> { | |
| await super.canActivate(context); | |
| const jwtToken = context.switchToHttp().getRequest().headers[ | |
| 'authorization' | |
| ]; | |
| let user: User = null; | |
| if (jwtToken) { | |
| const token = jwtToken.substring(7); | |
| if (await this.helper.validate(token)) | |
| user = await this.helper.decode(token); | |
| } | |
| return !!(user && user.id); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment