This commit is contained in:
2024-09-06 23:13:44 +04:00
parent 2b2018c317
commit 31906fbbd1
29 changed files with 2061 additions and 90 deletions

43
src/auth/auth.guard.ts Normal file
View File

@@ -0,0 +1,43 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
public static extractTokenFromRequest(req: Request): string | null {
const [type, token] = req.headers.authorization?.split(" ") ?? [];
return type === "Bearer" ? token : null;
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = AuthGuard.extractTokenFromRequest(request);
if (!token) throw new UnauthorizedException("Не указан токен!");
try {
if (
!(await this.jwtService.verifyAsync(token)) ||
!(await this.usersService.has({ access_token: token }))
) {
// noinspection ExceptionCaughtLocallyJS
throw new Error();
}
} catch {
throw new UnauthorizedException("Указан неверный токен!");
}
return true;
}
}