- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
65 lines
2.1 KiB
TypeScript
65 lines
2.1 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 { 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;
|
|
}
|
|
|
|
@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("کاربر یافت نشد");
|
|
}
|
|
return user;
|
|
}
|
|
}
|