All files / src/crypto/token-signer decode-token.ts

100% Statements 19/19
100% Branches 5/5
100% Functions 2/2
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  42x   42x     22x   20x 20x 20x 20x     20x         2x 2x 1x   1x 1x 1x     1x 1x 1x 1x     1x              
import { TokenInterface, TokenInterfaceEncodedObject } from './types';
import base64url from './base64url';
 
export function decodeToken(
  token: string | TokenInterface | TokenInterfaceEncodedObject
): TokenInterface | undefined {
  if (typeof token === 'string') {
    // decompose the token into parts
    const tokenParts = token.split('.');
    const header = JSON.parse(base64url.decode(tokenParts[0]));
    const payload = JSON.parse(base64url.decode(tokenParts[1]));
    const signature = tokenParts[2];
 
    // return the token object
    return {
      header,
      payload,
      signature,
    };
  } else if (typeof token === 'object') {
    if (typeof token.payload !== 'string') {
      throw new Error('Expected token payload to be a base64 or json string');
    }
    let payload = token.payload;
    if (token.payload[0] !== '{') {
      payload = base64url.decode(payload);
    }
 
    const allHeaders: any = [];
    (token.header as any).map((headerValue: string) => {
      const header = JSON.parse(base64url.decode(headerValue));
      allHeaders.push(header);
    });
 
    return {
      header: allHeaders,
      payload: JSON.parse(payload),
      signature: token.signature,
    };
  }
}