parent
effc393545
commit
238cd06920
2 changed files with 28 additions and 1 deletions
@ -0,0 +1,26 @@ |
||||
import { Injectable } from "@nestjs/common"; |
||||
import { CanActivate, ExecutionContext, UnauthorizedException } from "@nestjs/common"; |
||||
import { JwtService } from "@nestjs/jwt"; |
||||
import { Observable } from "rxjs"; |
||||
|
||||
@Injectable() |
||||
export class JwtAuthGuard implements CanActivate { |
||||
constructor(private readonly jwtService: JwtService) {} |
||||
|
||||
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { |
||||
const request = context.switchToHttp().getRequest(); |
||||
const token = request.headers["authorization"]?.split(" ")[1]; |
||||
|
||||
if (!token) { |
||||
throw new UnauthorizedException("Token not found"); |
||||
} |
||||
|
||||
try { |
||||
const decoded = this.jwtService.verify(token); |
||||
request.user = decoded; |
||||
return true; |
||||
} catch (error) { |
||||
throw new UnauthorizedException("Invalid or expired token"); |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue