summaryrefslogtreecommitdiff
path: root/server/providers/guards/auth.guard.ts
blob: 722094be0e4e68de34f9d855baec03324e29c6dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { JwtService } from '../services/jwt.service';
import { GuardUtil } from '../util/guard.util';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private guardUtil: GuardUtil, private jwtService: JwtService) {}

  canActivate(context: ExecutionContext) {
    // Handlers and Controllers can both skip this guard in the event that
    if (this.guardUtil.shouldSkip(this, context)) {
      return true;
    }

    const req = context.switchToHttp().getRequest();
    const authHeader = req.headers.authorization;
    if (!authHeader) return false;

    const jwt = authHeader.split(' ')[1];
    try {
      req.jwtBody = this.jwtService.parseToken(jwt);
    } catch (e) {
      return false;
    }

    return true;
  }
}