4

For my react-native app I need to make sure that before every fetch request to server the use-case below should be executed

-> check the expire date of token that is saved to redux.

--> If token is not expired, app keeps going on with requested fetch to server

--> If token expired, app immediately makes new request to refresh token without making user knows it. After successfully refreshing token, app keeps going on with requested fetch to server

I tried to implement middleware with redux-thunk, but I do not know whether it's good design or not. I just need someone experienced with redux and react to give me feedback over my middleware code.

This is how I make requests to server oveer my app's component through dispatching the checkTokenAndFetch - action creater.

url = "https://———————";
requestOptions = {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer ' + this.props.token
    }
};

dispatch(authActions.checkTokenAndFetch(url, requestOptions))
    .then((data) => {

    })

here is action creator - checkTokenAndFetch located in authActions.js file where my actions located

function checkTokenAndFetch(url, requestOptions){

        return dispatch => {

        if(authServices.isTokenExpired()){
            console.log("TOKEN EXPIRED");
            authServices.refreshToken()
                .then(
                    refreshToken => {
                        var arr = refreshToken.split('.');
                        decodedToken = base64.decode(arr[1]);
                        newTokenExpDate = JSON.parse(decodedToken).exp;
                        dispatch(writeTokenToRedux(refreshToken,newTokenExpDate));
                    },
                    error => {
                        Alert.alert("TOKEN refresh failed","Login Again");
                        Actions.login();

                    }
                );
        }
        else{
            console.log("TOKEN IS FRESH");
        }

        return authServices.fetchForUFS(url, requestOptions)
            .then(
                response => {
                    return response;
                },
                error => {
                }
            )
            ;
    }
}

Here is isTokenExpired and refreshToken functions that I call for case of token expire, located in another file named authServices.js.

function isTokenExpired(){
    var newState = store.getState();
    var milliseconds = (new Date).getTime();


    var exDate = newState.tokenExpDate;
    return milliseconds>exDate*1000
}


function refreshToken(){
    var refreshToken = store.getState();

    return fetch('https://—————————', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + refreshToken.token
        }
    })
        .then((response) => {
            return response._bodyText;
        })
        .catch((error) => {
        return error;
        })
}

and my fetchForUFS function in authServices.js to make a call to server after completeing token-check(refresh) stuff.

function fetchForUFS(url,requestOptions){

    return fetch(url, requestOptions)
        .then((response) => {
            return response.json();
        })
        .then((responseData) =>{
        return responseData;
    })
        .catch((error) => {
        })
}

I've read tons of redux-thunk, redux-promise and middleware documentation and I'm yet not sure whether I am implementing middleware logic truly?

Ali Zeynalov
  • 2,867
  • 8
  • 30
  • 54
  • All credit goes this man :) https://stackoverflow.com/questions/44982412/how-do-i-check-for-token-expiration-and-logout-user – th3g3ntl3m3n Aug 28 '18 at 12:51

0 Answers0