Skip to content

Instantly share code, notes, and snippets.

@hakimkal
Created September 26, 2022 14:03
Show Gist options
  • Select an option

  • Save hakimkal/bfba8a58dc54268b397cf51f6863e56e to your computer and use it in GitHub Desktop.

Select an option

Save hakimkal/bfba8a58dc54268b397cf51f6863e56e to your computer and use it in GitHub Desktop.
authentication guard for JWT
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