2021-11-23 16:04:12 -05:00
|
|
|
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
|
|
|
import { JwtService } from '../services/jwt.service';
|
2021-12-01 22:18:26 -05:00
|
|
|
import { SKIP_KEY } from 'server/decorators/skip.decorator';
|
|
|
|
import { Reflector } from '@nestjs/core';
|
|
|
|
import { Class } from 'server/dto/class.dto';
|
2021-11-23 16:04:12 -05:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AuthGuard implements CanActivate {
|
2021-12-01 22:18:26 -05:00
|
|
|
constructor(private reflector: Reflector, private jwtService: JwtService) {}
|
2021-11-23 16:04:12 -05:00
|
|
|
|
|
|
|
canActivate(context: ExecutionContext) {
|
2021-12-01 22:18:26 -05:00
|
|
|
const skippedGuards = this.reflector.getAllAndOverride<Class<CanActivate>[]>(SKIP_KEY, [
|
|
|
|
context.getHandler(),
|
|
|
|
context.getClass(),
|
|
|
|
]);
|
|
|
|
if (skippedGuards) {
|
|
|
|
const skippedGuard = skippedGuards.find((guard) => this instanceof guard);
|
|
|
|
if (skippedGuard) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2021-11-23 16:04:12 -05:00
|
|
|
const req = context.switchToHttp().getRequest();
|
|
|
|
const authHeader = req.headers.authorization;
|
2021-12-01 22:18:26 -05:00
|
|
|
if (!authHeader) return false;
|
|
|
|
|
2021-11-23 16:04:12 -05:00
|
|
|
const jwt = authHeader.split(' ')[1];
|
|
|
|
try {
|
|
|
|
req.jwtBody = this.jwtService.parseToken(jwt);
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|