/* ====================================================================
 * 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.registry;

// Java imports
import java.util.Vector;

// Jetspeed imports
import org.apache.jetspeed.om.profile.Entry;
import org.apache.jetspeed.om.profile.psml.PsmlEntry;
import org.apache.jetspeed.om.BaseSecurityReference;
import org.apache.jetspeed.om.SecurityReference;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.registry.base.BaseSecurityAccess;
import org.apache.jetspeed.om.registry.base.BaseSecurityAllow;
import org.apache.jetspeed.om.registry.base.BaseSecurityEntry;
import org.apache.jetspeed.om.registry.RegistryEntry;
import org.apache.jetspeed.om.registry.SecurityEntry;

import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.JetspeedPortalAccessController;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.security.JetspeedRoleManagement;

// Turbine imports
import org.apache.turbine.util.TurbineConfig;
import org.apache.turbine.util.StringUtils;

// Junit imports
import junit.awtui.TestRunner;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.framework.TestCase;

/**
 * TestAccessController
 *
 * @author <a href="paulsp@apache.org">Paul Spencer</a>
 * @version $Id: TestAccessController.java,v 1.4 2003/03/04 00:05:12 sgala Exp $
 */
public class TestAccessController extends TestCase
{
    
    private static String ADMIN_PORTLET = "GlobalAdminPortlet"; // Portlet accessable by Admin user, role = admin
    private static SecurityReference adminSecurityRef = new BaseSecurityReference();
    private static String ALL_PORTLET = "HelloVelocity";  // Portlet accessable by Anonymous user
    private static SecurityReference defaultSecurityRef = new BaseSecurityReference();
    private static String TEST_GROUP = "Jetspeed";
    private static String TEST_SECURITY_PAGE = "SecurityTest";
    private static String USER_PORTLET = "SkinBrowser"; // Portlet accessable by general user, role = user
    private static String USERANON_PORTLET = "Welcome";  // Portlet viewable by Anonymous user, all by role=user
    private static SecurityReference userSecurityRef = new BaseSecurityReference();
    private static SecurityReference userAllAnonViewSecurityRef = new BaseSecurityReference();

    /**
     * Defines the testcase name for JUnit.
     *
     * @param name the testcase's name.
     */
    public TestAccessController( String name )
    {
        super( name );
    }
    
    /**
     * Start the tests.
     *
     * @param args the arguments. Not used
     */
    public static void main(String args[])
    {
        TestRunner.main( new String[]
        { TestAccessController.class.getName() } );
    }
    
    public void setup()
    {
        System.out.println("Setup: Testing categories of Profiler Service");
    }
    /**
     * Creates the test suite.
     *
     * @return a test suite (<code>TestSuite</code>) that includes all methods
     *         starting with "test"
     */
    public static Test suite()
    {
        // All methods starting with "test" will be executed in the test suite.
        return new TestSuite( TestAccessController.class );
    }
    
    public void testVerifyEnvironment() throws Exception
    {
        assertEquals( "Using TurbineAccessController",
        "org.apache.jetspeed.services.security.registry.RegistryAccessController",
        JetspeedResources.getString("services.PortalAccessController.classname"));

        Registry.addEntry(Registry.SECURITY, (RegistryEntry) createSecurityEntry( "admin_only", "admin", "*"));
        assertNotNull( "Getting admin_only security " , Registry.getEntry( Registry.SECURITY, "admin_only"));
        Registry.addEntry(Registry.SECURITY, (RegistryEntry) createSecurityEntry( "user_only", "user", "*"));
        assertNotNull( "Getting user_only security " , Registry.getEntry( Registry.SECURITY, "user_only"));
        Registry.addEntry(Registry.SECURITY, (RegistryEntry) createSecurityEntry( "wide_open", null, "*"));
        assertNotNull( "Getting wide_open security " , Registry.getEntry( Registry.SECURITY, "wide_open"));

        /*
         * Create a security entry that looks look like the following
         *
         * <security-entry name="all_users-view_anon">
         *   <access action="*">
         *     <allow-if role="user"/>
         *   </access>
         *   <access action="view">
         *     <allow-if role="guest"/>
         *   </access>
         * </security-entry>
         */
        Registry.addEntry(Registry.SECURITY, (RegistryEntry) createSecurityEntry( "all_users-view_anon", "user", "*"));
        assertNotNull( "Getting all_users-view_anon security " , Registry.getEntry( Registry.SECURITY, "all_users-view_anon"));
        SecurityEntry secEntry = (SecurityEntry) Registry.getEntry( Registry.SECURITY, "all_users-view_anon");
        Vector accessVector = secEntry.getAccesses();
        assertEquals( "Getting number of accesses for all_users-view_anon", 1, accessVector.size());
        BaseSecurityAllow allowElement = new BaseSecurityAllow();
        allowElement.setRole("guest");
        Vector allowVector = new Vector();
        allowVector.addElement(allowElement);
        BaseSecurityAccess accessElement  = new BaseSecurityAccess();
        accessElement.setAction("view");
        accessElement.setAllows( allowVector );
        accessVector.addElement(accessElement);
        secEntry.setAccesses(accessVector);
        assertEquals( "Getting number of accesses for all_users-view_anon", 2, secEntry.getAccesses().size());
        
        // Verify users and their groups
        assertNotNull( "Getting admin user", JetspeedSecurity.getUser("admin"));
        assertTrue( "Admin user has Admin role", JetspeedRoleManagement.hasRole("admin","admin"));
        assertTrue( "Admin user has User role", JetspeedRoleManagement.hasRole("admin","user"));
        assertNotNull( "Getting turbine user", JetspeedSecurity.getUser("turbine"));
        assertTrue( "Turbine user does not have Admin role", !JetspeedRoleManagement.hasRole("turbine","admin"));
        assertTrue( "Turbine user has User role", JetspeedRoleManagement.hasRole("turbine","user"));
        assertNotNull( "Getting anonymous user", JetspeedSecurity.getAnonymousUser());
        assertTrue( "anonymous user does not have Admin role", !JetspeedRoleManagement.hasRole(JetspeedSecurity.getAnonymousUser().getUserName(),"admin"));
        assertTrue( "anonymous user does not have User role", !JetspeedRoleManagement.hasRole(JetspeedSecurity.getAnonymousUser().getUserName(),"user"));
        assertTrue( "anonymous user does not have Guest role", JetspeedRoleManagement.hasRole(JetspeedSecurity.getAnonymousUser().getUserName(),"guest"));
        
        assertNotNull( "adminSecurityRef", adminSecurityRef);
        adminSecurityRef.setParent("admin_only");
        assertNotNull( "Getting security for " + adminSecurityRef.getParent(), Registry.getEntry( Registry.SECURITY, adminSecurityRef.getParent()));

        assertNotNull( "userSecurityRef", userSecurityRef);
        userSecurityRef.setParent("user_only");
        assertNotNull( "Getting security for " + userSecurityRef.getParent(), Registry.getEntry( Registry.SECURITY, userSecurityRef.getParent()));

        assertNotNull( "defaultSecurityRef", defaultSecurityRef);
        defaultSecurityRef.setParent("wide_open");
        assertNotNull( "Getting security for " + defaultSecurityRef.getParent(), Registry.getEntry( Registry.SECURITY, defaultSecurityRef.getParent()));

        assertNotNull( "userAllAnonViewSecurityRef", userAllAnonViewSecurityRef);
        userAllAnonViewSecurityRef.setParent("all_users-view_anon");
        assertNotNull( "Getting security for " + userAllAnonViewSecurityRef.getParent(), Registry.getEntry( Registry.SECURITY, defaultSecurityRef.getParent()));

    }
        
    public void testRequiredActions() throws Exception
    {
        JetspeedUser adminUser = (JetspeedUser) JetspeedSecurity.getUser("admin");
        assertNotNull( "Getting admin user", adminUser);
        adminUser.setHasLoggedIn(Boolean.TRUE);
        
        JetspeedUser turbineUser = (JetspeedUser) JetspeedSecurity.getUser("turbine");
        assertNotNull( "Getting turbine user", turbineUser);
        turbineUser.setHasLoggedIn(Boolean.TRUE);
        
        JetspeedUser anonymousUser =  (JetspeedUser) JetspeedSecurity.getAnonymousUser();
        assertNotNull( "Getting anonymous user", anonymousUser);
        Entry adminEntry = createEntry( ADMIN_PORTLET, "ST_01.admin", adminSecurityRef);
        Entry userEntry = createEntry( USER_PORTLET, "ST_01.user", userSecurityRef);
        Entry allEntry = createEntry( ALL_PORTLET, "ST_01.all", defaultSecurityRef);
        Entry userAnonEntry = createEntry( USERANON_PORTLET, "ST_01.userAnon", userAllAnonViewSecurityRef);
        
        assertEquals( "Admin user has view access to " + ADMIN_PORTLET, true, JetspeedPortalAccessController.checkPermission( adminUser, adminEntry, "view"));
        assertEquals( "Turbine user DOES NOT have view access to " + ADMIN_PORTLET, false, JetspeedPortalAccessController.checkPermission( turbineUser, adminEntry, "view"));
        assertEquals( "Anonymous user DOES NOT have view access to " + ADMIN_PORTLET, false, JetspeedPortalAccessController.checkPermission( anonymousUser, adminEntry, "view"));
        
        assertEquals( "Admin user has view access to " + USER_PORTLET, true, JetspeedPortalAccessController.checkPermission( adminUser, userEntry, "view"));
        assertEquals( "Turbine user has view access to " + USER_PORTLET, true, JetspeedPortalAccessController.checkPermission( turbineUser, userEntry, "view"));
        assertEquals( "Anonymous user DOES NOT have view access to " + USER_PORTLET, false, JetspeedPortalAccessController.checkPermission( anonymousUser, userEntry, "view"));
        
        assertEquals( "Admin user has view access to " + ALL_PORTLET, true, JetspeedPortalAccessController.checkPermission( adminUser, allEntry, "view"));
        assertEquals( "Turbine user has view access to " + ALL_PORTLET, true, JetspeedPortalAccessController.checkPermission( turbineUser, allEntry, "view"));
        assertEquals( "Anonymous user has view access to " + ALL_PORTLET, true, JetspeedPortalAccessController.checkPermission( anonymousUser, allEntry, "view"));

        assertEquals( "Admin user has view access to " + USERANON_PORTLET, true, JetspeedPortalAccessController.checkPermission( adminUser, userAnonEntry, "view"));
        assertEquals( "Admin user has maximize access to " + USERANON_PORTLET, true, JetspeedPortalAccessController.checkPermission( turbineUser, userAnonEntry, "maximize"));
        assertEquals( "Anonymous user has view access to " + USERANON_PORTLET, true, JetspeedPortalAccessController.checkPermission( anonymousUser, userAnonEntry, "view"));
        assertEquals( "Anonymous user has maximize access to " + USERANON_PORTLET, false, JetspeedPortalAccessController.checkPermission( anonymousUser, userAnonEntry, "maximize"));
    }

/*
     * Setup Turbine environment
     */
    
    /*
     * Configuration object to run Turbine outside a servlet container
     * ( uses turbine.properties )
     */
    private static TurbineConfig config = null;
    
    /*
     * Sets up TurbineConfig using the system property:
     * <pre>turbine.properties</pre>
     */
    static
    {
        try
        {
            config = new TurbineConfig( "../webapp", "/WEB-INF/conf/TurbineResources.properties");
            config.init();
        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }
    }
    
    private PsmlEntry createEntry(String parent, String entryId, SecurityReference security)
    {
        PsmlEntry entry = new PsmlEntry();
        entry.setParent( parent);
        if (entryId != null)
            entry.setId( entryId);
        if (security != null)
            entry.setSecurityRef( security);
        return entry;
    }

    private SecurityEntry createSecurityEntry( String name, String role, String action)
    {
        Vector allowVector = null;
        if (role != null)
        {
            BaseSecurityAllow allowElement = new BaseSecurityAllow();
            allowElement.setRole(role);
            allowVector = new Vector();
            allowVector.addElement(allowElement);
        }
        
        BaseSecurityAccess accessElement  = new BaseSecurityAccess();
        accessElement.setAction(action);
        accessElement.setAllows( allowVector );
        Vector accessVector = new Vector();
        accessVector.addElement(accessElement);
        
        BaseSecurityEntry securityEntry = new BaseSecurityEntry();
        securityEntry.setName(name);
        securityEntry.setAccesses( accessVector);
        return securityEntry;
    }
    
}
