forked from Yara724/api
42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from "@nestjs/common";
|
|
import { JwtService } from "@nestjs/jwt";
|
|
import { Request } from "express";
|
|
|
|
/**
|
|
* Verifies Bearer JWT for platform settings routes. Does not restrict by role;
|
|
* pair with {@link RolesGuard} on handlers.
|
|
*/
|
|
@Injectable()
|
|
export class SettingsJwtGuard implements CanActivate {
|
|
constructor(private readonly jwtService: JwtService) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<Request>();
|
|
const token = this.extractTokenFromHeader(request);
|
|
if (!token) {
|
|
throw new UnauthorizedException("Token not found");
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyAsync(token, {
|
|
secret: `${process.env.JWT_SECRET}`,
|
|
});
|
|
(request as any).user = payload;
|
|
(request as any).identity = payload;
|
|
return true;
|
|
} catch {
|
|
throw new UnauthorizedException("Invalid token");
|
|
}
|
|
}
|
|
|
|
private extractTokenFromHeader(request: Request): string | undefined {
|
|
const [type, token] = request.headers.authorization?.split(" ") ?? [];
|
|
return type === "Bearer" ? token : undefined;
|
|
}
|
|
}
|