Commit 2c5b792d authored by Diego Iván's avatar Diego Iván
Browse files

creando guard para la autenticacione

parent e482aa1a
Loading
Loading
Loading
Loading
+24 −0
Original line number Diff line number Diff line
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthService } from 'src/shared/service/auth.service';
import { Roles } from '../role.decorator';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private reflector: Reflector,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRole = this.reflector.get(Roles, context.getHandler());
    console.log(requiredRole);

    if (!requiredRole) return true;
    const request = context.switchToHttp().getRequest();
    const { authorization }: any = request.headers;
    if (!authorization) throw new UnauthorizedException('session expired! Please sign In');
    const role = await this.authService.validateToken(authorization);
    if (!requiredRole.includes(role)) throw new UnauthorizedException('Unauthorized access');
    return true;
  }
}