Files
CRM_Montzar/apps/api/src/platform/platform-jwt.strategy.ts
T
2026-09-19 22:42:51 +03:30

60 lines
1.5 KiB
TypeScript

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from '../prisma/prisma.service';
export type PlatformJwtPayload = {
sub: string;
typ?: string;
};
export type PlatformActor = {
platformAdminId: string;
mobile: string | null;
email: string | null;
fullName: string;
};
@Injectable()
export class PlatformJwtStrategy extends PassportStrategy(
Strategy,
'platform-jwt',
) {
constructor(
config: ConfigService,
private readonly prisma: PrismaService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get<string>('JWT_SECRET') ?? 'dev-secret',
});
}
async validate(payload: PlatformJwtPayload): Promise<PlatformActor> {
if (payload.typ !== 'platform-admin' || !payload.sub) {
throw new UnauthorizedException();
}
const admin = await this.prisma.platformAdmin.findUnique({
where: { id: payload.sub },
select: {
id: true,
mobile: true,
email: true,
fullName: true,
isActive: true,
},
});
if (!admin || admin.isActive === false) {
throw new UnauthorizedException();
}
return {
platformAdminId: admin.id,
mobile: admin.mobile,
email: admin.email,
fullName: admin.fullName,
};
}
}