use MIME::Base64;
use vars qw(%PASS);
%PASS = ('TEST' => 'TEST');

sub Session_OnStart {
    $Response->AppendToLog("starting session");
    $Session->{AuthID} = substr($Session->SessionID, 0, 8).rand();
}

sub Script_OnStart {
    my $auth = Apache->header_in('Authorization');
    my($user, $pass);
    if ($auth && ($auth =~ /^Basic (.*)$/i)) {
	($user,$pass) = split(/:/, decode_base64($1), 2);
	$Response->Debug("got user $user, pass $pass for basic auth"); 
    }

    if ($Session->{AuthInit} && $user && ($PASS{$user} eq $pass)) {
	$ENV{REMOTE_USER} = $user;
	$Request->ServerVariables->{REMOTE_USER} = $user;
    } else {
	$Session->{AuthInit} = 1;
	$Response->Debug("forcing authenticate");
	$Response->AddHeader('WWW-Authenticate', 'basic realm="MyRealm-'.$Session->{AuthID}.'"');
	Apache->cgi_header_out('Status', 401);
	$Response->Write("<h2>Failed 401 Authorization</h2>");
	$Response->End;
    }
}
