# All files / modules/auth/strategies jwt.strategy.ts

100% Statements 15/15
66.66% Branches 2/3
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    401x
    1x
    1x
    1x
    1x

    1x

    3x
    3x

    3x

    3x

    3x
    1x

    2x

     import { Injectable, UnauthorizedException } from '@nestjs/common';
    import { PassportStrategy } from '@nestjs/passport';
    import { ExtractJwt, Strategy } from 'passport-jwt';
    import { ConfigService } from '@nestjs/config';
    import { AuthService, JwtPayload } from '../services/auth.service';

    export interface RequestUser {
      id: string;
      email: string;
      tenant_id: string;
    }

    @Injectable()
    export class JwtStrategy extends PassportStrategy(Strategy) {
      constructor(
        private readonly configService: ConfigService,
        private readonly authService: AuthService,
      ) {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          ignoreExpiration: false,
          secretOrKey: configService.get<string>('jwt.secret') || 'default-secret-change-in-production',
        });
      }

      async validate(payload: JwtPayload): Promise<RequestUser> {
        const user = await this.authService.validateUser(payload.sub);

        if (!user) {
          throw new UnauthorizedException('Usuario no encontrado o inactivo');
        }

        return {
          id: user.id,
          email: user.email,
          tenant_id: user.tenant_id,
        };
      }
    }