You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
993 B
33 lines
993 B
import { Injectable } from "@nestjs/common"; |
|
import { CanActivate, ExecutionContext, UnauthorizedException } from "@nestjs/common"; |
|
import { JwtService } from "@nestjs/jwt"; |
|
import { JwtStrategy } from './jwt.strategy'; |
|
|
|
@Injectable() |
|
export class JwtAuthGuard implements CanActivate { |
|
constructor( |
|
private readonly jwtService: JwtService, |
|
private readonly jwtStrategy: JwtStrategy |
|
) {} |
|
|
|
async canActivate(context: ExecutionContext): Promise<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, { |
|
secret: process.env.JWT_SECRET, |
|
}); |
|
await this.jwtStrategy.validate(decoded); |
|
|
|
request.user = decoded; |
|
return true; |
|
} catch (error) { |
|
throw new UnauthorizedException("Invalid or expired token"); |
|
} |
|
} |
|
}
|
|
|