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 ?

Thanks

Hi,

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

@Component
public class LoginEventListener {

    @Inject
    private UserSessionsAPI userSessions;

    @Inject
    private Messages messages;

    @EventListener
    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 ?

Thanks

Hi,

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.