BE/src/guards/jwt-auth.guard.ts
2025-06-18 17:15:21 +05:30

47 lines
1.2 KiB
TypeScript

import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
Global,
} from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';
@Global()
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
// Read token from cookie
console.log('------------------------------');
let g = await request.cookies
console.log("g : ",g);
console.log(' guard cookies ------------------------------');
const token = request.cookies?.access_token;
if (!token) {
console.log('error from inspect token .....');
throw new UnauthorizedException('Authentication failed');
}
try {
const decoded = await this.authService.decodeToken(token);
request.user = decoded;
return true;
} catch (err) {
console.log("error in jwt-auth guard below decode : ",err.message);
throw new UnauthorizedException({
message: 'Invalid Token',
error: 'Unauthorized',
statusCode: 401,
});
}
}
}