Files
canina/backend/src/auth/jwt.strategy.ts
T

75 lines
3.0 KiB
TypeScript

import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UsersService } from "../users/users.service";
import { assertPrincipalActive } from "./stage-test-principal";
import { getJwtSecret } from "./auth.constants";
import { RedisService } from "../redis/redis.service";
import type { Request } from "express";
export interface JwtPayload {
sub: string;
email?: string;
role?: string;
phoneNumber?: string;
stageTestSession?: string;
stageTestGeneration?: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly usersService: UsersService,
private readonly redisService: RedisService,
) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
(req: Request) => {
if (!req || !req.headers) return null;
// Support parsed cookie object or raw Cookie header
const cookieHeader = req.headers.cookie;
if (cookieHeader) {
const match = cookieHeader.match(/(?:^|;\s*)accessToken=([^;]+)/);
if (match) return decodeURIComponent(match[1]);
}
return (req as any).cookies?.accessToken || null;
},
]),
ignoreExpiration: false,
secretOrKey: getJwtSecret(),
passReqToCallback: true,
});
}
async validate(req: Request, payload: JwtPayload) {
let rawToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
if (!rawToken && req.headers?.cookie) {
const match = req.headers.cookie.match(/(?:^|;\s*)accessToken=([^;]+)/);
if (match) rawToken = decodeURIComponent(match[1]);
}
if (rawToken) {
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
if (isBlacklisted) {
throw new UnauthorizedException(
"این توکن باطل شده است. لطفاً مجدداً وارد شوید",
);
}
}
const user = await this.usersService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException("کاربر یافت نشد");
}
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
if (user.stageTestSession) {
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
const path = req.originalUrl?.split('?')[0] || '';
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure)$/.test(path));
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
}
return user;
}
}