Shell_Casing

auth actions file

Oct 10th, 2020
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // parse the token and extract user data from it
  2. const setUserDataAction = token => {
  3.     return async dispatch => {
  4.         try {
  5.             const { id, fullname, exp } = await jwt_decode(token);
  6.             return dispatch({ type: SET_USER_DATA, payload: { id, fullname, exp } });
  7.         } catch (e) {
  8.             console.log(e);  // InvalidTokenError
  9.             await dispatch(setAlertAction('warning', 'Something went wrong, please try again later'));
  10.             return dispatch({ type: LOGIN_FAIL });
  11.         }
  12.     };
  13. };
  14.  
  15. export const checkAuthTokenAction = () => {
  16.     return async dispatch => {
  17.         try {
  18.             const token = await localStorage.getItem('AUTH_JWT');
  19.             const now = Math.floor(+Date.now()/1000);
  20.             if(token) {
  21.                 const { exp } = await jwt_decode(token);
  22.                 // token is valid if exp > now
  23.                 if(exp > now) {
  24.                     await dispatch(setUserDataAction(token));
  25.                 }
  26.             }
  27.         } catch (e) {
  28.             console.log(e);
  29.         }
  30.     };
  31. };
  32.  
  33. export const renewAuthTokenAction = () => {  // runs 5 minutes after app is launched
  34.     return async dispatch => {
  35.         try {
  36.             const jwt = await localStorage.getItem('AUTH_JWT');
  37.             const now = Math.floor(+Date.now()/1000);
  38.             if(jwt) {
  39.                 const { exp } = await jwt_decode(jwt);
  40.                 if(exp > now) {
  41.                     // renew token while exp > now
  42.                     const { data } = await axios.post(`${RENEW_AUTH_TOKEN_URL}`, JSON.stringify({ token: jwt }), httpHeaders);
  43.                     const { token } = data;
  44.                     localStorage.setItem('AUTH_JWT', token);
  45.                     return dispatch(setUserDataAction(token));
  46.                 }
  47.             }
  48.         } catch (e) {
  49.             console.log(e);
  50.         }
  51.     };
  52. };
Add Comment
Please, Sign In to add comment