package Apache::AuthSessionNTLM;

use strict;

use Apache::Constants qw(:common REDIRECT);
use Apache::SessionManager;

use Apache::AuthenNTLM;
use base ('Apache::AuthenNTLM');
use Data::Dumper;

use vars qw($VERSION);
$VERSION = 0.01;

my $remote_user;

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

	# Get session
	my $session = Apache::SessionManager::get_session($r);

	my $debug = $r->dir_config('ntlmdebug') || 0;

	# Login ok: user is already logged or login form is requested
	if ( $session->{'logged'} == 1 || $r->uri eq $r->dir_config('MyAuthLogin') ) { 

		# Set REMOTE_USER
		# $r ->user($remote_user);
		my $user = lc($session->{'userdomain'} . '\\' . $session->{'username'});
		$r ->user($user); 

		print STDERR "[$$] AuthSessionNTLM: user " . $user . " already logged \n" if $debug > 0;

		return OK;
	}


	# user not logged in or session expired

	# store in session the destination url if not set
	# $session->{'redirect'} ||= $r->uri . ( ( $r->args ) ? ('?' . $r->args) : '' );

	# User not logged. Try to authenticate him/her
	my $v = Apache::AuthenNTLM::handler($self, $r);

	# verify credentals
	unless ( $v == 0 ) {

		# Log error
		$r->log_error("[$$] AuthSessionNTLM: access to " . $r->uri . ' failed for ' . $r->get_remote_host);

		# Redirect to login page
		$r->custom_response(FORBIDDEN, $r->dir_config('MyAuthLogin'));
		return $v;
	}
	$session->{'logged'} = 1;
	$session->{'username'} = $remote_user->{username};
	$session->{'userdomain'} = $remote_user->{userdomain};

	return $v;
}


sub map_user {
	my ($self, $r) = @_ ;

	# Save to global
	if ($remote_user eq {} || $remote_user->{username} ne $self->{username}) {
		$remote_user->{username} = $self->{username};
		$remote_user->{userdomain} = $self->{userdomain};
	}

	return lc("$self->{userdomain}\\$self->{username}");
}

1;

