39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { User, UserStatus } from '../../users/user.entity';
|
|
import { JwtPayload } from '../interfaces/jwt-payload.interface';
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor(
|
|
private readonly configService: ConfigService,
|
|
@InjectRepository(User)
|
|
private readonly userRepository: Repository<User>,
|
|
) {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
ignoreExpiration: false,
|
|
secretOrKey: configService.get<string>(
|
|
'JWT_SECRET',
|
|
'your-secret-key-change-in-production',
|
|
),
|
|
});
|
|
}
|
|
|
|
async validate(payload: JwtPayload): Promise<User> {
|
|
const user = await this.userRepository.findOne({
|
|
where: { id: payload.sub },
|
|
});
|
|
|
|
if (!user || user.status !== UserStatus.ACTIVE) {
|
|
throw new UnauthorizedException('用户不存在或已被禁用');
|
|
}
|
|
|
|
return user;
|
|
}
|
|
}
|