Search code examples
reactjsreduxadmin-on-rest

Adding Role based access control for Admin-On-Rest


Am creating an app using Marmelab Admin-On-Rest to create an app to let a team of users edit, graph, schedule, publish and finally track a set of blog posts.

Would like to show custom views to every team based on their role.

Any way to achieve that using Admin-On-Rest? Would ideally like to use default Admin-On-Rest and NOT create my own Redux and React app from scratch.


Solution

  • I think that's a fairly common scenario. I'm considering the following solution:

    Extend the authClient with a hasRole method.

    Provide a withRoles Higher Order Function taking the authClient and an object mapping roles to Views components.

    Usage would be:

    import React from 'react';
    
    import { simpleRestClient, Admin, Resource } from 'admin-on-rest';
    import withRoles from 'aor-roles';
    
    import { PostCreateForTeam1, PostCreateForTeam2 } from './posts';
    
    const App = () => (
        <Admin restClient={simpleRestClient('http://path.to.my.api')}>
            <Resource name="posts" list={PostList} create={
                withRoles(authClient, {
                    team1: PostCreateForTeam1,
                    team2: PostCreateForTeam2,
                })
            } />
        </Admin>
    );
    
    export default App;

    Where team1 and team2 would be roles. It may be interesting that the authClient.hasRole can be asynchronous so that it may check the role using an API (I'm thinking about SASS services for auth and roles checks). It may be tricky to correctly handle this.

    Give me some days to think about it :)

    Edit: Found an API I'm happy with.

    authClient would have to manage a new type: AUTH_GET_ROLE which would return a promise resolving to the user role.

    export const ProductEdit = props => (
        <SwitchRoles authClient={authClient} {...props}>
            <ForRole role="role1">
                <ProductEditRole1 />
            </ForRole>
            <ForRole role="role2">
                <ProductEditRole2 />
            </ForRole>
        </SwitchRoles>
    );

    The role prop of the ForRole component also accept a function for more complex check.

    We just released aor-permissions !