DJ.
DJ.

Reputation: 6784

Authorization to access resource based on role and record's state

What is the best way to restrict access to resource depend on both the user's permission and the state of the record? For example, form that has some kind of workflow such as timesheet or expense claim system, where user can submit a form and then the form is in submitted state where user can only view them and only the admin can edit the form?

Trying to figure out best way to enforce the permissions based in AuthProvider to prevent user to just change the URL browser from switching between "show/edit" mode.

Upvotes: 2

Views: 191

Answers (1)

François Zaninotto
François Zaninotto

Reputation: 7335

I see 2 possibilities:

  1. Set both a show and an edit view in the Resource. In the edit view, if the user permissions don't allow the edition, use a <Redirect> component to redirect to the show view.
  2. Set only an edit view that, depending on the permissions, renders a <SimpleForm> or a <SimpleShowLayout>

Here is how I would go with the second solution:

import * as React from 'react'
import { Edit, useRecordContext, SimpleForm, TextInput, SimpleShowLayout, TextField  } from 'react-admin';

export const PostEdit = ({ permissions, ...props }) => (
    <Edit {...props}>
        <EditContent permissions={permissions}/>
    </Edit>
);

const EditContent = ({ permissions }) => {
    const record = useRecordContext();
    if (record?.canEdit && permissions === "admin") {
        return (
            <SimpleForm>
                <TextInput source="title" />
            </SimpleForm>
        );
    } else {
        return (
            <SimpleShowLayout>
                <TextField source="title" />
            </SimpleShowLayout>);
    }
};

Upvotes: 2

Related Questions