/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.web.test;

import java.net.HttpURLConnection;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jboss.test.JBossTestCase;
import org.jboss.test.JBossTestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;

/** Tests of web app single sign-on
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1.2.7 $
 */
public class SingleSignOnUnitTestCase extends JBossTestCase
{
   private String baseURLNoAuth = "http://localhost:" + Integer.getInteger("web.port", 8080) + "/"; 

   public SingleSignOnUnitTestCase(String name)
   {
      super(name);
   }

   /** Test single sign-on across two web apps using form based auth
    * 
    * @throws Exception
    */ 
   public void testFormAuthSingleSignOn() throws Exception
   {
      // Start by accessing the secured index.html of war1
      HttpClient httpConn = new HttpClient();
      GetMethod indexGet = new GetMethod(baseURLNoAuth+"war1/index.html");
      int responseCode = httpConn.executeMethod(indexGet);
      String body = indexGet.getResponseBodyAsString();
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );

      HttpState state = httpConn.getState();
      Cookie[] cookies = state.getCookies();
      String sessionID = null;
      for(int c = 0; c < cookies.length; c ++)
      {
         Cookie k = cookies[c];
         if( k.getName().equalsIgnoreCase("JSESSIONID") )
            sessionID = k.getValue();
      }
      getLog().debug("Saw JSESSIONID="+sessionID);

      // Submit the login form
      PostMethod formPost = new PostMethod(baseURLNoAuth+"war1/j_security_check");
      formPost.addRequestHeader("Referer", baseURLNoAuth+"war1/login.html");
      formPost.addParameter("j_username", "jduke");
      formPost.addParameter("j_password", "theduke");
      responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
         formPost, state);
      String response = formPost.getStatusText();
      getLog().debug("responseCode="+responseCode+", response="+response);
      assertTrue("Saw HTTP_MOVED_TEMP("+responseCode+")",
         responseCode == HttpURLConnection.HTTP_MOVED_TEMP);

      //  Follow the redirect to the index.html page
      Header location = formPost.getResponseHeader("Location");
      String indexURI = location.getValue();
      GetMethod war1Index = new GetMethod(indexURI);
      responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(),
         war1Index, state);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war1Index.getResponseBodyAsString();
      if( body.indexOf("j_security_check") > 0 )
         fail("get of "+indexURI+" redirected to login page");

      cookies = state.getCookies();
      String ssoID = null;
      for(int c = 0; c < cookies.length; c ++)
      {
         Cookie k = cookies[c];
         if( k.getName().equalsIgnoreCase("JSESSIONIDSSO") )
            ssoID = k.getValue();
      }
      assertTrue("Saw JSESSIONIDSSO", ssoID != null);
      getLog().debug("Saw JSESSIONIDSSO="+ssoID);

      // Now try getting the war2 index using the JSESSIONIDSSO cookie 
      GetMethod war2Index = new GetMethod(baseURLNoAuth+"war2/index.html");
      responseCode = httpConn.executeMethod(war2Index.getHostConfiguration(),
         war2Index, state);
      response = war2Index.getStatusText();
      getLog().debug("responseCode="+responseCode+", response="+response);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war2Index.getResponseBodyAsString();
      getLog().debug("body: "+body);
      if( body.indexOf("j_security_check") > 0 )
         fail("get of /war2/index.html redirected to login page");

      /* Access a secured servlet that calls a secured ejb in war2 to test
      propagation of the SSO identity to the ejb container.
      */
      GetMethod war2Servlet = new GetMethod(baseURLNoAuth+"war2/EJBServlet");
      responseCode = httpConn.executeMethod(war2Servlet.getHostConfiguration(),
         war2Servlet, state);
      response = war2Servlet.getStatusText();
      getLog().debug("responseCode="+responseCode+", response="+response);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war2Servlet.getResponseBodyAsString();
      getLog().debug("body: "+body);
      if( body.indexOf("j_security_check") > 0 )
         fail("get of /war2/EJBServlet redirected to login page");
   }

   /** One time setup for all SingleSignOnUnitTestCase unit tests
    */
   public static Test suite() throws Exception
   {
      TestSuite suite = new TestSuite();
      suite.addTest(new TestSuite(SingleSignOnUnitTestCase.class));

      // Create an initializer for the test suite
      Test wrapper = new JBossTestSetup(suite)
      {
         protected void setUp() throws Exception
         {
            super.setUp();
            // Deploy the test ear
            deploy("web-sso.ear");
            // Make sure the security cache is clear
            flushAuthCache();
         }
         protected void tearDown() throws Exception
         {
            undeploy("web-sso.ear");
            super.tearDown();
         }
      };
      return wrapper;
   }
}
