Assign a role through code

I created a user this way

User user = dataManager.create(User.class);
user.setCf(codiceFiscale);
user.setUsername(codiceFiscale);
user.setPassword(codiceFiscale);
user.setFirstName((String) VaadinSession.getCurrent().getAttribute(""));
user.setLastName((String) VaadinSession.getCurrent().getAttribute(""));
saveContext.saving(user);

I want to assign it a role by writing some code.

I tried with this but it throws an exception

RoleAssignment roleAssignment = new RoleAssignment(user.getUsername(), “ditta”, “resource”);

What can I do?

My programmatic role assignments look more like,

            RoleAssignmentEntity ra = dataManager.create(RoleAssignmentEntity.class);
            ra.setUsername("username here");
            ra.setRoleCode("role code here");
            ra.setRoleType("resource");
            dataManager.save(ra);
1 Like

Yes. And I call the following, when a new user is created like this:


@EventListener
public void onUserChangedBeforeCommit(final EntityChangedEvent event) {

    if (event.getType() == EntityChangedEvent.Type.CREATED) {
        User user = dataManager.load(event.getEntityId()).one();

        switch (user.getUsertype().name()) {

            case "EMPLOYEE":
                addRole(dataManager, user.getUsername(), "employee-resource-role",
                        RoleAssignmentRoleType.RESOURCE);
                addRole(dataManager, user.getUsername(), "employee-rowlevel-role",
                        RoleAssignmentRoleType.ROW_LEVEL);
                break;