package dendrarium.portal;

import dendrarium.core.entities.Role;
import dendrarium.core.entities.User;

import java.io.Serializable;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

/**
 * Komponent nadajacy uprawnienia w momencie zalogowania
 *  
 * @author Piotr Achinger <piotr.achinger at gmail.com>
 */
@Name("authenticator")
public class Authenticator implements Serializable {

    @In
    Session session;

    @Out(required = false, scope = ScopeType.SESSION)
    private User user;

    @In
    Credentials credentials;

    @In
    Identity identity;

    @In
    FacesMessages facesMessages;

    public boolean authenticate() {
        user = (User) session.getNamedQuery("login").setParameter("username", credentials.getUsername()).
                setParameter("password", credentials.getPassword()).
                uniqueResult();

        if (user == null) {
            return false;
        } else {
            for (Role role : user.getRoles()) {
                identity.addRole(role.getRolename());
                facesMessages.add("Masz uprawnienia: " + role.getRolename());
            }
            return true;
        }
    }
}
