#!/usr/bin/perl

################################
# This program 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, published at
# http://www.gnu.org/copyleft/gpl.html
#
#
#This program is written in Persistent Systems Pvt Ltd (http://www.persistent.co.in)
#Author : sopan_shewale@persistent.co.in
#Date   : 8/Feb/2005
#
#The basic idea is taken from SessionPlugins's logon script.
#The script is modifying ENV{REMOTE_USER} value  after authentication 
######################

sub BEGIN { $ENV{PTKDB_STOP_TAG_COLOR} = "yellow" } 
use CGI::Carp qw(fatalsToBrowser);
use CGI;

### If htpassword  is used for authentication 
#
my $htpassword = "/home/httpd/twiki/data/.htpasswd";




BEGIN {
    # Set default current working directory (needed for mod_perl)
    if( $ENV{"SCRIPT_FILENAME"} && $ENV{"SCRIPT_FILENAME"} =~ /^(.+)\/[^\/]+$/ ) {
        chdir $1;
    }
    # Set library paths in @INC, at compile time
    unshift @INC, '.';
    require '../bin/setlib.cfg';
}
use TWiki;
use TWiki::Plugins::SessionPlugin;
$query = new CGI();


my $username = $query->param('username');
my $password = $query->param('password');

main();

sub main
{
    my $thePathInfo = $query->path_info(); 
    
  
    my $the_user = do_login($username, $password);


   if ($the_user eq '') { 
	   $ENV{REMOTE_USER} ="guest"; 
	   my $oopsurl = $query->param('url');
            $oopsurl =~ s/https/http/;   ## change https to http 
            $oopsurl =~ s/bin-ssl/bin/;   ## change https to http 
           my @oopsurlarray = split /logon/, $oopsurl;
	    $oopsurl = $oopsurlarray[0]."oops";
	      
	   $query->delete_all(); 
	   &TWiki::redirect($query, "$oopsurl?template=oopsauth");   }
   else { 
	   $ENV{REMOTE_USER} = $the_user; }  

    my $theRemoteUser = $query->remote_user();
    

    my $theTopic = $query->param( 'url' );

    my @topiclisting = split/logon/, $theTopic;  ## The logon word is part of 
                                                 ## %SESSIONLOGONURL% variable
    foreach (@topiclisting) { $theTopic = $_;}
 
    $theTopic =~ s/\/+//;  ## Remove all "/" from begining of string. 
    my $theUrl = $query->url;
    $query->delete_all();    ###This was required... reset the $query 
 ( $topic, $web ) = 
	&TWiki::initialize( $thePathInfo, $theRemoteUser, $theTopic, $theUrl, $query );

    my $url = &TWiki::getViewUrl( $TWiki::webName, $topic );

    $url .= ( '?' . $query->query_string() ) if $query->query_string();
    $url =~ s/^https/http/;   ## change https to http 
    #$url =~ s/:8887//;   ##  remove the the port number if https is running on non-default port. 

    &TWiki::redirect( $query, $url );
}


sub do_login {
       my $user = shift;
       my $password = shift;
       my $remote_user = '';
       open(FILE, $htpassword) or die "Error in opening the password database\n";
       my $htpassline = '';
       while (<FILE>) {
              if (/^$user:/) { $htpassline = $_; last; }
        }
	close(FILE);
      if ($htpassline eq '') {  return $remote_user; } ## username does not exist in htpasswd databse
        my $encryptpass = (split/:/, $htpassline)[1];
        chomp($encryptpass);
        chomp($password);
        my $salt = substr($encryptpass, 0, 2);
      if(crypt($password, $salt) eq $encryptpass) { $remote_user = $user } ## Takes care of MD5 and MD5Crypt algo
      return $remote_user;
  }

