Run some code before user creation

Hi,

Is it possible to run some code before user creation? I would like to check how many users are in the system and prevent creating more users if let’s say the user count already reached 10.

Would this be possible?

Thanks,

Hi Zoltan,

Sure you can do it.

If you are on CUBA 6.10 or 7+, I would recommend using EntityChangedEvent.
First, define the event listener in a middle tier bean:

package com.company.sales.core;

import com.haulmont.cuba.core.TransactionalDataManager;
import com.haulmont.cuba.core.app.events.EntityChangedEvent;
import com.haulmont.cuba.security.entity.User;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.UUID;

@Component(UserChangeListener.NAME)
public class UserChangeListener {
    public static final String NAME = "sales_UserChangeListener";

    @Inject
    private TransactionalDataManager txDataManager;

    @EventListener
    private void onUserChanged(EntityChangedEvent<User, UUID> event) {
        if (event.getType() == EntityChangedEvent.Type.CREATED) {
            Long count = txDataManager.loadValue("select count(u) from sec$User u", Long.class).one();
            if (count > 3) {
                throw new RuntimeException("Exceeded maximum number of registered users");
            }
        }
    }
}

Usage of TransactionalDataManager is crucial here - you must execute the query in the current transaction, otherwise the deadlock on the database level may occur.

Next, we need to make the framework to send EntityChangedEvent when a User is changed. Obviously, we cannot add @PublishEntityChangedEvents annotation on the entity class as it is out of our control. So we will make use of the metadata annotations feature and define the annotation for User in the metadata.xml file:

<metadata xmlns="http://schemas.haulmont.com/cuba/metadata.xsd">

    <metadata-model root-package="com.company.sales" namespace="sales"/>

    <annotations>
        <entity class="com.haulmont.cuba.security.entity.User">
            <annotation name="com.haulmont.cuba.core.entity.annotation.PublishEntityChangedEvents">
                <attribute name="created" value="true"/>
                <attribute name="updated" value="false"/>
                <attribute name="deleted" value="false"/>
            </annotation>
        </entity>
    </annotations>

</metadata>

That’s all - the code checking the number of users will be invoked on each user creation. If the exception is thrown, the transaction is rolled back and the user is not saved.

If you are on CUBA version prior to 6.10, use an entity listener for User as described in the documentation on dynamic registration of entity listeners. In this case, you need EntityManager to execute the query.