auth.guard.ts 1.14 KB
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class MixAuthGuard implements CanActivate {
  constructor(
    // private jwtService: JwtService,
    private action,
  ) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const jwtService = new JwtService({});
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      await jwtService.verify(token, { secret: process.env.TOKEN_SECRET });
      const payload = await jwtService.decode(token);
      if (payload.type !== this.action) {
        throw new UnauthorizedException();
      }
    } catch (error: Error | any) {
      throw new UnauthorizedException(error.message);
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}