How to implement Role based restrictions/permissions in react redux app?

前端 未结 5 2256
醉梦人生
醉梦人生 2021-02-06 12:18

I have a React-Redux-KoaJs application with multiple components. I have few user roles as well. Now i want to display few buttons, tables and div to only specific roles and hide

5条回答
  •  失恋的感觉
    2021-02-06 12:44

    The best practice to solve this Problem is, simply prevent the app to generate unnecessary routes, rather checking current user role on each route it is great to generate only the routes that user have access.

    So The Normal reouting is: To control the whole view:

    const App = () => (
      
        
          
          
        
      
      export default App;
    );

    Routing based on user role:

    import { connect } from 'react-redux'
       // other imports ...
       const App = () => (
          
            
            {
              this.props.currentUser.role === 'admin' ?
                <>
              
              
                 
                : 
              
            }
            
    
            
          
          
    const mapStateToProps = (state) => {
      return {
        currentUser: state.currentUser,
      }
    }
    export default connect(mapStateToProps)(App);

    So the user with an Admin role will have access to the Account page and for other users will have access to the Home page Only! and if any user try to access to another route, the 404 page error will appear. I hope I've given a helpful solution.

    For advanced details about this approach you can check this repo on github: Role-based-access-control with react

    To hide just a presentational component:

    {this.props.currentUser.role === 'admin' &&  }

提交回复
热议问题