Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { BadRequestException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
- import { PassportStrategy } from '@nestjs/passport';
- import { Strategy, ExtractJwt } from 'passport-jwt';
- import * as process from "process";
- import { JwtPayload } from './auth/auth.service';
- import { UsersService } from '../../shared/services/users/users.service';
- import { JWT_SECRET_KEY_TOKEN } from '../auth.tokens';
- @Injectable()
- export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
- constructor(
- private userService: UsersService,
- @Inject(JWT_SECRET_KEY_TOKEN) private secretToken: string
- ) {
- super({
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
- secretOrKey: secretToken,
- });
- }
- async validate(payload: JwtPayload, done: (err?, user?) => void) {
- try {
- const user = (await this.userService.findByEmail(payload.email))[0];
- if (!user) {
- throw new BadRequestException('User doesn\'t exists');
- }
- // вторым параметром передается user, его можно получить в контроллере через request.user
- done(null, {...payload, ...user});
- } catch (err) {
- throw new UnauthorizedException('unauthorized', err.message);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement