Добавлена возможность заменять файл с расписанием.

Добалена возможность давать доступ к end-point'ам только определённым ролям.

Чуть-чуть меньше спагетти в объявлениях модулей.
This commit is contained in:
2024-10-03 01:49:23 +04:00
parent d18a6764c9
commit 32e06350ad
20 changed files with 361 additions and 46 deletions

View File

@@ -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;
}