Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // parse the token and extract user data from it
- const setUserDataAction = token => {
- return async dispatch => {
- try {
- const { id, fullname, exp } = await jwt_decode(token);
- return dispatch({ type: SET_USER_DATA, payload: { id, fullname, exp } });
- } catch (e) {
- console.log(e); // InvalidTokenError
- await dispatch(setAlertAction('warning', 'Something went wrong, please try again later'));
- return dispatch({ type: LOGIN_FAIL });
- }
- };
- };
- export const checkAuthTokenAction = () => {
- return async dispatch => {
- try {
- const token = await localStorage.getItem('AUTH_JWT');
- const now = Math.floor(+Date.now()/1000);
- if(token) {
- const { exp } = await jwt_decode(token);
- // token is valid if exp > now
- if(exp > now) {
- await dispatch(setUserDataAction(token));
- }
- }
- } catch (e) {
- console.log(e);
- }
- };
- };
- export const renewAuthTokenAction = () => { // runs 5 minutes after app is launched
- return async dispatch => {
- try {
- const jwt = await localStorage.getItem('AUTH_JWT');
- const now = Math.floor(+Date.now()/1000);
- if(jwt) {
- const { exp } = await jwt_decode(jwt);
- if(exp > now) {
- // renew token while exp > now
- const { data } = await axios.post(`${RENEW_AUTH_TOKEN_URL}`, JSON.stringify({ token: jwt }), httpHeaders);
- const { token } = data;
- localStorage.setItem('AUTH_JWT', token);
- return dispatch(setUserDataAction(token));
- }
- }
- } catch (e) {
- console.log(e);
- }
- };
- };
Add Comment
Please, Sign In to add comment