Limit access to fields in models

In some cases we may need more fine grained access control and to limit the access to specific fields in a model.

It is possible for a field to be accessible only by specific security groups, using the groups attribute. We will show how to add to the Library Books model a field with limited access.

How to do it...

To add a field with access limited to specific security groups, perform the following steps:

  1. Edit the model file to add the field:
    private_notes = fields.Text(groups='base.group_system')
  2. Edit the view in the XML file to add the field:
    <field name="private_notes" />

That's it. Now upgrade the addon module for the changes in the model to take place. If you sign in with a user with no system configuration access, such as demo in a database with demonstration data, the Library books form won't display the field.

How it works...

Fields with the groups attribute are specially handled to check if the user belongs to any of the security groups indicated in the attribute, and if not removes it from UI views and ORM operations for the user.

Note that this security is not superficial. The field is not only hidden in the user interface, but is also made unavailable to the user in the other ORM operations, such as read and write. This is also true for the XML-RPC or JSON-RPC calls.

Be careful when using these fields in business logic, or on change UI events (@api.onchange methods); they can raise errors for users with no access to the field. One workaround for this is to use privilege elevation, such as the sudo() model method or the compute_sudo field attribute for computed fields.

The groups value is a string containing a comma separated list of valid XML IDs for security groups. The simplest way to find the XML ID for a particular group is to navigate to its form, at Settings | Users | Groups, and then access the View Metadata option from the debug menu, as shown in the following screenshot:

How it works...

There's more...

In some cases, we need a field to be available or not depending on particular conditions, such as the values in a particular field, like stage_id or state. This is usually handled at the view level using attributes such as states or attrs, to dynamically display or hide the field according to certain conditions. You may refer to Chapter 8, Backend Views for a detailed description.

Note that these techniques work at the user interface level only and don't provide actual access security. For that you should add checks in the business logic layer. Either add model methods decorated with @constrains, implementing the specific validations intended, or extend the create, write, or unlink methods to add them validation logic. You can get more insight on how to do this in Chapter 5, Basic Server Side Business Logic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset