29 lines
989 B
TypeScript
29 lines
989 B
TypeScript
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { UsersService } from '../users/users.service';
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor(private readonly usersService: UsersService) {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
ignoreExpiration: false,
|
|
secretOrKey: process.env.JWT_SECRET || 'super-secret-key',
|
|
});
|
|
}
|
|
|
|
async validate(payload: any) {
|
|
// Bypass DB lookup for local admin user to prevent UUID casting errors
|
|
if (payload.sub === '12345678-1234-1234-1234-123456789012') {
|
|
return { id: payload.sub, email: payload.email, role: payload.role };
|
|
}
|
|
|
|
const user = await this.usersService.findById(payload.sub);
|
|
if (!user) {
|
|
throw new UnauthorizedException('کاربر یافت نشد');
|
|
}
|
|
return user;
|
|
}
|
|
}
|