From afd6c3c30034fac2d7457dc87b26d61b36971eb3 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Mon, 20 May 2019 16:32:07 +0300 Subject: [PATCH] Fixes ACCOUNTS-5FJ. Use common getJwtPayloads function to decode jwt payloads --- src/components/accounts/actions.js | 11 +++++------ src/functions.js | 7 +++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/components/accounts/actions.js b/src/components/accounts/actions.js index e163fef..ec7759b 100644 --- a/src/components/accounts/actions.js +++ b/src/components/accounts/actions.js @@ -1,6 +1,6 @@ // @flow import type { Account, State as AccountsState } from './reducer'; -import { getJwtPayload } from 'functions'; +import { getJwtPayloads } from 'functions'; import { sessionStorage } from 'services/localStorage'; import { validateToken, requestToken, logout } from 'services/api/authentication'; import { relogin as navigateToLogin } from 'components/auth/actions'; @@ -116,8 +116,7 @@ export function authenticate(account: Account | { } function findAccountIdFromToken(token: string): number { - const encodedPayloads = token.split('.')[1]; - const { sub, jti }: { sub: string, jti: number } = JSON.parse(atob(encodedPayloads)); + const { sub, jti } = getJwtPayloads(token); // sub has the format "ely|{accountId}", so we must trim "ely|" part if (sub) { return parseInt(sub.substr(4), 10); @@ -144,10 +143,10 @@ export function ensureToken() { const {token} = getActiveAccount(getState()) || {}; try { - const SAFETY_FACTOR = 300; // ask new token earlier to overcome time dissynchronization problem - const jwt = getJwtPayload(token); + const SAFETY_FACTOR = 300; // ask new token earlier to overcome time desynchronization problem + const { exp } = getJwtPayloads(token); - if (jwt.exp - SAFETY_FACTOR < Date.now() / 1000) { + if (exp - SAFETY_FACTOR < Date.now() / 1000) { return dispatch(requestNewToken()); } } catch (err) { diff --git a/src/functions.js b/src/functions.js index 0c37edf..6bd7160 100644 --- a/src/functions.js +++ b/src/functions.js @@ -66,9 +66,12 @@ export { default as debounce } from 'debounce'; * * @return {object} - decoded jwt payload */ -export function getJwtPayload(jwt: string): Object { +export function getJwtPayloads(jwt: string): { + sub: string; + jti: number; + exp: number; +} { const parts = (jwt || '').split('.'); - if (parts.length !== 3) { throw new Error('Invalid jwt token'); }