Coder Social home page Coder Social logo

Comments (4)

mjrussell avatar mjrussell commented on August 11, 2024 2

@colinramsay good idea for an example or explanation.

Ultimately it is dependent on your app and what kind of middleware you are using for your API calls which makes an example a little bit tricky. Lets say that you have a fairly standard API middleware such as something similar to redux-api-middleware. This would dispatch actions for fetching, success, and failure. Such as GET_TODOS_FETCH, GET_TODOS_SUCCESS and GET_TODOS_FAILURE. The api middleware would attach the status code inside the payload on failure.

What you could do is create a custom middleware that comes after the api middleware and if it receives an action with a payload.status === 401 then dispatch API_UNAUTHORIZED. Then inside your reducer:

const userReducer = (state = {}, { type, payload }) => {
  switch (type) {
    case USER_LOGGED_IN:
      return payload;
    case API_UNAUTHORIZED: // fall-through
    case USER_LOGGED_OUT:
       return {};
  }
}

You could also easily implement this using a saga, either for listener or implement the middleware API inside a saga and simply dispatch the action from there.

Does that help? I don't have time at the moment to extend the JWT example (or another example) with a resource that could return 401 at times but would be more than happy to review a PR if someone wants to give it a go 😄

from redux-auth-wrapper.

colinramsay avatar colinramsay commented on August 11, 2024 1

Once the API_UNAUTHORIZED hits the userReducer, it clears the user data and causes a re-render in the authWrapper.

This is the (rather obvious) bit I was missing. Thanks. If I get time then I'll try and produce an expanded example as a PR but for now I'm happy to close this issue. Appreciate you taking the time to walk me through this.

from redux-auth-wrapper.

colinramsay avatar colinramsay commented on August 11, 2024

How would dispatching API_UNAUTHORIZED actually trigger a redirect though?

from redux-auth-wrapper.

mjrussell avatar mjrussell commented on August 11, 2024

@colinramsay Assuming you had the following auth wrapper and route setup:

// Redirects to /login by default
const UserIsAuthenticated = UserAuthWrapper({
  authSelector: state => state.user, // how to get the user state
  redirectAction: routerActions.replace, // the redux action to dispatch for redirect
  wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
})

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <Route path="login" component={Login}/>
        <Route path="foo" component={UserIsAuthenticated(Foo)}/>
        <Route path="bar" component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('mount')
)

Lets say you are on /foo and the user had an existing JWT token and the validation of the token on the initial app load or after login dispatched a USER_LOGGED_IN. Therefore the user data in the store (state.user) has has some data in it, like { name: 'Demo User' }. When the user navigates to the /foo route the authWrapper checks state.user and the predicate returns true (because the default checks for non empty/null) and renders the Foo Component. Once the API_UNAUTHORIZED hits the userReducer, it clears the user data and causes a re-render in the authWrapper. This time, the authWrapper predicate returns false, which forces a redirect back to Login.

The redirection would be same as if a user was on the /foo route and hit a logout button. The API_UNAUTHORIZED is just a different mechanism for clearing out the data but the redirect logic is identical. You can see that scenario at work in the basic example included in the repo or the JWT example here

from redux-auth-wrapper.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.