#!/usr/bin/perl
# Author: Brad Marshall (bmarshal@pisoftware.com)
# Date: 20010803

# This script is released under the GNU GPL.  See http://www.gnu.org/copyleft/gpl.html
# for full licensing details.

use CGI;
use CGI::Carp qw(fatalsToBrowser carpout);
use Net::LDAP; 

my($debug) = 0;
my($basedn) = "dc=gumby";
my($ldaphost) = "eta";
my($adminuser) = "cn=admin,ou=People," . $basedn;
my($adminpasswd) = "admin";

my($query) = new CGI();

if ($query->param('user')) {
    $user = $query->param('user');
    $newpasswd1 = $query->param('newpasswd1');
    $newpasswd2 = $query->param('newpasswd2');

	print $query->header(-type=>"text/html"),
		$query->start_html(-title=>'LDAP Change Password', -BGCOLOR=>"white"), "\n",
        $query->h1("Changing Password");

    $userbind = "uid=$user,ou=People,$basedn";

    print "User is uid=$user,ou=People,$basedn" if $debug;
    print $query->br if $debug;

    my($ldap) = Net::LDAP->new("$ldaphost") or die "Can't bind to $ldaphost: $!\n";


    $mesg = $ldap->bind(
                dn       => $adminuser,
                password => $adminpasswd,
    );

    if ($mesg->code) {
        # oldpasswd is wrong
        print "Sorry, wrong password";
        print $query->br;
    } else {
        print "Yay, right password" if $debug;
        print $query->br if $debug;
        if ($newpasswd1 ne $newpasswd2) {
            # passwords don't match, deal with asking for it again
            print "Sorry, new password does not match";
            print $query->br;
        } else {
            # passwords do match
            print "And new passwords match" if $debug;
            print $query->br if $debug;
            $salt = join '', ('.', '/', 0..9, 'A'..'Z','a'..'z')[rand 64, rand 64];
            print "salt = ", $salt if $debug;
            print $query->br if $debug;
            $cryptpass = crypt($newpasswd1,$salt);
            $msg = $ldap->modify( $userbind,
                    replace => { userPassword => "{crypt}$cryptpass" });
            print "Congratulations, you have now changed " . $user . "'s password";
            print $query->br;

        }
    }
} else {
	print $query->header(-type=>"text/html"),
		$query->start_html(-title=>'LDAP Change Password', -BGCOLOR=>"white"), "\n";

    print $query->hr, "\n",
        "<FORM METHOD='post' ACTION='/cgi-bin/ldap/admin-passwd.pl' ENCTYPE='application/x-www-form-urlencoded'>", "\n";

	print "User: ", $query->textfield(-name=>'user', -default=>'username', -size=>'10'),
			$query->br,
			"New Password: ", $query->password_field(-name=>'newpasswd1', -size=>'10'),
			$query->br,
			"Password (again): ", $query->password_field(-name=>'newpasswd2', -size=>'10');

	print $query->br,
		$query->submit,
        $query->end_form,
        $query->hr,
        $query->end_html;

}
