Advertisement
Guest User

Untitled

a guest
Jun 1st, 2022
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {
  2.     applyDecorators,
  3.     CanActivate,
  4.     ExecutionContext, HttpException, HttpStatus,
  5.     Injectable,
  6.     SetMetadata,
  7.     UnauthorizedException, UseGuards
  8. } from "@nestjs/common";
  9. import {Observable} from "rxjs";
  10. import {JwtService} from "@nestjs/jwt";
  11. import {UserRolesEnum} from "../user/enums/user-roles.enum";
  12. import {Reflector} from "@nestjs/core";
  13.  
  14. export function Auth(...roles: string[]) {
  15.     return applyDecorators(
  16.         SetMetadata('roles', roles),
  17.         UseGuards(AuthGuard)
  18.     );
  19. }
  20.  
  21. @Injectable()
  22. class AuthGuard implements CanActivate {
  23.     constructor(private jwtService: JwtService,
  24.                 private reflector: Reflector) {}
  25.  
  26.     canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
  27.         const req = context.switchToHttp().getRequest()
  28.         try {
  29.            
  30.             //Верефикация JWT токена
  31.             const authHeader = req.headers.authorization;
  32.             const bearer = authHeader.split(' ')[0]
  33.             const token = authHeader.split(' ')[1]
  34.  
  35.             if (bearer !== 'Bearer' || !token) {
  36.                 throw new UnauthorizedException({message: 'Пользователь не авторизован'})
  37.             }
  38.  
  39.             const user = this.jwtService.verify(token);
  40.             req.user = user;
  41.            
  42.             //Проверка роли
  43.             try {
  44.                 const roles = this.reflector.get<string[]>('roles', context.getHandler());
  45.                 if (!roles) {
  46.                     return true;
  47.                 }
  48.  
  49.                 return user.roles.some(role => roles.includes(role.value));
  50.             } catch (e) {
  51.                 throw new HttpException( 'Нет доступа', HttpStatus.FORBIDDEN)
  52.             }
  53.            
  54.             return true;
  55.         } catch (e) {
  56.             throw new UnauthorizedException({message: 'Пользователь не авторизован'})
  57.         }
  58.     }
  59.  
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement