How can I automatically set row-level policies, when new user is created?

Hello!
If I create a new user, I can add some row level policies. Very important e.g.: where = “{E}.CreatedByUserID.id = :current_user_id” — so every user can only see his own entities.
Easy.

If I have a cascade of users, and one user might create another user, I want to guarantee, that my row level role is set to the newest user, of course.

How can this be done automatically, so that the creation of a new user cannot be done without this (for my purpose very important) issue?

Do I have to add an instance automatically when storing a new user entry, e.g. in an onBeforeCommitChanges() handler?
Or is there a better way?

Thanks in advance,

br
HP

Hello!

I think you can use EntityChangedEvent application event. It is fired when User instance is saved by DataManager. Thus you cover creating users programmatically and by User editor.

For instance:

@Component("demo_UserEventListener")
public class UserEventListener {
    protected final DataManager dataManager;

    public UserEventListener(DataManager dataManager) {
        this.dataManager = dataManager;
    }

    @EventListener
    public void onUserChangedBeforeCommit(final EntityChangedEvent<User> event) {
        if (event.getType() == EntityChangedEvent.Type.CREATED) {
            User user = dataManager.load(event.getEntityId()).one();

            RoleAssignmentEntity roleAssignment = dataManager.create(RoleAssignmentEntity.class);
            roleAssignment.setUsername(user.getUsername());
            roleAssignment.setRoleCode(MyCustomRole.CODE);
            roleAssignment.setRoleType(RoleAssignmentRoleType.RESOURCE);

            dataManager.save(roleAssignment);
        }
    }
}

The method will be called by the framework right after saving the entity to the database but before the transaction commit.

See Entity Events :: Jmix Documentation

2 Likes

Thanks, works!