47 lines
1.2 KiB
TypeScript
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,
|
|
});
|
|
}
|
|
}
|
|
}
|