/*  Copyright (c) 2000 by Oracle Corporation. All Rights Reserved. */

package oracle.portal.provider.v2.security;

import oracle.portal.provider.v2.PortletDefinition;
import oracle.portal.provider.v2.ProviderUser;
import oracle.portal.provider.v2.ProviderInstance;
import oracle.portal.provider.v2.PortletNotFoundException;
import oracle.portal.provider.v2.personalize.PortletReference;
import oracle.portal.log.LogManager;

import java.io.*;
import java.util.*;

/**
 * GroupSecurityManager is a simple access controller for a portlet that uses
 * a user's membership of a group to control access. A user will be granted
 * access to a portlet if the user is a member of a named group
 */
public class GroupSecurityManager extends PortletSecurityManager
{
    private List mGroups = new ArrayList(5);

    /**
     *  Verifies that the specified user is a member of one of the groups
     *
     *  @param pi the provider instance from which the portlet is being
     *  accessed.
     *  @param pd the definition of the portlet which we want to authorize
     *  access to.
     *  @param user the current user we are being asked to authorize.
     *  @return true is this user is authorized to access this portlet.
     */
    public boolean hasAccess(ProviderInstance pi, PortletDefinition pd, 
                             ProviderUser user)
    {
       boolean hasAccess = false; // default access is false

       Iterator iter = mGroups.iterator();
       while(hasAccess == false && iter.hasNext())
       {
           String group = (String)iter.next();
           hasAccess = user.isUserInGroup(group);
       }
        return hasAccess;
    }

    /**
     *  Verifies that the specified user is a member of one of the groups
     *
     *  @param  inst the portlet instance
     *  @param  user the current user we are being asked to authorize.
     *  @return true is this user is authorized to access this portlet instance.
     */
    public boolean hasAccess(PortletReference ref, ProviderUser user)
        throws PortletNotFoundException
    {
       boolean hasAccess = false; // default access is false

       Iterator iter = mGroups.iterator();
       while(hasAccess == false && iter.hasNext())
       {
           String group = (String)iter.next();
           hasAccess = user.isUserInGroup(group);
       }
        return hasAccess;
    }

    /**
    * Adds the group distinguished name for this security manager. 
    *
    * Group distinghished names are like 
    * "cn=deptX,cn=Groups,dc=uk,dc=oracle,dc=com".
    * This version of the method is intended for use by Providers that
    * are initialized via the provider.xml file 
    *
    * @param name String the group distinguished name
    */
    public void addGroup(String name) 
         throws IllegalStateException
    {
        mGroups.add(name);
    }


}

