forked from Yara724/api
68 lines
1.8 KiB
TypeScript
68 lines
1.8 KiB
TypeScript
import {
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from "@nestjs/common";
|
|
import { JwtService } from "@nestjs/jwt";
|
|
import { AuthGuard } from "@nestjs/passport";
|
|
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
|
|
|
@Injectable()
|
|
export class LocalActorAuthGuard extends AuthGuard("actor") {
|
|
constructor(
|
|
private readonly actorAuthService: ActorAuthService,
|
|
private readonly jwtService: JwtService,
|
|
) {
|
|
super();
|
|
}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest();
|
|
const token = this.extractTokenFromHeader(request);
|
|
const path = request.url;
|
|
|
|
if (!token) {
|
|
if (path === "/actor/login") {
|
|
const loginData = await this.actorAuthService.loginActors(request.body);
|
|
request.user = loginData;
|
|
request.identity = request;
|
|
return true;
|
|
} else {
|
|
throw new UnauthorizedException("Token not found");
|
|
}
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyAsync(token, {
|
|
secret: `${process.env.SECRET}`,
|
|
});
|
|
|
|
if (
|
|
![
|
|
RoleEnum.EXPERT,
|
|
RoleEnum.DAMAGE_EXPERT,
|
|
RoleEnum.COMPANY,
|
|
RoleEnum.FIELD_EXPERT,
|
|
RoleEnum.REGISTRAR,
|
|
].includes(payload.role)
|
|
) {
|
|
throw new UnauthorizedException("User role is not authorized");
|
|
}
|
|
|
|
request.user = payload;
|
|
request.identity = request.user;
|
|
} catch {
|
|
throw new UnauthorizedException("Invalid token");
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private extractTokenFromHeader(request: Request): string | undefined {
|
|
//@ts-ignore
|
|
const [type, token] = request.headers.authorization?.split(" ") ?? [];
|
|
return type === "Bearer" ? token : undefined;
|
|
}
|
|
}
|