Our application comes with login/logout support, but it obviously must be personalized by making the authentication method check whether the username and password passed are associated with a user.
In order to do that, let's edit the book.richfaces.advcm.modules.login.Authenticator
class to make it look like this:
package book.richfaces.advcm.modules.login; @Name("authenticator") public class Authenticator { @Logger private Log log; @In Credentials credentials; @In (create=true) EntityManager entityManager; @Out (scope=ScopeType.SESSION, required = false) Contact loggedUser; public boolean authenticate() { log.debug("authenticating {0}", credentials.getUsername()); try { // Try to find the user from username and password String query = "select c from Contact c where c.username = :username and c.password = :password and c.active=1"; loggedUser = (Contact)entityManager.createQuery(query) .setParameter("username",credentials.getUsername()) .setParameter("password",credentials.getPassword()) .getSingleResult(); login/logout supportlogin/logout supportabout// Update the lastAccessOn field // with the current date loggedUser.setLastAccessOn(new Date()); // Save the changes on db entityManager.merge(loggedUser); // The login is successful return true; } catch (NoResultException e) { // No logged user loggedUser = null; // The login is failed return false; } } }
The authenticate()
method executes a JPA query to check if a user with the given username and password (stored in the credentials
component) exists. If so, it updates the lastAccessOn
date property of the entity and returns true, otherwise it returns false.
The loggedUser
property is annotated with the @Out
property. It means that after the execution of the authenticate()
method, if the user instance exists, it will be outjected into the session context in order to be used by other components. It is necessary to set required = false
, because if the authentication fails, no instance will be outjected.
Finally, notice the use of the Seam standard logger for the purpose of debugging.
18.224.54.255