/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.services.security.ldap;

import java.util.Iterator;
import java.util.Vector;
import java.util.HashMap;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
//openisp
import javax.naming.*;
import javax.naming.directory.*;
import org.apache.jetspeed.om.security.ldap.LDAPUser;
import org.apache.jetspeed.om.security.ldap.LDAPRole;
import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.ldap.LDAPURL;

// Jetspeed Security
import org.apache.jetspeed.services.security.RoleManagement;
import org.apache.jetspeed.services.security.JetspeedSecurityCache;
import org.apache.jetspeed.services.security.CachedAcl;

import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.BaseJetspeedUser;
//import org.apache.jetspeed.om.security.BaseJetspeedRole;
import org.apache.jetspeed.om.security.Group;
import org.apache.jetspeed.om.security.Role;

import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.security.UserManagement;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
import org.apache.jetspeed.om.security.UserNamePrincipal;

// Jetspeed Security Exceptions
import org.apache.jetspeed.services.security.RoleException;
import org.apache.jetspeed.services.security.UnknownUserException;
import org.apache.jetspeed.services.security.NotUniqueUserException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;

import org.apache.jetspeed.services.PsmlManager;

// Profile
import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.om.profile.ProfileException;

// Rundata
import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.turbine.services.rundata.RunDataService;

// Turbine
import org.apache.turbine.util.Log;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;

/**
 *
 * @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
 * @version $Id: LDAPRoleManagement.java,v 1.5 2002/12/09 20:24:08 taylor Exp $
 *
 */
public class LDAPRoleManagement extends TurbineBaseService
                                   implements RoleManagement
{
    private JetspeedRunDataService runDataService = null;
    private final static String CASCADE_DELETE = "programmatic.cascade.delete";
    private final static boolean DEFAULT_CASCADE_DELETE = true;
    private boolean cascadeDelete;
    private final static String CACHING_ENABLE = "caching.enable";
    private boolean cachingEnable = true;
    String[] attrs = {"ou","uid"};

    ///////////////////////////////////////////////////////////////////////////
    // Role Management Interfaces
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Retrieves all <code>Role</code>s for a given username principal.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param username a user principal identity to be retrieved.
     * @return Iterator over all roles associated to the user principal.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getRoles(String username)
        throws JetspeedSecurityException
    {
        StringTokenizer st;
        LDAPUser user;
        try
        {
            if (cachingEnable)
            {
                Iterator result = JetspeedSecurityCache.getRoles(username);
                if (null != result)
                {
                    return result;
                }
            }
            user = (LDAPUser)JetspeedSecurity.getUser(new UserNamePrincipal(username));
        }
        catch(JetspeedSecurityException e)
        {
            throw new RoleException("Failed to Retrieve User: ", e);
        }

        Vector roles= new Vector();
        try
        {
            for (Enumeration enum = user.getGroupRoles().elements() ;enum.hasMoreElements() ;)
            {
                st = new StringTokenizer((String)enum.nextElement(), ",");
                st.nextToken();
                roles.add(new LDAPRole(st.nextToken(), false));
            }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to retrieve groups ", e);
        }
        return roles.iterator();

    }
    /**
     * Retrieves all <code>Role</code>s.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @return Iterator over all roles.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getRoles()
        throws JetspeedSecurityException
    {
        BasicAttributes attr= new BasicAttributes();
        Vector roles = new Vector();
        Vector roleurls;
        try
        {
            roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),"(objectclass=jetspeedrole)",attrs,true);
          if (roleurls.size() > 0){
            for (Enumeration enum = roleurls.elements();enum.hasMoreElements() ;){
              roles.add(new LDAPRole((LDAPURL) (((Vector)enum.nextElement()).firstElement())));
            }
          } else {
            throw new UnknownUserException("No role ");
          }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to retrieve roles ", e);
        }
        return roles.iterator();

    }
    /**
     * Adds a <code>Role</code> into permanent storage.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void addRole(Role role)
        throws JetspeedSecurityException
    {
        if(roleExists(role.getName()))
        {
            throw new RoleException("The role '" +
                role.getName() + "' already exists");
        }

        try
        {
          new LDAPRole(role.getName(),true).update(true) ;
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to create role '" +
                role.getName() + "'", e);
        }

        if (cachingEnable) 
        { 
            JetspeedSecurityCache.addRole(role); 
        } 

        try
        {
            addDefaultRolePSML(role);
        }
        catch (Exception e)
        {
            try
            {
                removeRole(role.getName());
            }
            catch (Exception e2)
            {
            }
            throw new RoleException("failed to add default PSML for Role resource", e);
        }
    }

    protected void addDefaultRolePSML(Role role)
        throws RoleException
    {
        try
        {
            JetspeedRunDataService runDataService =
               (JetspeedRunDataService)TurbineServices.getInstance()
                   .getService(RunDataService.SERVICE_NAME);
            JetspeedRunData rundata = runDataService.getCurrentRunData();
            Profile profile = Profiler.createProfile();
            profile.setRole(role);
            profile.setMediaType("html");
            Profiler.createProfile(rundata, profile);
        }
        catch (ProfileException e)
        {
            try
            {
                removeRole(role.getName());
            }
            catch(Exception e2)
            {
            }
            throw new RoleException("Failed to create Role PSML", e);
        }
    }

    /**
     * Saves a <code>Role</code> into permanent storage.
     *
     * The security service can throw a <code>NotUniqueEntityException</code> when the public
     * credentials fail to meet the security provider-specific unique constraints.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void saveRole(Role role)
        throws JetspeedSecurityException
    {
        if(!roleExists(role.getName()))
        {
            throw new RoleException("The role '" +
                role.getName() + "' doesn't exists");
        }

        try
        {

        }
        catch(Exception e)
        {
            throw new RoleException("Failed to create role '" +
                role.getName() + "'", e);
        }

    }
    /**
     * Removes a <code>Role</code> from the permanent store.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param roleName the principal identity of the role to be retrieved.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void removeRole(String roleName)
        throws JetspeedSecurityException
    {
        try
        {
            LDAPRole role = new LDAPRole(roleName,false);
            JetspeedLDAP.deleteEntry(role.getldapurl());
            PsmlManager.removeRoleDocuments(role);
            if(cascadeDelete)
            {
            }
            if (cachingEnable)
            {
                JetspeedSecurityCache.removeAllRoles(roleName);
            }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to remove group '" +
                roleName + "'", e);
        }

    }
    /**
     * Grants a role to a user.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void grantRole(String username, String roleName)
        throws JetspeedSecurityException
    {
        LDAPUser user;
        LDAPRole role;
        try
        {
            user = (LDAPUser)JetspeedSecurity.getUser(new UserNamePrincipal(username));
            role = (LDAPRole)JetspeedSecurity.getRole(roleName);
        }
        catch(JetspeedSecurityException e)

        {
            throw new RoleException("Failed to Retrieve User or Role: ", e);
        }

        try
        {
          user.addGroupRole(JetspeedSecurity.JETSPEED_GROUP, roleName);
          user.update(false);

          if (cachingEnable)
          {
              JetspeedSecurityCache.addRole(username, role);
          }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to add role info ", e);
        }

    }

    /**
     * Revokes a role from a user.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void revokeRole(String username, String roleName)
        throws JetspeedSecurityException
    {
        LDAPUser user;

        try
        {
            user = (LDAPUser)JetspeedSecurity.getUser(new UserNamePrincipal(username));
        }
        catch(JetspeedSecurityException e)
        {
            throw new RoleException("Failed to Retrieve User: ", e);
        }

        try
        {
            user.removeGroupRoles(JetspeedSecurity.JETSPEED_GROUP, roleName);
            user.update(false);

            if (cachingEnable)
            {
                JetspeedSecurityCache.removeRole(username, roleName);
            }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to add role info ", e);
        }
    }

    /**
     * Checks for the relationship of user has a role. Returns true when the user has the given role.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public boolean hasRole(String username, String roleName)
        throws JetspeedSecurityException
    {
        StringTokenizer st;
        LDAPUser user;
        try
        {
            if (cachingEnable)
            {
                CachedAcl acl = JetspeedSecurityCache.getAcl(username);
                if (null != acl)
                {
                    return acl.hasRole(roleName);
                }
            }
            user = (LDAPUser)JetspeedSecurity.getUser(new UserNamePrincipal(username));
        }
        catch(JetspeedSecurityException e)
        {
            throw new RoleException("Failed to Retrieve User: ", e);
        }
        try
        {
            for (Enumeration enum = user.getGroupRoles().elements() ;enum.hasMoreElements() ;)
            {
                st = new StringTokenizer((String)enum.nextElement(),",");
                st.nextToken();
                if (st.nextToken().equalsIgnoreCase(roleName))
                {
                    return true;
                }
            }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to retrieve roles ", e);
        }
        return false;
    }

    /**
     * Retrieves a single <code>Role</code> for a given roleName principal.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param roleName a role principal identity to be retrieved.
     * @return Role the role record retrieved.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Role getRole(String roleName)
        throws JetspeedSecurityException
    {
        BasicAttributes attr= new BasicAttributes();
        Vector roleurls;

        try
        {
            roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
                       "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);

            if (roleurls.size() == 1)
            {
                return new LDAPRole((LDAPURL) ((Vector)roleurls.elementAt(0)).firstElement());
            }
            else if(roleurls.size() > 1)
            {
                throw new RoleException("Multiple roles with same name");
            }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to retrieve roles ", e);
        }
        throw new RoleException("Unknown role '" + roleName + "'");
    }
    ///////////////////////////////////////////////////////////////////////////
    // Internal
    ///////////////////////////////////////////////////////////////////////////

    protected JetspeedRunData getRunData()
     {
         JetspeedRunData rundata = null;
         if (this.runDataService != null)
         {
             rundata = this.runDataService.getCurrentRunData();
         }
         return rundata;
     }

    /**
     * Check whether a specified role exists.
     *
     * The login name is used for looking up the account.
     *
     * @param roleName the name of the role to check for existence.
     * @return true if the specified account exists
     * @throws RoleException if there was a general db access error
     *
     */
    protected boolean roleExists(String roleName)
        throws RoleException
    {
        BasicAttributes attr= new BasicAttributes();
        Vector roleurls;
        try
        {
            roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
                                        "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
          if (roleurls.size() > 0){
            return true;
          }
        }
        catch(Exception e)
        {
            throw new RoleException("Failed to retrieve roles ", e);
        }
        return false;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Service Init
    ///////////////////////////////////////////////////////////////////////////

    /**
     * This is the early initialization method called by the
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception throws a <code>InitializationException</code> if the service
     * fails to initialize
     */
    public synchronized void init(ServletConfig conf)
        throws InitializationException
    {
        if (getInit()) return;

        super.init(conf);

        // get configuration parameters from Jetspeed Resources
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(JetspeedSecurityService.SERVICE_NAME);

        this.runDataService =
           (JetspeedRunDataService)TurbineServices.getInstance()
               .getService(RunDataService.SERVICE_NAME);

        cascadeDelete = serviceConf.getBoolean( CASCADE_DELETE, DEFAULT_CASCADE_DELETE );
        cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
        setInit(true);
     }

}