/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005-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: JResourceRemoteImpl.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.security.internal.realm.factory;

import java.rmi.AccessException;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.rmi.PortableRemoteObject;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import org.ow2.jonas.lib.security.auth.JGroup;
import org.ow2.jonas.lib.security.auth.JPrincipal;
import org.ow2.jonas.lib.security.auth.JRole;
import org.ow2.jonas.lib.security.auth.JSubject;
import org.ow2.jonas.security.SecurityService;
import org.ow2.jonas.security.auth.callback.NoInputCallbackHandler;
import org.ow2.jonas.security.realm.factory.JResource;
import org.ow2.jonas.security.realm.factory.JResourceException;
import org.ow2.jonas.security.realm.principal.JUser;


/**
 * This class allow to make authentication on server side even for Client
 * container or remote applications
 * @author Florent Benoit
 */
public class JResourceRemoteImpl extends PortableRemoteObject implements JResourceRemote {

    /**
     * Security service
     */
    private static SecurityService securityService = null;

    /**
     * Default constructor
     * @throws RemoteException if super class cannot export object
     */
    public JResourceRemoteImpl(SecurityService ss) throws RemoteException {
        super();
        securityService = ss;
    }

    /**
     * Authenticate a given user
     * @param principalName name of the user
     * @param arrayPass password of the user
     * @param resourceName type of resource to use to register ( memory, jdbc,
     *        ldap)
     * @throws RemoteException if the authentication failed
     * @return an authenticated subject if it succeed
     */
    public JSubject authenticate(String principalName, char[] arrayPass, String resourceName) throws RemoteException {
        // Get security service
        if (securityService == null) {
            // Should not go here.
            throw new RemoteException("Cannot retrieve security service");
        }

        if (resourceName == null) {
            throw new AccessException("The 'resourceName' parameter is required and cannot be null.");
        }

        // Get resource
        JResource jResource = null;
        try {
            jResource = securityService.getJResource(resourceName);
        } catch (Exception e) {
            throw createChainedAccessException("The resource '" + resourceName + "' is not available.", e);
        }

        if (jResource == null) {
            throw new AccessException("The resource '" + resourceName + "' is not available.");
        }

        // Authentication - step 1 (user)
        JUser user = null;
        try {
            user = jResource.findUser(principalName);
        } catch (Exception jre) {
            // could not retrieve user
            throw createChainedAccessException("Can not find the user", jre);
        }
        // User was not found
        if (user == null) {
            throw new AccessException("User '" + principalName + "' not found.");
        }

        // Authentication - step 2 (password)
        boolean validated = jResource.isValidUser(user, new String(arrayPass));
        if (!validated) {
            throw new AccessException("The password for the user '" + principalName + "' is not valid");
        }

        // Authentication - step 3 (roles)
        ArrayList principalRoles = null;
        try {
            principalRoles = jResource.getArrayListCombinedRoles(user);
        } catch (JResourceException jre) {
            throw createChainedAccessException(jre.getMessage(), jre);
        }

        JGroup group = new JGroup("Roles");

        // Convert list into array
        String[] roles = new String[principalRoles.size()];
        roles = (String[]) principalRoles.toArray(roles);
        int size = principalRoles.size();
        for (int i = 0; i < size; i++) {
            group.addMember(new JRole(roles[i]));
        }

        // build object with name and group
        return new JSubject(new JPrincipal(principalName), group);

    }


    /**
     * Authenticate a given user
     * @param principalName name of the user
     * @param arrayPass password of the user
     * @param entryName the name of the JAAS entry to search in jaas configuration file
     * @throws RemoteException if the authentication failed
     * @return an authenticated subject if it succeed
     */
    public Subject authenticateJAAS(String principalName, char[] arrayPass, String entryName) throws RemoteException {
        // entry arg ?
        if (entryName == null) {
            throw new AccessException("The 'entryName' parameter is required and cannot be null.");
        }

        // Create a Login context
        LoginContext loginContext = null;
        try {
            loginContext = new LoginContext(entryName, new NoInputCallbackHandler(principalName, new String(arrayPass)));
        } catch (LoginException e) {
            throw new AccessException("Login Exception for user '" + principalName + "' : " + e.getMessage());
        }

        // Negotiate a login via this LoginContext
        try {
            loginContext.login();
        } catch (LoginException e) {
            throw new AccessException("Login Exception for user '" + principalName + "' : " + e.getMessage());
        }
        return loginContext.getSubject();
    }


    /**
     * Create a AccessException with the given message and set the cause to the
     * given Exception
     * @param msg Exception message
     * @param t Root cause
     * @return AccessException the chained exception
     */
    private static AccessException createChainedAccessException(String msg, Throwable t) {
        if (t instanceof Exception) {
            // If this is an Exception subclass, we can directly chain the cause.
            return new AccessException(msg, (Exception) t);
        } else {
            // In the other case, no chaining is possible
            // We simply put the cause's message in brackets and append
            // it to the new AccessException
            String causeMessage = "[inner cause message: " + t.getMessage() + "]";
            return new AccessException(msg + causeMessage);
        }
    }

}
