All files / src/__tests__ auth_client.ts

100% Statements 100/100
100% Branches 0/0
100% Functions 28/28
100% Lines 89/89
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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 2071x         1x 1x 1x         1x 1x 1x   7x 7x   5x                 1x 1x     1x 1x 1x       1x 1x     1x 2x     1x 1x     1x 1x     1x 13x     1x 1x 1x               1x 1x     1x 1x   1x       1x 1x       1x 1x       1x 1x 1x     1x 1x   1x   1x     1x 1x   1x 1x 1x     1x 1x 1x 1x               1x 1x   1x 1x 1x     1x 1x 1x 1x     1x 1x     1x 1x 1x     1x 1x               1x   1x         1x   1x       1x 1x                   1x 1x   1x     1x   1x 1x 1x       1x 1x   1x     1x   1x 1x 1x          
import express from 'express';
import { Server } from 'http';
import jwtDecode from 'jwt-decode';
import { AuthClient, HttpConnector } from '..';
 
describe('Auth Client', () => {
  const PORT = 5001;
  const URL = 'http://localhost:' + PORT;
 
  let server: Server;
 
  const accessToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1SWQiOiJ1c2VyXzEyMyIsImNJZCI6ImNvbXBhbnlfMTIzIiwic2NvcGUiOiJhOnI6dyIsImlhdCI6MTUxOTA2MjY4MH0.FPnQLylqy7hfTLULsNDLNhaswFD3HI7zxRt6G-u3h9s';
  const app = express();
  const authClient = new AuthClient({
    decode(at) {
      try {
        return jwtDecode(at);
      } catch {
        return;
      }
    },
    fetchConnector: new HttpConnector({
      createAccessTokenUrl: URL + '/accessToken',
      logoutUrl: URL + '/logout'
    })
  });
 
  app.get('/accessToken', (_req, res) => {
    res.json({ accessToken: 'newToken' });
  });
 
  app.get('/accessToken/late', (_req, res) => {
    setTimeout(() => {
      res.json({ accessToken: Math.random().toString(36) });
    }, 500);
  });
 
  app.get('/logout', (_req, res) => {
    res.json({ done: true });
  });
 
  app.get('/error', (_req, res) => {
    res.status(400).json({ message: 'failed' });
  });
 
  beforeAll(() => {
    server = app.listen(PORT);
  });
 
  afterAll(() => {
    server.close();
  });
 
  afterEach(() => {
    authClient.removeAccessToken();
  });
 
  describe('Can use custom options', () => {
    it('Can use custom cookies and cookie options', () => {
      const client = new AuthClient({
        decode: authClient.decode,
        fetchConnector: authClient.fetch,
        cookie: 'custom',
        refreshTokenCookie: 'custom', // this one is private
        cookieOptions: { secure: false }
      });
 
      expect(client.cookie).toBe('custom');
      expect(client.cookieOptions).toEqual({ secure: false });
    });
 
    it('Can use a function in cookieOptions', () => {
      expect.assertions(2);
 
      const client = new AuthClient({
        decode: authClient.decode,
        fetchConnector: authClient.fetch,
        cookieOptions(at?: string) {
          expect(at).toBe(accessToken);
          return { secure: false };
        }
      });
 
      expect(typeof client.cookieOptions).toBe('function');
      client.setAccessToken(accessToken);
    });
  });
 
  it('Adds an accessToken to cookies', () => {
    expect(authClient.setAccessToken('')).toBeUndefined();
    expect(authClient.setAccessToken(accessToken)).toBe(accessToken);
  });
 
  it('Returns the accessToken from cookies', () => {
    expect(authClient.getAccessToken()).toBeUndefined();
 
    authClient.setAccessToken(accessToken);
 
    expect(authClient.getAccessToken()).toBe(accessToken);
  });
 
  it('Removes the accessToken', () => {
    authClient.setAccessToken(accessToken);
 
    expect(authClient.getAccessToken()).toBe(accessToken);
    expect(authClient.removeAccessToken()).toBeUndefined();
    expect(authClient.getAccessToken()).toBeUndefined();
  });
 
  it('Decodes an accessToken', () => {
    expect(authClient.decodeAccessToken('')).toBeNull();
    expect(authClient.decodeAccessToken('invalid')).toBeNull();
    expect(authClient.decodeAccessToken(accessToken)).toEqual({
      uId: 'user_123',
      cId: 'company_123',
      scope: 'a:r:w',
      iat: 1519062680
    });
  });
 
  it('Logouts', async () => {
    authClient.setAccessToken(accessToken);
 
    expect(authClient.getAccessToken()).toBe(accessToken);
    expect(await authClient.logout()).toEqual({ done: true });
    expect(authClient.getAccessToken()).toBeUndefined();
  });
 
  describe('fetch a new accessToken', () => {
    it('Should use the current token if its still valid', async () => {
      authClient.setAccessToken(accessToken);
      expect(await authClient.fetchAccessToken()).toBe(accessToken);
    });
 
    it('Should not do anything if no current token is present', async () => {
      expect(await authClient.fetchAccessToken()).toBeUndefined();
    });
 
    it('Should return a new token', async () => {
      authClient.setAccessToken('invalid');
      expect(await authClient.fetchAccessToken()).toBe('newToken');
    });
 
    it('Should use the same fetch when called multiple times', async () => {
      const client = new AuthClient({
        decode: authClient.decode,
        fetchConnector: new HttpConnector({
          createAccessTokenUrl: URL + '/accessToken/late',
          logoutUrl: 'x'
        })
      });
 
      client.setAccessToken('x');
 
      const tokens = await Promise.all([
        client.fetchAccessToken(),
        client.fetchAccessToken(),
        client.fetchAccessToken()
      ]);
      const firstToken = tokens[0];
 
      expect(tokens).toEqual([firstToken, firstToken, firstToken]);
    });
  });
 
  describe('Throws an error', () => {
    const client = new AuthClient({
      decode() {
        // this will make decode fails
      },
      fetchConnector: new HttpConnector({
        createAccessTokenUrl: URL + '/error',
        logoutUrl: URL + '/error'
      })
    });
 
    it('When the logout fails', async () => {
      client.setAccessToken(accessToken);
 
      expect.assertions(3);
 
      try {
        await client.logout();
      } catch (e) {
        expect(client.getAccessToken()).toBe(accessToken);
        expect(e.name).toBe('FetchError');
        expect(e.res).toBeDefined();
      }
    });
 
    it('When a fetch for a new accessToken fails', async () => {
      client.setAccessToken(accessToken);
 
      expect.assertions(3);
 
      try {
        await client.fetchAccessToken();
      } catch (e) {
        expect(client.getAccessToken()).toBe(accessToken);
        expect(e.name).toBe('FetchError');
        expect(e.res).toBeDefined();
      }
    });
  });
});