######################################################################
#
# EPrints::Apache::Login
#
######################################################################
#
#
# Copyright 2000-2009 University of Southampton. All Rights Reserved.
# 
#  This file is part of GNU EPrints 3.
#  
#  Copyright (c) 2000-2008 University of Southampton, UK. SO17 1BJ.
#  
#  EPrints 3 is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  EPrints 3 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 General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with EPrints 3; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
######################################################################

package EPrints::Apache::Login;

use strict;

use EPrints;
use EPrints::Apache::AnApache;

sub handler
{
	my( $r ) = @_;

	my $session = new EPrints::Session;
	my $problems;

	if( $session->param( "login_check" ) )
	{
		# If this is set, we didn't log in after all!
		$problems = $session->html_phrase( "cgi/login:no_cookies" );
	}

	my $username = $session->param( "login_username" );
	my $password = $session->param( "login_password" );
	if( defined $username )
	{
		if( $session->valid_login( $username, $password ) )
		{
			my $user = EPrints::DataObj::User::user_with_username( $session, $username );

			my $url = $session->get_url( host=>1 );
			$url .= "?login_params=".URI::Escape::uri_escape( $session->param("login_params") );
			$url .= "&login_check=1";
			# always set a new random cookie value when we login
			my @a = ();
			srand;
			my $r = $session->get_request;
			for(1..16) { push @a, sprintf( "%02X",int rand 256 ); }
			my $code = join( "", @a );
			$session->login( $user,$code );
			my $cookie = $session->{query}->cookie(
				-name    => "eprints_session",
				-path    => "/",
				-value   => $code,
				-domain  => $session->get_conf("cookie_domain"),
			);			
			$r->err_headers_out->add('Set-Cookie' => $cookie);
			$session->redirect( $url );
			return DONE;
		}

		$problems = $session->html_phrase( "cgi/login:failed" );
	}

	$r->status( 401 );
	$r->custom_response( 401, '' ); # disable the normal error document

	EPrints::ScreenProcessor->process(
		session => $session,
		screenid => "Login",
		problems => $problems,
	);

	return DONE;
}

1;
