Do not rely on isGuest in auth middleware. Instead use token availability

This commit is contained in:
SleepWalker 2016-08-10 22:29:16 +03:00
parent 54664044eb
commit a504981407
3 changed files with 16 additions and 26 deletions

View File

@ -8,7 +8,7 @@ export default function factory(store, stopLoading) {
// do bsod for 500/404 errors
request.addMiddleware({
catch(resp) {
if (resp && [500, 404].indexOf(resp.originalResponse.status) > -1) {
if (resp && resp.originalResponse && [500, 404].indexOf(resp.originalResponse.status) > -1) {
dispatchBsod();
}

View File

@ -13,19 +13,23 @@ import {updateUser, logout} from '../actions';
export default function refreshTokenMiddleware({dispatch, getState}) {
return {
before(data) {
const {isGuest, refreshToken, token} = getState().user;
const {refreshToken, token} = getState().user;
const isRefreshTokenRequest = data.url.includes('refresh-token');
if (isGuest || isRefreshTokenRequest) {
if (!token || isRefreshTokenRequest) {
return data;
}
try {
const SAFETY_FACTOR = 60; // ask new token earlier to overcome time dissynchronization problem
const jwt = getJWTPayload(token);
if (jwt.exp - SAFETY_FACTOR < Date.now() / 1000) {
return requestAccessToken(refreshToken, dispatch).then(() => data);
}
} catch (err) {
dispatch(logout());
}
return data;
},

View File

@ -32,8 +32,7 @@ describe('refreshTokenMiddleware', () => {
getState.returns({
user: {
token: expiredToken,
refreshToken,
isGuest: false
refreshToken
}
});
@ -55,15 +54,11 @@ describe('refreshTokenMiddleware', () => {
});
});
it('should not be applied for guests', () => {
it('should not be applied if no token', () => {
getState.returns({
user: {
isGuest: true
}
user: {}
});
authentication.requestToken.returns(Promise.resolve({token: validToken}));
const data = {url: 'foo'};
const resp = middleware.before(data);
@ -77,8 +72,6 @@ describe('refreshTokenMiddleware', () => {
user: {}
});
authentication.requestToken.returns(Promise.resolve({token: validToken}));
const data = {url: '/refresh-token'};
const resp = middleware.before(data);
@ -88,13 +81,13 @@ describe('refreshTokenMiddleware', () => {
});
xit('should update user with new token'); // TODO: need a way to test, that action was called
xit('should logout if invalid token'); // TODO: need a way to test, that action was called
xit('should logout if token request failed', () => {
getState.returns({
user: {
token: expiredToken,
refreshToken,
isGuest: false
refreshToken
}
});
@ -117,13 +110,6 @@ describe('refreshTokenMiddleware', () => {
const restart = sinon.stub().named('restart');
const data = {
url: 'foo',
options: {
headers: {}
}
};
authentication.requestToken.returns(Promise.resolve({token: validToken}));
return middleware.catch({