From 41454e3903a0be7e5a3dbdd76e3387ba95f22295 Mon Sep 17 00:00:00 2001 From: doktordirk Date: Fri, 27 May 2016 09:28:06 +0200 Subject: [PATCH] fix(authentication): consistent throw if token not found --- src/authentication.js | 8 ++++++-- test/authentication.spec.js | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/authentication.js b/src/authentication.js index b6f542a..55b2d48 100644 --- a/src/authentication.js +++ b/src/authentication.js @@ -186,8 +186,12 @@ export class Authentication { } if (typeof responseTokenProp === 'object') { - const tokenRootData = tokenRoot && tokenRoot.split('.').reduce(function(o, x) { return o[x]; }, responseTokenProp); - return tokenRootData ? tokenRootData[tokenName] : responseTokenProp[tokenName]; + const tokenRootData = tokenRoot && tokenRoot.split('.').reduce((o, x) => o[x], responseTokenProp); + const token = tokenRootData ? tokenRootData[tokenName] : responseTokenProp[tokenName]; + + if (!token) throw new Error('Token not found in response'); + + return token; } const token = response[tokenName] === undefined ? null : response[tokenName]; diff --git a/test/authentication.spec.js b/test/authentication.spec.js index 3e4ed8e..da6252f 100644 --- a/test/authentication.spec.js +++ b/test/authentication.spec.js @@ -306,6 +306,15 @@ describe('Authentication', () => { )).toBe('some'); }); + it('Should throw if token not found in nested', () => { + const fail = () => authentication.getTokenFromResponse( + {tokenProp: {wrongTokenName: 'some'}}, + 'tokenProp', + 'tokenName' + ); + expect(fail).toThrow(); + }); + it('Should return token if response has a string in tokenName in tokenRoot of tokenProp', () => { expect(authentication.getTokenFromResponse( {tokenProp: {tokenRoot1: {tokenRoot2: {tokenName: 'some'}}}},