jwt.strategy.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { ExtractJwt, Strategy } from 'passport-jwt'
  2. import { PassportStrategy } from '@nestjs/passport'
  3. import { Inject, Injectable, Logger, UnauthorizedException } from '@nestjs/common'
  4. import jwtconfig from './jwt.config'
  5. import { ConfigType } from '@nestjs/config'
  6. import { UsersService } from 'src/users/users.service'
  7. import { Role } from 'src/model/role.enum'
  8. @Injectable()
  9. export class JwtStrategy extends PassportStrategy(Strategy) {
  10. constructor(
  11. @Inject(jwtconfig.KEY)
  12. private readonly jwtConfiguration: ConfigType<typeof jwtconfig>,
  13. private readonly userService: UsersService
  14. ) {
  15. super({
  16. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  17. ignoreExpiration: false,
  18. secretOrKey: jwtConfiguration.secret
  19. })
  20. }
  21. async validate(payload: any) {
  22. const user = await this.userService.findById(payload.sub)
  23. if (!user) {
  24. throw new UnauthorizedException('User not found')
  25. }
  26. // if (!(payload.roles.includes(Role.Admin) || payload.roles.includes(Role.Api))) {
  27. // if (!user.iat) {
  28. // throw new UnauthorizedException('用户身份已过期,请重新登录')
  29. // }
  30. // if (payload.iat < user.iat) {
  31. // throw new UnauthorizedException('用户身份已过期,请重新登录')
  32. // }
  33. // }
  34. return {
  35. id: payload.sub,
  36. userId: payload.sub,
  37. username: payload.username,
  38. roles: payload.roles
  39. }
  40. }
  41. }