Question

How to Assign User Permission via Checkboxlist

I’m trying to achieve giving user permission using a checkbox list via MERN, I already tried doing a manual user permission by giving fixed permission using an if and else statement. Here is an example:

{user.role == "SuperAdmin" || user.role == "Admin" ? (
<>
    {/* Users */}
    <PrivateRoute path="/admin/users" component={Users} exact />
    <PrivateRoute path="/admin/users/create" component={AddUser} exact />
    <PrivateRoute path="/admin/users/edit/:id" component={EditUser} exact />
    ) : (
    <div id="notfound">
        <div class="notfound">
            <div class="notfound-404">
                <h1>Oops!</h1>
            </div>
            <h2>404 - You are not Authorized</h2>
            <p>
                The page you are looking for might have been removed had
                its name changed or you are not authorized to access this
                page.
            </p>
            <a href="#">Go To Homepage</a>
        </div>
    </div>
    )}

As you can see I used if and else statement in the route, are there any packages tutorial or any sample code you could give me to assign user permission using checkbox list with MERN, thank you all for your help your answers will deeply be appreciated. :)


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
July 2, 2023

Hi there,

Here’s a general guideline for assigning user permissions via a checkbox list:

  1. Create a UI that has checkboxes for each of the permissions. The permissions could be things like ‘can view users’, ‘can add users’, ‘can edit users’, etc.

Here’s a basic example using React:

function PermissionsForm() {
    const [permissions, setPermissions] = useState({
        canViewUsers: false,
        canAddUsers: false,
        canEditUsers: false,
        // other permissions...
    });

    const handleCheck = (event) => {
        setPermissions({
            ...permissions,
            [event.target.name]: event.target.checked,
        });
    };

    return (
        <div>
            <label>
                <input
                    type="checkbox"
                    name="canViewUsers"
                    checked={permissions.canViewUsers}
                    onChange={handleCheck}
                />
                Can view users
            </label>

            <label>
                <input
                    type="checkbox"
                    name="canAddUsers"
                    checked={permissions.canAddUsers}
                    onChange={handleCheck}
                />
                Can add users
            </label>

            <label>
                <input
                    type="checkbox"
                    name="canEditUsers"
                    checked={permissions.canEditUsers}
                    onChange={handleCheck}
                />
                Can edit users
            </label>

            {/* other permissions... */}
        </div>
    );
}
  1. Save these permissions to the user object in your MongoDB database. You’ll probably want to make a request to your Express server when the checkboxes are changed. On the server side, you would handle this request by updating the user’s permissions in the database.

Here’s an example Express route:

app.patch('/users/:id/permissions', async (req, res) => {
    const { id } = req.params;
    const { permissions } = req.body;

    const user = await User.findByIdAndUpdate(id, { permissions }, { new: true });

    res.json(user);
});
  1. In your React app, when the user logs in, you would fetch their permissions from the server and store them in your React app’s state.

  2. Now, instead of checking the user’s role in your routes, you would check their permissions.

Here’s an example:

<PrivateRoute
    path="/admin/users"
    component={Users}
    canAccess={user.permissions.canViewUsers}
    exact
/>

And here’s how the PrivateRoute component might look:

function PrivateRoute({ component: Component, canAccess, ...rest }) {
    return (
        <Route
            {...rest}
            render={props =>
                canAccess ? (
                    <Component {...props} />
                ) : (
                    <div id="notfound">
                        {/* 404 - You are not Authorized */}
                    </div>
                )
            }
        />
    );
}

Please note that you need to handle permissions on the server side as well. Even if the front-end doesn’t allow users to navigate to certain routes, users could still manually make requests to your Express server, so you need to make sure that your server checks permissions before responding to a request.

This is just a rough guideline. There are many details that you would need to fill in, depending on the specifics of your application. Please be aware that implementing security features like this can be complex and needs to be done carefully to avoid introducing security vulnerabilities.

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel