Avoid same user login in same time - REST

Hi All,

I’m Try to use REST Api based on cuba for my mobile Apps…

is there a setting/config to avoid same user to login in same time ? or Do I need create custom authentication to do that ?



You can see sample project https://github.com/cuba-platform/sample-login-restrictions and check that user logged in the before login listener.
For example:

public class LoginEventListener {

    private UserSessionsAPI userSessions;

    private Messages messages;

    private void onBeforeLogin(BeforeLoginEvent event) throws LoginException {
        if (event.getCredentials() instanceof AbstractClientCredentials) {
            AbstractClientCredentials credentials = (AbstractClientCredentials) event.getCredentials();
            Locale locale = ((AbstractClientCredentials) event.getCredentials()).getLocale();
            if (checkExistingSessions(credentials.getUserIdentifier()))
                throw new LoginException(messages.getMessage(getClass(), "LoginException.sessionAlreadyExists", locale));

    protected boolean checkExistingSessions(String login) {
        return userSessions.getUserSessionsStream()
                .anyMatch(s -> !s.isSystem() && Objects.equals(s.getUser().getLogin(),  login));

Hi thanks @subbotin really helpful :wink:

Hi @subbotin

I need modify the code, Instead of checking session by login name , I need check session by particular “role” that given to the user.

Where can I get “role” information programmatically ?



Could you clarify your intention? A user enters the name and the password, then what should the system check? And what to do in response?

As for getting the list of roles from a user session, it’s easy: the UserSession object contains the List<String> roles property.

Hi @knstvk

Thanks very much for reply

My itention is to prevent same users with particular role can login in the same same time / only single sessions is allowed for that user account

Does UserSession can be called within “onBeforeLogin” ?

Yes, you can get the list of currently active user sessions from the UserSessionsAPI bean as shown in the sample application.