init
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { Request } from 'express';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { Config } from '../types/Config';
|
||||
|
||||
@Injectable()
|
||||
export class JwtGuard implements CanActivate {
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
|
||||
const { secret } = this.configService.get('jwt') as Config['jwt'];
|
||||
|
||||
const tokenPrefix = 'Bearer ';
|
||||
const raw: unknown = request.cookies.bearer_token;
|
||||
|
||||
if (typeof raw !== 'string' || !raw.startsWith(tokenPrefix)) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
const token = raw.slice(tokenPrefix.length).trim();
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
try {
|
||||
jwt.verify(token, secret);
|
||||
} catch {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user