Is it possible to restrict user access by time range?

for example, I’d like to create a user that should be allowed to access the system only from Monday to Friday from 10am to 3pm.
Is it possible?

There is no such functionality at the moment. However, you can implement it yourself.
The simplest way to intercept the login event is to override the connectionStateChanged() method of your App class located in the web module:


public class App extends DefaultApp {

    @Override
    public void connectionStateChanged(Connection connection) throws LoginException {
        if (connection.isConnected() && !isAllowed(connection.getSession())) {
            throw new RuntimeException("Not allowed");
        }
        super.connectionStateChanged(connection);
    }

    private boolean isAllowed(UserSession session) {
        return true; // your logic here
    }
}

Where to store the information about the allowed time?
You can extend the User entity as explained in the docs, or use Session Attributes. Let me explain the latter.
Create an Access Group and a Session Attribute for it. Set a name, the String data type, and a Value. In the value, encode your allowed period somehow. Then your isAllowed() method can look as follows:


private boolean isAllowed(UserSession session) {
    String loginTimeAttr = session.getAttribute("login_time");
    if (StringUtils.isNotEmpty(loginTimeAttr)) {
        return // decode attribute value and compare to current time
    }
    return true;
}

This is a great response. Thanks. I will go ahead and try it out.

Hi Konstantin, it worked. Thanks.

Hi,
This is good solution, but I have a task to organize user activity monitoring including login/logout. Extention of DefaultApp does not intercept logout events. I tried to extend LoginWorker and/or LoginService beans but got such error(s):

No qualifying bean of type ‘com.haulmont.cuba.security.app.LoginService’ available: expected single matching bean but found 2: cuba_MyLoginService,cuba_LoginService

How can I do it right? Maybe I must to register my bean somewhere in xml configuration file, spring.xml for example?

Hi @evgenypopov!

Yes, your guess is right, it should be registered explicitly in spring.xml. For more details, please read through this sample. Pay attention to the 4th step in the readme file.

Regards,
Aleksey

I’d like to add that in the platform version 6.7 (which is about to be released) we have greatly reworked the authentication mechanism, so it can be easily extended for your task. See https://doc.cuba-platform.com/manual-6.7/login.html#login-events