All files / src/authzero/utils/jwt jwtValidator.ts

100% Statements 22/22
100% Branches 4/4
100% Functions 4/4
100% Lines 19/19

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 5412x 12x   12x             12x                               12x 55x     4x   4x 1x     3x 1x   2x 2x     55x 5x 5x 1x   4x 4x        
import { Injectable } from '@nestjs/common';
import JwtLib from './jwtLib';
 
export const JWT_ERROR = {
  INVALID_ISSUER: 'jwt issuer invalid',
  SIGNING_KEY_NOT_FOUND: 'Unable to find a signing key',
  TOKEN_EXPIRED: 'TokenExpiredError',
  MALFORMED_TOKEN: 'JsonWebTokenError',
};
 
export const JWT_CHECK_RESULT = {
  ERROR_INVALID_ISSUER: { code: 1, errorMessage: 'ERROR_INVALID_ISSUER' },
  ERROR_TOKEN_EXPIRED: {
    code: 2,
    errorMessage: 'ERROR_TOKEN_EXPIRED',
  },
  ERROR_MALFORMED_TOKEN: { code: 3, errorMessage: 'ERROR_MALFORMED_TOKEN' },
  ERROR_UNHANDLED: { code: -1, errorMessage: 'ERROR_UNHANDLED' },
 
  VALID_TOKEN: {
    code: 0,
    errorMessage: '',
  },
};
 
@Injectable()
export default class JwtValidator {
  constructor(private readonly jwtLib: JwtLib) {}
 
  private getJWTError(e: Error) {
    const errorMessage = `${e.name}:${e.message}`;
 
    if (errorMessage.includes(JWT_ERROR.TOKEN_EXPIRED)) {
      return JWT_CHECK_RESULT.ERROR_TOKEN_EXPIRED;
    }
 
    if (errorMessage.includes(JWT_ERROR.MALFORMED_TOKEN)) {
      return JWT_CHECK_RESULT.ERROR_MALFORMED_TOKEN;
    }
    JWT_CHECK_RESULT.ERROR_UNHANDLED.errorMessage = errorMessage;
    return JWT_CHECK_RESULT.ERROR_UNHANDLED;
  }
 
  validate = async (accessToken: string) => {
    try {
      await this.jwtLib.decodeJwt(accessToken);
      return JWT_CHECK_RESULT.VALID_TOKEN;
    } catch (e) {
      console.error(e)
      return this.getJWTError(e);
    }
  };
}