/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: AbsSecurityContextHelper.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.security.internal;

import java.util.ArrayList;

import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.security.SecurityService;
import org.ow2.jonas.security.realm.factory.JResource;
import org.ow2.jonas.security.realm.factory.JResourceException;
import org.ow2.jonas.security.realm.principal.JUser;
import org.ow2.jonas.lib.security.context.SecurityContext;
import org.ow2.jonas.lib.security.context.SecurityCurrent;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class allows to authenticate users.
 * It's a singleton to allow inherence and "static" methods.
 * @author Florent Benoit : Initial Developper
 * @author Helene Joanin : Refactoring
 */
public abstract class AbsSecurityContextHelper {

    /**
     * JResource
     */
    private static JResource jResource = null;

    /**
     * ref on the SecurityService
     */
    protected SecurityService securityService = null;

    /**
     * @return return the associated logger
     */
    abstract protected Logger getLogger();

    /**
     * @return return the Realm Key
     */
    abstract protected String getRealmKey();

    /**
     * @return return the default realm value
     */
    abstract protected String getRealmDefault();

    /**
     * Set the SecurityService. Avoids to use the ServiceManager here.
     * @param sec SecurityService
     */
    public void setSecurityService(SecurityService sec) {
        securityService = sec;
    }

    /**
     * Login with given principal and given credential
     * @param principalName the login
     * @param credential the password
     */
    public void login(String principalName, String credential) {

        // No authentication can be made with a null username
        if (principalName == null) {
            getLogger().log(BasicLevel.ERROR, "No username so no authentication");
            return;
        }

        // Does a user with this username exist?
        JUser user = null;
        try {
            user = getJResource().findUser(principalName);
        } catch (Exception jre) {
            // could not retrieve user
            getLogger().log(BasicLevel.ERROR, "Can not find the user : " + jre.getMessage());
            return;
        }

        // User was not found
        if (user == null) {
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "User " + principalName + " not found.");
            }
            return;
        }

        boolean validated = getJResource().isValidUser(user, credential);
        if (!validated) {
            getLogger().log(BasicLevel.ERROR, "The password for the user " + principalName + " is not valid");
            return;
        }

        ArrayList combinedRoles = null;
        try {
            combinedRoles = getJResource().getArrayListCombinedRoles(user);
        } catch (JResourceException jre) {
            getLogger().log(BasicLevel.ERROR, jre.getMessage());
            return;
        }

        SecurityContext ctx = new SecurityContext(principalName, combinedRoles);
        SecurityCurrent current = SecurityCurrent.getCurrent();
        current.setSecurityContext(ctx);
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "Login of principalName '" + principalName + "' succeeded.");
        }

    }

    /**
     * @return the Resource for the authentication (Realm based)
     */
    private JResource getJResource() {

        if (jResource != null) {
            return jResource;
        }

        String resName = null;
        try {
            resName = JProp.getInstance().getValue(getRealmKey());
        } catch (Exception e) {
            getLogger().log(BasicLevel.ERROR, "Cannot read properties in jonas.properties file.");
        }
        if (resName == null) {
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "Cannot read property '" + getRealmKey() + "' in jonas.properties file. Use default value = '" + getRealmDefault() + "'.");
            }
            resName = getRealmDefault();
        }

        // Get the resource from the security service
        jResource = securityService.getJResource(resName);
        if (jResource == null) {
            throw new IllegalStateException("Can't retrieve resource '" + resName + "' from the security service");
        }
        return jResource;
    }


}
