LocChat/server/providers/guards/auth.guard.ts

29 lines
829 B
TypeScript
Raw Normal View History

2021-11-23 16:04:12 -05:00
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { JwtService } from '../services/jwt.service';
2021-12-03 16:46:44 -05:00
import { GuardUtil } from '../util/guard.util';
2021-11-23 16:04:12 -05:00
@Injectable()
export class AuthGuard implements CanActivate {
2021-12-03 16:46:44 -05:00
constructor(private guardUtil: GuardUtil, private jwtService: JwtService) {}
2021-11-23 16:04:12 -05:00
canActivate(context: ExecutionContext) {
2021-12-03 16:46:44 -05:00
// Handlers and Controllers can both skip this guard in the event that
if (this.guardUtil.shouldSkip(this, context)) {
return true;
2021-12-01 22:18:26 -05:00
}
2021-12-03 16:46:44 -05:00
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;
}
}