Paulo Henrique Dutra
Paulo Henrique Dutra

Reputation: 25

Homegrown authentication, how do I remember and get the logged in user

I made a filter and a authentication in an application JSF it works very well but I'd like get the current user and I have no idea how to do that. anybody could help me?

This method authenticates

public String Authenticates() {
    FacesContext fc = FacesContext.getCurrentInstance();
    EntityManager manager = getManager();
    PersonDAO dao = new PersonDAOJPA(manager);

    if (dao.login(getPerson().getEmail(), getPerson().getPassword())) {
        ExternalContext ec = fc.getExternalContext();
        HttpSession session = (HttpSession) ec.getSession(false);
        session.setAttribute("userLogged", true);
        getCurrentUser();
        return "/index.xhtml" + "?faces-redirect=true";
    } else {
        FacesMessage ms = new FacesMessage("Email or Password Incorrect");
        ms.setSeverity(FacesMessage.SEVERITY_ERROR);
        fc.addMessage(null, ms);
        return "/account.xhtml";
    }
}

Upvotes: 1

Views: 142

Answers (1)

BalusC
BalusC

Reputation: 1108782

You're basically setting a boolean in session to indicate if an user is logged in or not.

if (userService.login(email, password)) {
    session.setAttribute("userLogged", true);
}

This is rather simplistic. This can be improved by simply putting the user itself in the session.

User user = userService.find(email, password);

if (user != null) {
    session.setAttribute("user", user);
}

Now, wherever you'd like to check if an user is logged in, instead of checking if userLogged equals true, you just check if user does not equal null.

User user = (User) session.getAttribute("user");

if (user != null) {
    // User is logged in.
} else {
    // User is not logged in.
}

This immediately solves your problem of getting the "current" user. It's this way already available by #{user}.

<p>Your email is #{user.email}.</p>

Unrelated to the concrete problem, you'd better not grab the raw HttpSession from under JSF's covers in a JSF artifact. That false argument in getSession(false) is also another thinking mistake and prone to NullPointerException later on. Instead, use ExternalContext#getSessionMap().

context.getExternalContext().getSessionMap().put("user", user);

Upvotes: 1

Related Questions