traintrape-moi/server/src/auth/jwt.strategy.ts
2024-12-07 13:06:15 +01:00

24 lines
722 B
TypeScript

import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { JWT_SECRET } from './auth.module'
import { UsersService } from 'src/users/users.service'
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private usersService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: JWT_SECRET,
})
}
async validate(payload: { userId: number }) {
const user = await this.usersService.findOne(payload.userId)
if (!user) {
throw new UnauthorizedException()
}
return user
}
}