Created
October 1, 2018 10:58
-
-
Save ericpkatz/36583d82490a750b8d59e7c7a04dae4c to your computer and use it in GitHub Desktop.
Client Side Thunks for Token Exchange
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
const exchangeTokenForAuth = (history)=> { | |
return (dispatch)=> { | |
const token = window.localStorage.getItem('token'); | |
if(!token){ | |
return | |
} | |
return axios.get('/api/auth', { | |
headers: { | |
authorization: token | |
} | |
}) | |
.then( response => response.data) | |
.then( auth => { | |
dispatch(_setAuth(auth)) | |
if(history){ | |
history.push('/users'); | |
} | |
}) | |
.catch( ex => window.localStorage.removeItem('token')) | |
} | |
} | |
const logout = ()=> { | |
window.localStorage.removeItem('token'); | |
return _setAuth({}); | |
} | |
const login = (credentials, history)=> { | |
return (dispatch)=>{ | |
return axios.post('/api/auth', credentials) | |
.then(response => response.data) | |
.then( data => { | |
window.localStorage.setItem('token', data.token); | |
dispatch(exchangeTokenForAuth(history)); | |
}) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment