/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.test.web.test;

import java.net.HttpURLConnection;

import junit.framework.TestCase;
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.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Category;

/** 
 * Base class for tests of web app single sign-on
 * 
 * @author Brian Stansberry
 * @version $Revision: 1.1.2.4 $
 */
public abstract class SSOBaseCase extends TestCase
{ 
   /** Test single sign-on across two web apps using form based auth
    * 
    * @throws Exception
    */ 
   protected static void executeFormAuthSingleSignOnTest(String serverA, 
                                                  String serverB,
                                                  Category log) 
         throws Exception
   {
      // Start by accessing the secured index.html of war1
      HttpClient httpConn = new HttpClient();
      GetMethod indexGet = new GetMethod(serverA+"/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();
      }
      log.debug("Saw JSESSIONID="+sessionID);

      // Submit the login form
      PostMethod formPost = new PostMethod(serverA+"/war1/j_security_check");
      formPost.addRequestHeader("Referer", serverA+"/war1/login.html");
      formPost.addParameter("j_username", "jduke");
      formPost.addParameter("j_password", "theduke");
      responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
         formPost, state);
      String response = formPost.getStatusText();
      log.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();
            if (serverA.equals(serverB) == false) 
            {
               // Make an sso cookie to send to serverB
               Cookie copy = copyCookie(k, serverB);
               state.addCookie(copy);
               log.debug("Added state cookie: "+copy);
            }
         }
      }
      assertTrue("Saw JSESSIONIDSSO", ssoID != null);
      log.debug("Saw JSESSIONIDSSO="+ssoID);

      // Now try getting the war2 index using the JSESSIONIDSSO cookie 
      log.debug("Prepare /war2/index.html get");
      GetMethod war2Index = new GetMethod(serverB+"/war2/index.html");
      responseCode = httpConn.executeMethod(war2Index.getHostConfiguration(),
         war2Index, state);
      response = war2Index.getStatusText();
      log.debug("responseCode="+responseCode+", response="+response);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war2Index.getResponseBodyAsString();
      log.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(serverB+"/war2/EJBServlet");
      responseCode = httpConn.executeMethod(war2Servlet.getHostConfiguration(),
         war2Servlet, state);
      response = war2Servlet.getStatusText();
      log.debug("responseCode="+responseCode+", response="+response);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war2Servlet.getResponseBodyAsString();
      log.debug("body: "+body);
      if( body.indexOf("j_security_check") > 0 )
         fail("get of /war2/EJBServlet redirected to login page");

      // Now try logging out of war2 
      GetMethod war2Logout = new GetMethod(serverB+"/war2/Logout");
      war2Logout.setFollowRedirects(false);
      responseCode = httpConn.executeMethod(war2Logout.getHostConfiguration(),
         war2Logout, state);
      response = war2Logout.getStatusText();
      log.debug("responseCode="+responseCode+", response="+response);
      assertTrue("Logout: Saw HTTP_MOVED_TEMP("+responseCode+")",
         responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
      location = war2Logout.getResponseHeader("Location");
      indexURI = location.getValue();
      if( indexURI.indexOf("index.html") < 0 )
         fail("get of /war2/Logout not redirected to login page");
      
      // Try accessing war1 again
      war1Index = new GetMethod(serverA+"/war1/index.html");
      responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(),
         war1Index, state);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war1Index.getResponseBodyAsString();
      log.debug("body: " + body);
      if( body.indexOf("j_security_check") < 0 )
         fail("get of /war1/index.html not redirected to login page");
      
      // Try accessing war2 again
      war2Index = new GetMethod(serverB+"/war2/index.html");
      responseCode = httpConn.executeMethod(war2Index.getHostConfiguration(),
         war2Index, state);
      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
      body = war2Index.getResponseBodyAsString();
      log.debug("body: " + body);
      if( body.indexOf("j_security_check") < 0 )
         fail("get of /war2/index.html not redirected to login page");      
      
   }
   
   private static Cookie copyCookie(Cookie toCopy, String targetServer)
   {
      // Parse the target server down to a domain name
      int index = targetServer.indexOf("://");
      if (index > -1)
      {
         targetServer = targetServer.substring(index + 3);
      }
      index = targetServer.indexOf(":");
      if (index > -1)
      {
         targetServer = targetServer.substring(0, index);         
      }
      index = targetServer.indexOf("/");
      if (index > -1)
      {
         targetServer = targetServer.substring(0, index);
      }
      
      Cookie copy = new Cookie(targetServer,
                               toCopy.getName(),
                               toCopy.getValue(),
                               "/",
                               null,
                               false);
      return copy;
   }
}
