nest-project/src/auth/jwt.strategy.ts

31 lines
951 B
TypeScript
Raw Normal View History

2023-02-16 12:09:48 +08:00
import { Strategy, ExtractJwt } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { User } from '@prisma/client'
import { TokenPayload } from './models/token.model'
import { PrismaService } from 'nestjs-prisma'
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private prismaService: PrismaService,
readonly configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get('JWT_ACCESS_SECRET', 'JWT_ACCESS_SECRET'),
})
}
async validate(payload: TokenPayload): Promise<User> {
const user = await this.prismaService.user.findUnique({
where: { id: payload.userId },
})
if (!user) {
throw new UnauthorizedException()
}
return user
}
}