54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
// jwt-auth.guard.ts
|
|
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { Request } from 'express';
|
|
|
|
@Injectable()
|
|
export class RegisterGuard implements CanActivate {
|
|
constructor(private readonly jwtService: JwtService) {}
|
|
|
|
canActivate(context: ExecutionContext): boolean {
|
|
const request = context.switchToHttp().getRequest<Request>();
|
|
const authHeader = request.headers['authorization'];
|
|
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
throw new UnauthorizedException('Authorization header missing or malformed');
|
|
}
|
|
|
|
const token = authHeader.split(' ')[1];
|
|
|
|
try {
|
|
// Decode without verifying to check expiry
|
|
const decoded: any = this.jwtService.decode(token);
|
|
|
|
console.log(decoded);
|
|
|
|
|
|
if (!decoded || !decoded.exp) {
|
|
throw new UnauthorizedException('Invalid token payload');
|
|
}
|
|
|
|
// Check expiration (exp is in seconds, Date.now() in ms)
|
|
const now = Math.floor(Date.now() / 1000);
|
|
if (decoded.exp < now) {
|
|
throw new UnauthorizedException('Token expired');
|
|
}
|
|
|
|
// Verify the token (checks signature and expiration again)
|
|
this.jwtService.verify(token, {secret:'yourSecretKey'});
|
|
|
|
// Optionally attach user info to request object for further use
|
|
request['user'] = decoded;
|
|
|
|
return true;
|
|
} catch (err) {
|
|
throw new UnauthorizedException('Invalid or expired token');
|
|
}
|
|
}
|
|
}
|