feat: 优化项目目录结构
This commit is contained in:
47
apps/backend/src/auth/strategies/jwt.strategy.ts
Normal file
47
apps/backend/src/auth/strategies/jwt.strategy.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly userSessionService: UserSessionService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.get<string>('JWT_SECRET', 'tone-page'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
const { userId, sessionId } = payload ?? {};
|
||||
|
||||
const isValidSession = await this.userSessionService.isSessionValid(
|
||||
userId,
|
||||
sessionId,
|
||||
);
|
||||
if (!isValidSession) {
|
||||
throw new UnauthorizedException('登录凭证已过期,请重新登录');
|
||||
}
|
||||
|
||||
const user = await this.userService.findById(userId);
|
||||
if (!user) {
|
||||
throw new BadRequestException('用户不存在');
|
||||
}
|
||||
|
||||
return {
|
||||
...user,
|
||||
sessionId,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user