29 lines
980 B
TypeScript
29 lines
980 B
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
import { PrismaService } from '../../prisma/prisma.service';
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor(private prisma: PrismaService) {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
ignoreExpiration: false,
|
|
secretOrKey: process.env.JWT_SECRET || 'super-secret',
|
|
});
|
|
}
|
|
|
|
async validate(payload: any) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { id: payload.sub },
|
|
});
|
|
|
|
if (!user) {
|
|
throw new UnauthorizedException('Người dùng không tồn tại hoặc phiên làm việc hết hạn');
|
|
}
|
|
|
|
// Note: We allow anonymous users to pass JWT validation
|
|
// Individual endpoints decide whether to accept anonymous users based on their guard
|
|
return user;
|
|
}
|
|
} |