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

30 lines
905 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 { 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'),
})
}
2023-02-16 15:43:38 +08:00
async validate(payload: { userId: string }): Promise<User> {
2023-02-16 12:09:48 +08:00
const user = await this.prismaService.user.findUnique({
where: { id: payload.userId },
})
if (!user) {
throw new UnauthorizedException()
}
return user
}
}