|
| 1 | +import { |
| 2 | + CanActivate, |
| 3 | + ExecutionContext, |
| 4 | + Injectable, |
| 5 | + UnauthorizedException, |
| 6 | +} from '@nestjs/common'; |
| 7 | +import { Reflector } from '@nestjs/core'; |
| 8 | +import { JwtService } from '@nestjs/jwt'; |
| 9 | +import { Request } from 'express'; |
| 10 | +import { jwtConstants } from '../../auth/constants'; |
| 11 | +import { IS_PUBLIC_KEY } from '../../auth/decorators/public.decorator'; |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class AuthGuard implements CanActivate { |
| 15 | + constructor( |
| 16 | + private jwtService: JwtService, |
| 17 | + private reflector: Reflector, |
| 18 | + ) {} |
| 19 | + |
| 20 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 21 | + const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ |
| 22 | + context.getHandler(), |
| 23 | + context.getClass(), |
| 24 | + ]); |
| 25 | + if (isPublic) { |
| 26 | + // 💡 See this condition |
| 27 | + return true; |
| 28 | + } |
| 29 | + |
| 30 | + const request = context.switchToHttp().getRequest(); |
| 31 | + const token = this.extractTokenFromHeader(request); |
| 32 | + if (!token) { |
| 33 | + throw new UnauthorizedException(); |
| 34 | + } |
| 35 | + try { |
| 36 | + const payload = await this.jwtService.verifyAsync(token, { |
| 37 | + secret: jwtConstants.secret, |
| 38 | + }); |
| 39 | + // 💡 We're assigning the payload to the request object here |
| 40 | + // so that we can access it in our route handlers |
| 41 | + request['user'] = payload; |
| 42 | + } catch { |
| 43 | + throw new UnauthorizedException(); |
| 44 | + } |
| 45 | + return true; |
| 46 | + } |
| 47 | + |
| 48 | + private extractTokenFromHeader(request: Request): string | undefined { |
| 49 | + const [type, token] = request.headers.authorization?.split(' ') ?? []; |
| 50 | + return type === 'Bearer' ? token : undefined; |
| 51 | + } |
| 52 | +} |
0 commit comments