Friday, 17 March 2017

How do I deal with failed auth statuses in a Redux app using redux-thunk?

I am struggling to deal with handling the response in the client when the server sends back a 401 failed to authenticate status from authentication middleware in a React/Redux Express app.

Simply put, on loading the Dashboard, I am making a request to a protected route:

router.route('/')
  .get(authenticate, controller.get)

Authenticate is the middleware which checks the JWT token:

exports.authenticate = function(req, res, next) {
  const authorizationHeader = req.headers['authorization']
  let token

  if (authorizationHeader) {
      token = authorizationHeader.split(' ')[1]
  }

  if (token) {
    jwt.verify(token, config.secrets.jwt, (err, decoded) => {
      if (err) {
        logger.log(err)
        res.status(401).json({ error: 'Failed to authenticate' })
      } else {
        User.findById(decoded._id)
        .select('-password')
        .exec()
        .then(user => {
          if (!user) {
            res.status(404).json({ error: 'No such user.' })
          } else {
            req.currentUser = user
            next()
          }
        })
      }
    })
  } else {
    res.status(403).json({ error: 'No token provided.' })
  }
}

So if the authentication failed, the returned status is 401. I am trying to work out how to deal with the 401 status gracefully in the middleware and:

  • Delete the localStorage token which is the jwt token
  • Run a function which will delete the authorization header
  • Dispatch a Redux action to set auth back to initial state, which is an isAuthenticated boolean to false, and the user back to an empty object. This is then handled in the application by redirecting the user back to the login page

As mentioned before, I am using thunk middleware to deal with async actions (just no idea how to handle the 401 response)

const configureStore = () => {
  const store = createStore(
    rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    applyMiddleware(thunk)
  )
  return store
}

Thank you :)



via Le Moi

No comments:

Post a Comment