// The contents of this file are subject to the Mozilla Public License Version 1.1
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
// WARRANTY OF ANY KIND, either express or implied. See the License for the specific
// language governing rights and limitations under the License.
// 
// The Original Code is the Venice Web Communities System.
// 
// The Initial Developer of the Original Code is Eric J. Bowersox <erbo@ricochet.com>,
// for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
// Copyright (C) 2002-2004 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
// 
// Contributor(s): 

importPackage(Packages.com.silverwrist.venice.core);
importPackage(Packages.com.silverwrist.venice.except);
importPackage(Packages.com.silverwrist.venice.ui);
importPackage(Packages.com.silverwrist.venice.ui.helpers);

// Get the request and the session.
rinput = bsf.lookupBean("request");
sess = vlib.castVeniceUISession(bsf.lookupBean("session"));

// Is this browser a crawler or stripper?  If so, make sure the session is destroyed at
// the end of this request.
binfo = vlib.queryBrowserInformation(rinput);
if (binfo.hasCapability("crawler") || binfo.hasCapability("stripper"))
{ // delete this session after 30 seconds if nothing else happens
  logger.debug("this session is a crawler, it will be killed");
  sess.setMaxInactiveInterval(30);

  // don't encode any servlet paths we send
  rinput.setSpecial("No-Session-Encode","true");

  // the session will be killed at the end of the request anyway
  rinput.registerCleanup(new SessionKiller(sess));

} // end if
else
{ // Get the login cookie name and the CookieControl service.
  cookie_name = rinput.getConfigProperty("login.cookie");
  cctl = vlib.queryCookieControl(rinput);
  if (cctl.isCookiePresent(cookie_name))
  { // get the login cookie value and try to use it to log in
    logger.debug("cookie " + cookie_name + " found");
    logged_in = false;
    try
    { // attempt to log the user in with the cookie
      // but don't do it if they're IP-banned
      if (rinput.engine.testIPBan(rinput.sourceAddress)==null)
        logged_in = sess.user.authenticateWithToken(cctl.getCookie(cookie_name));

    } // end try
    catch (e)
    { // login failed
      logger.error("caught " + vlib.exceptionType(e) + ": " + e.message);
      logged_in = false;

    } // end catch

    if (!logged_in) // not logged in - delete the cookie
      cctl.deleteCookie(cookie_name);

  } // end if
  else
    logger.debug("cookie " + cookie_name + " not found");

} // end else (this is a REAL browser, not a crawler or stripper)
