Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logging out the user when token has expired #1747

Closed
williamgranli opened this issue May 8, 2017 · 5 comments
Closed

Logging out the user when token has expired #1747

williamgranli opened this issue May 8, 2017 · 5 comments

Comments

@williamgranli
Copy link

Has anyone implemented tokens/user sessions with this project? I'm just wondering what approach you guys have taken to implement the functionality of logging out a user when the token has expired and a 401 unauthorized response is received from the backend.

Right now I'm thinking it should be sufficient to run the logoutSaga in the catch of every saga which connects to the API server. Like so:

function* getMachineMetadata() {
  try {
    const response = yield call(getMachineMetadataRequest);
    const machineMetadata = response.data;
    yield put({ type: SET_MACHINE_METADATA, payload: { machineMetadata } });
  } catch (error) {
    if (error.statusCode === 401) yield put({ type: LOGOUT }); 
    console.log(error); // eslint-disable-line no-console
  }
}

The drawback of that is that I have to couple all my sagas with my Authentication container which holds the saga for logging out a user.

Any ideas?

@danielo515
Copy link

What I do is to run a checkLoginStatus function on every route navigation. Such function checks the state of the cookie/token , sets the logged status if it has changed and redirects to the login page if the status is logged out.

This is an example route:

 {
      path: '/create',
      name: 'createLicense',
      onEnter: requireAuth, // <--- this is the check login saga
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          System.import('containers/SomeSection/reducer'),
          System.import('containers/SomeSection/sagas'),
          System.import('containers/SomeSection'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, sagas, component]) => {
          injectReducer('createlicenses', reducer.default);
          injectSagas(sagas.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    },

And here is the login logic func

export function requireAuth( nextState, replace, cb ) {
    process.env.NODE_ENV !== 'production' && console.log('Checking login status...', isLoggedIn())
    if (!isLoggedIn()) {
        return axios
            .get('/api/login')
            .then((response) => {
                if (response.data.autenticated) {
                    setLoggedIn();
                    cb();
                }
            })
            .catch(() => {
                replace({
                    pathname: '/login',
                    state: {
                        nextPathname: nextState.location.pathname
                    }
                });
                setLoggedOut();
                cb()
            });
    } else
    cb();
}

export function isLoggedIn() {
    return !!localStorage.getItem(LOGIN_STATUS);
}

export function setLoggedIn() {
    localStorage.setItem(LOGIN_STATUS, true);
}
export function setLoggedOut() {
    localStorage.removeItem(LOGIN_STATUS, false );
}

Hope that helps

@avdeev
Copy link
Contributor

avdeev commented May 10, 2017

We patched checkStatus method

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  if (response.status === 401) {
    window.localStorage.clear('jwt');
    window.location = '/session';
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

@gretzky
Copy link
Member

gretzky commented Dec 13, 2017

Unrelated to issues related to this boilerplate, closing

@gretzky gretzky closed this as completed Dec 13, 2017
@naiduprakash
Copy link

I found this question so much related in everyday projects. I did not find the way to logout the user and redirect him to login page after status code 401 unauthorize responce. Is anyone find the solution?

@lock
Copy link

lock bot commented May 29, 2018

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators May 29, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants