Created
April 15, 2018 11:54
-
-
Save ephes/6b5f9f2bcf9f62e2b49e4eee2ffe337a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jwtDecode from 'jwt-decode' | |
import * as auth from '../actions/auth' | |
function getInitialState() { | |
let initialState = { | |
access: undefined, | |
refresh: undefined, | |
errors: {} | |
} | |
const authStorage = localStorage.getItem('persist:polls') | |
if (!(authStorage == null)) { | |
const token = JSON.parse(JSON.parse(authStorage)['auth']) | |
if (!(token.access === undefined)) { | |
initialState.access = token.access.token | |
initialState.refresh = { | |
token: token.refresh.token, | |
exp: token.refresh.exp | |
} | |
} | |
} | |
return initialState | |
} | |
export default (state = getInitialState(), action) => { | |
switch (action.type) { | |
case auth.LOGIN_SUCCESS: | |
return { | |
access: { | |
token: action.payload.access, | |
...jwtDecode(action.payload.access) | |
}, | |
refresh: { | |
token: action.payload.refresh, | |
...jwtDecode(action.payload.refresh) | |
}, | |
errors: {} | |
} | |
case auth.TOKEN_RECEIVED: | |
return { | |
...state, | |
access: { | |
token: action.payload.access, | |
...jwtDecode(action.payload.access) | |
} | |
} | |
case auth.LOGIN_FAILURE: | |
case auth.TOKEN_FAILURE: | |
return { | |
access: undefined, | |
refresh: undefined, | |
errors: action.payload.response || {'non_field_errors': action.payload.statusText} | |
} | |
default: | |
return state | |
} | |
} | |
export function accessToken (state) { | |
if (state.access) { | |
return state.access.token | |
} | |
} | |
export function isAccessTokenExpired (state) { | |
if (state.access && state.access.exp) { | |
return 1000 * state.access.exp - (new Date()).getTime() < 5000 | |
} | |
return true | |
} | |
export function refreshToken (state) { | |
if (state.refresh) { | |
return state.refresh.token | |
} | |
} | |
export function isRefreshTokenExpired (state) { | |
if (state.refresh && state.refresh.exp) { | |
return 1000 * state.refresh.exp - (new Date()).getTime() < 5000 | |
} | |
return true | |
} | |
export function isAuthenticated (state) { | |
return !isRefreshTokenExpired(state) | |
} | |
export function errors (state) { | |
return state.errors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment