All files / src/core Jwt.js

96.55% Statements 28/29
90% Branches 9/10
100% Functions 7/7
96.15% Lines 25/26

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75          5x   5x 43x 43x   43x       43x             2860x     43x         44x   44x 44x   44x       6x       1x       3x       2x       44x   44x 1x       43x 43x   1x     42x 42x       5x  
'use strict';
 
// atob is not available in React Native
// https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging
 
const base64Charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
 
const decodeBase64 = input => {
  const str = input.replace(/=+$/, '');
  let output = '';
 
  Iif (str.length % 4 === 1) {
    throw new Error('Malformed base64 string.');
  }
 
  for (let bc = 0, bs = 0, buffer, i = 0;
    buffer = str.charAt(i++); // eslint-disable-line no-cond-assign
 
    ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4)
      ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6))
      : 0
  ) {
    buffer = base64Charset.indexOf(buffer);
  }
 
  return output;
};
 
class Jwt {
  constructor (encodedJwt) {
    this._encodedJwt = encodedJwt;
 
    this._userId = null;
    this._expiresAt = null;
 
    this._decode();
  }
 
  get encodedJwt () {
    return this._encodedJwt;
  }
 
  get userId () {
    return this._userId;
  }
 
  get expiresAt () {
    return this._expiresAt;
  }
 
  get expired () {
    return Date.now() > this.expiresAt;
  }
 
  _decode () {
    const payloadRaw = this._encodedJwt.split('.')[1];
 
    if (!payloadRaw) {
      throw new Error('Invalid JWT format');
    }
 
    let payload;
    try {
      payload = JSON.parse(decodeBase64(payloadRaw));
    } catch (error) {
      throw new Error('Invalid JSON payload for JWT');
    }
 
    this._userId = payload._id;
    this._expiresAt = payload.exp;
  }
}
 
module.exports = Jwt;