Search code examples
javavaadinvaadin7

Forcing logout of a user in vaadin. How to show a message to force logged out user


In my vaadin web app, an admin user should be able to forcefully logout a currently logged in user. When a user is forcefully logged out, he should be immediately redirected to the login page and an error message should be shown to the user that he has been forcefully logged out.

So far, I have written following code, which successfully logs out the user to the login page.

try {
    vaadinSession.lock();   //The session to be forcefully logged out

    try {
        vaadinSession.getUIs().forEach(ui -> {
            if (ui.getPage() != null) {
                ui.getPage().setLocation("");
                ui.push();
                Notification notification = new Notification("You have been forcefully logged out", Notification.Type.WARNING_MESSAGE);
                notification.setDelayMsec(-1);
                notification.show(ui.getPage());
                ui.push();
            }
        });
    } catch (Exception e) {
        logger.error("Exception triggered when redirecting pages on forceDisconnect " + e.getLocalizedMessage(), e);
    }

    vaadinSession.close();
} finally {
    vaadinSession.unlock();
}

But, the notification shown in the code is not actually shown to the user. I think it is because a new Vaadin session gets created when vaadinSession.close(); is called. If I show a notification in the new vaadin session, I think it will successfully get displayed.

But, I have no idea how I can access the new session after I call vaadinSession.close();.

Can someone point me a way how I can achieve this?


Solution

  • May not be ideal, but following is how I got this done finally.

    In forceDisconnect() method, set the message as a session variable in the underlying session of VaadinSession

    vaadinSession.getSession().setAttribute("PrevSessionError", "You have been forcefully logged out");
    

    In attach() of the login view, show the message to the user if previously set variable was found.

    @Override
    public void attach() {
        super.attach();
        Object previousSessionError = getSession().getSession().getAttribute("PrevSessionError");
        if (previousSessionError != null) {
            Notification notification = new Notification(previousSessionError.toString(), Notification.Type.ERROR_MESSAGE);
            notification.setDelayMsec(-1);
            notification.show(getUI().getPage());
            getSession().getSession().setAttribute("PrevSessionError", null);
        }
    }
    

    This works because the underlying session does not change even when VaadinSession gets changed. I don't know whether this is reliable or not, but this is all I could do.