Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep user information after login in JavaFX Desktop Application

I have an application with login screen, after the user is authenticated some "data" is retrieved from a database (username and privileges), until here everything is well.

After the login process I need to access to the privileges to generate some menus across different JavaFX scenes, this all throughout the entire application in any moment, but I don´t know how to do it.

What I am looking for is a behavior such as SESSION variable in PHP (yep, I come from web development), which keeps information alive and accesible during a certain period of time (usually while user is logged in).

The information I have found about this topic is unclear and outdated, I mean, solutions that do not apply for JavaFX 2 or solutions with old design patterns.

I have created an image because in other forums I have found the same question but that is misunderstood, so I hope this could help.

Thanks to everyone.

enter image description here

like image 305
Fabrizio Valencia Avatar asked Oct 01 '17 00:10

Fabrizio Valencia


2 Answers

You can use the Java Preferences. At the first successful authentication, you need to write information about user in the Preferences like this:

Preferences userPreferences = Preferences.userRoot();
userPreferences.put(key,value);

And then take the data from the Preferences:

Preferences userPreferences = Preferences.userRoot();
String info = userPreferences.get(key,value);
like image 108
Vladyslav Panchenko Avatar answered Sep 28 '22 18:09

Vladyslav Panchenko


You can use singleton design patter. For example:

    public final class UserSession {

    private static UserSession instance;

    private String userName;
    private Set<String> privileges;

    private UserSession(String userName, Set<String> privileges) {
        this.userName = userName;
        this.privileges = privileges;
    }

    public static UserSession getInstace(String userName, Set<String> privileges) {
        if(instance == null) {
            instance = new UserSession(userName, privileges);
        }
        return instance;
    }

    public String getUserName() {
        return userName;
    }

    public Set<String> getPrivileges() {
        return privileges;
    }

    public void cleanUserSession() {
        userName = "";// or null
        privileges = new HashSet<>();// or null
    }

    @Override
    public String toString() {
        return "UserSession{" +
                "userName='" + userName + '\'' +
                ", privileges=" + privileges +
                '}';
    }
}

and use the UserSession whenever you need. When you do login you just call: UserSession.getInstace(userName, privileges) and when you do log out: UserSession.cleanUserSession()

like image 36
Tymur Berezhnoi Avatar answered Sep 28 '22 17:09

Tymur Berezhnoi