#!/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
#Date   : 28/May/2005 Modified for minor changes, 
#       : fixed- if topic does not belong to Main web, the redirection happens properly after
#       : login 
#
#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 $theurl = $query->param( 'url' );
    my ($trash, $webandtopic) = split/logon\//, $theurl;  ## The logon word is part of
                                                          ## %SESSIONLOGONURL% variable
    my ($Web, $theTopic) = split /\//, $webandtopic;
    $theurl  =~ s/\/logon\//\/view\//;

   ( $topic, $web ) =
        &TWiki::initialize( $thePathInfo, $theRemoteUser, $theTopic, $theurl, $query );

    my $url = &TWiki::getViewUrl( $Web, $topic );
    &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;
  }

