Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux, actions, authorization

I'm currently using redux and redux-thunk middleware.

When it comes to controls regarding action dispatching, such as:

  • does the user have sufficient permissions for this action?
  • prompt the user to confirm his action (for destructive action)

I believe placing such controls inside async actions (thunk) is the way to go, because:

  • it keeps my code DRYer (many components/views could trigger the action, whereas there is only one actionCreator for said action)
  • it's the last point before "something happens" in the app. Making it feel like a strategic place to make such controls.

The question(s)

  1. I'm looking for feedback from other redux users. I'm fairly confident of this decision, but having little feedback (and being junior dev) makes me doubt. Is this the right way to go for authorization controls when using redux?

  2. What about making the authorization controller into middleware. It would keep auth controls in a single place instead of duplicating it in every actionCreator.
    Edit When digging deeper into this possibility it quickly became challenging because middleware initially only receive (dispatch, getState) meaning that an authorization middleware would need to "know" which action is being dispatched (or which actionCreator is being used), something that required a hacky-ish setup and eventually proved un-reliable.

Other points

  • Yes, this is client-side. Yes, we also make server-side checks.
  • I know that these types of controls should NOT be in my store/reducers. They need to be pure.
like image 870
Sebastien Daniel Avatar asked Mar 10 '26 09:03

Sebastien Daniel


1 Answers

I think you are good to go with your setup. Thunk is a good way for orchestrating your program-flow. There are also other Middlewares like redux-saga which is a bit more sophisticated but as far as i understand you want to do something like this (pseudo code)?

function authorizeAndTriggerAction(forUser) {
  return function (dispatch) {
    return authorizeUser().then(
      action => dispatch(concreteAction(forUser)),
      error => dispatch(notAuthorized(forPerson, error))
    );
  };
}

This can be done with thunk.

like image 94
larrydahooster Avatar answered Mar 12 '26 17:03

larrydahooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!