readd the lost items
[mirror/userdir-ldap-cgi.git] / login.cgi
1 #!/usr/bin/perl
2
3 # $Id: login.cgi,v 1.10 2006/12/22 08:58:50 rmurray Exp $
4 # (c) 1999 Randolph Chung. Licensed under the GPL. <tausq@debian.org>
5 # (c) 2006 Ryan Murray. Licensed under the GPL. <rmurray@debian.org>
6
7 use lib '.';
8 use strict;
9 #use Apache::Registry;
10 use CGI;
11 use Util;
12 use URI::Escape;
13 use Crypt::Blowfish;
14 use Net::LDAP qw(LDAP_SUCCESS LDAP_PROTOCOL_ERROR);
15
16 my %config = &Util::ReadConfigFile;
17
18 my $query = new CGI;
19 my $proto = ($ENV{HTTPS} ? "https" : "http");
20
21 if ($proto eq "http" || !($query->param('username')) || !($query->param('password'))) {
22   print "Location: https://$ENV{SERVER_NAME}/$config{webloginhtml}\n\n";
23   exit;
24 }
25
26 my $key = &Util::CreateKey($config{blowfishkeylen}); # human-readable version of the key
27 my $hrkey = unpack("H".($config{blowfishkeylen}*2), $key);
28 my $cipher = new Crypt::Blowfish $key;
29
30 my $ldap = Net::LDAP->new($config{ldaphost}) || &Util::HTMLError($!);
31 &Util::UpgradeConnection($ldap) unless $config{usessl} eq 'False';
32
33 my $username = $query->param('username');
34 my $password = $query->param('password');
35 my $binddn = "uid=$username,$config{basedn}";
36
37 my $mesg = $ldap->bind($binddn, password => $password);
38 $mesg->sync;
39
40 if ($mesg->code == LDAP_SUCCESS) {
41   # HACK HACK HACK
42   # Check for md5 password, and update as necessary
43   $mesg = $ldap->search(base   => $config{basedn}, 
44                         filter => "(uid=$username)");
45   $mesg->code && &Util::HTMLError($mesg->error);
46   my $entries = $mesg->as_struct;
47   my $dn = (keys %$entries)[0];
48   my $oldpassword = $entries->{$dn}->{userpassword}->[0];
49   if ($oldpassword !~ /^{crypt}\$1\$/) {
50     # Update their password to md5
51     open (LOG, ">>$config{weblogfile}");
52     print LOG scalar(localtime);
53     print LOG ": Updating MD5 password for $dn\n";
54     close LOG;
55     my $newpassword = '{crypt}'.crypt($password, &Util::CreateCryptSalt(1));
56     &Util::LDAPUpdate($ldap, $dn, 'userPassword', $newpassword);
57   }
58   ## END HACK HACK HACK
59   
60   my $cryptid = &Util::SavePasswordToFile($username, $password, $cipher);
61
62   if ($query->param('update')) {
63     my $url = "$proto://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$username&authtoken=$cryptid,$hrkey&editdn=";
64     $url .= uri_escape("uid=$username,$config{basedn}", "\x00-\x40\x7f-\xff");
65     print "Location: $url\n\n";
66   } else {
67     my $url = "$proto://$ENV{SERVER_NAME}/$config{websearchurl}?id=$username&authtoken=$cryptid,$hrkey";
68     print "Location: $url\n\n";
69   }
70
71   $ldap->unbind;
72 } else {
73   print "Content-type: text/html; charset=utf-8\n\n";
74   print "<html><body><h1>Not authenticated</h1></body></html>\n";
75 }
76