src/auth/strategies/jwt.strategy.ts
Properties |
email:
|
Type : string
|
| organizationId |
organizationId:
|
Type : string
|
| role |
role:
|
Type : string
|
| sub |
sub:
|
Type : string
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../prisma/prisma.service';
export interface JwtPayload {
sub: string;
email: string;
role: string;
organizationId: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
configService: ConfigService,
private prisma: PrismaService,
) {
const secret = configService.get<string>('jwt.secret') || configService.get<string>('JWT_SECRET');
if (!secret) {
throw new Error('FATAL: JWT_SECRET environment variable is required.');
}
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: secret,
});
}
async validate(payload: JwtPayload) {
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
role: true,
organizationId: true,
isActive: true,
},
});
if (!user || !user.isActive) {
throw new UnauthorizedException('User not found or deactivated');
}
return user;
}
}