mirror of
https://github.com/n08i40k/schedule-parser-next.git
synced 2025-12-06 09:47:46 +03:00
1.2.0
Добавлена возможность заменять файл с расписанием. Добалена возможность давать доступ к end-point'ам только определённым ролям. Чуть-чуть меньше спагетти в объявлениях модулей.
This commit is contained in:
@@ -1,18 +1,23 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { AuthRoles } from "../auth-role/auth-role.decorator";
|
||||
import { isJWT } from "class-validator";
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
public static extractTokenFromRequest(req: Request): string {
|
||||
@@ -28,18 +33,27 @@ export class AuthGuard implements CanActivate {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = AuthGuard.extractTokenFromRequest(request);
|
||||
|
||||
if (!token)
|
||||
try {
|
||||
if (
|
||||
!(await this.jwtService.verifyAsync(token)) ||
|
||||
!(await this.usersService.contains({ accessToken: token }))
|
||||
) {
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
throw new Error();
|
||||
}
|
||||
} catch {
|
||||
throw new UnauthorizedException("Указан неверный токен!");
|
||||
}
|
||||
let jwtUser: { id: string } | null = null;
|
||||
|
||||
if (
|
||||
!isJWT(token) ||
|
||||
!(jwtUser = await this.jwtService
|
||||
.verifyAsync(token)
|
||||
.catch(() => null))
|
||||
)
|
||||
throw new UnauthorizedException();
|
||||
|
||||
const user = await this.usersService.findUnique({ id: jwtUser.id });
|
||||
if (!user || user.accessToken !== token)
|
||||
throw new UnauthorizedException();
|
||||
|
||||
const acceptableRoles = this.reflector.get(
|
||||
AuthRoles,
|
||||
context.getHandler(),
|
||||
);
|
||||
|
||||
if (acceptableRoles != null && !acceptableRoles.includes(user.role))
|
||||
throw new ForbiddenException();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user