| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import { ExtractJwt, Strategy } from 'passport-jwt'
- import { PassportStrategy } from '@nestjs/passport'
- import { Inject, Injectable, Logger, UnauthorizedException } from '@nestjs/common'
- import jwtconfig from './jwt.config'
- import { ConfigType } from '@nestjs/config'
- import { UsersService } from 'src/users/users.service'
- import { Role } from 'src/model/role.enum'
- @Injectable()
- export class JwtStrategy extends PassportStrategy(Strategy) {
- constructor(
- @Inject(jwtconfig.KEY)
- private readonly jwtConfiguration: ConfigType<typeof jwtconfig>,
- private readonly userService: UsersService
- ) {
- super({
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
- ignoreExpiration: false,
- secretOrKey: jwtConfiguration.secret
- })
- }
- async validate(payload: any) {
- const user = await this.userService.findById(payload.sub)
- if (!user) {
- throw new UnauthorizedException('User not found')
- }
- // if (!(payload.roles.includes(Role.Admin) || payload.roles.includes(Role.Api))) {
- // if (!user.iat) {
- // throw new UnauthorizedException('用户身份已过期,请重新登录')
- // }
- // if (payload.iat < user.iat) {
- // throw new UnauthorizedException('用户身份已过期,请重新登录')
- // }
- // }
- return {
- id: payload.sub,
- userId: payload.sub,
- username: payload.username,
- roles: payload.roles
- }
- }
- }
|