Bug 7973 : Follow up to remove an extraneous my
[koha.git] / C4 / Auth_with_ldap.pm
index 3bb850b..1f2f617 100644 (file)
@@ -13,12 +13,12 @@ package C4::Auth_with_ldap;
 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along with
-# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU General Public License along
+# with Koha; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
 use strict;
-# use warnings; almost?
+#use warnings; FIXME - Bug 2505
 use Digest::MD5 qw(md5_base64);
 
 use C4::Debug;
@@ -35,7 +35,7 @@ use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
 
 BEGIN {
        require Exporter;
-       $VERSION = 3.10;        # set the version for version checking
+    $VERSION = 3.07.00.049;    # set the version for version checking
        @ISA    = qw(Exporter);
        @EXPORT = qw( checkpw_ldap );
 }
@@ -47,7 +47,7 @@ BEGIN {
 # ~ then gets the LDAP entry
 # ~ and calls the memberadd if necessary
 
-sub ldapserver_error ($) {
+sub ldapserver_error {
        return sprintf('No ldapserver "%s" defined in KOHA_CONF: ' . $ENV{KOHA_CONF}, shift);
 }
 
@@ -58,7 +58,7 @@ my $prefhost  = $ldap->{hostname}     or die ldapserver_error('hostname');
 my $base      = $ldap->{base}          or die ldapserver_error('base');
 $ldapname     = $ldap->{user}          ;
 $ldappassword = $ldap->{pass}          ;
-our %mapping  = %{$ldap->{mapping}} || (); #   or die ldapserver_error('mapping');
+our %mapping  = %{$ldap->{mapping}}; # FIXME dpavlin -- don't die because of || (); from 6eaf8511c70eb82d797c941ef528f4310a15e9f9
 my @mapkeys = keys %mapping;
 $debug and print STDERR "Got ", scalar(@mapkeys), " ldap mapkeys (  total  ): ", join ' ', @mapkeys, "\n";
 @mapkeys = grep {defined $mapping{$_}->{is}} @mapkeys;
@@ -70,8 +70,8 @@ my %config = (
        update => defined($ldap->{update}   ) ? $ldap->{update}    : 1,  # update from LDAP to Koha database for existing user
 );
 
-sub description ($) {
-       my $result = shift or return undef;
+sub description {
+       my $result = shift or return;
        return "LDAP error #" . $result->code
                        . ": " . $result->error_name . "\n"
                        . "# " . $result->error_text . "\n";
@@ -82,11 +82,6 @@ sub search_method {
     my $userid = shift or return;
        my $uid_field = $mapping{userid}->{is} or die ldapserver_error("mapping for 'userid'");
        my $filter = Net::LDAP::Filter->new("$uid_field=$userid") or die "Failed to create new Net::LDAP::Filter";
-    my $res = ($config{anonymous}) ? $db->bind : $db->bind($ldapname, password=>$ldappassword);
-    if ($res->code) {          # connection refused
-        warn "LDAP bind failed as ldapuser " . ($ldapname || '[ANONYMOUS]') . ": " . description($res);
-        return 0;
-    }
        my $search = $db->search(
                  base => $base,
                filter => $filter,
@@ -110,19 +105,32 @@ sub checkpw_ldap {
     my $db = Net::LDAP->new(\@hosts);
        #$debug and $db->debug(5);
     my $userldapentry;
-       if ( $ldap->{auth_by_bind} ) {
-        my $principal_name = $ldap->{principal_name};
-        if ($principal_name and $principal_name =~ /\%/) {
-            $principal_name = sprintf($principal_name,$userid);
-        } else {
-            $principal_name = $userid;
-        }
-               my $res = $db->bind( $principal_name, password => $password );
-        if ( $res->code ) {
-            $debug and warn "LDAP bind failed as kohauser $principal_name: ". description($res);
-            return 0;
-        }
-       } else {
+
+  if ( $ldap->{auth_by_bind} ) {
+    # Perform an anonymous bind
+    my $res = $db->bind;
+    if ( $res->code ) {
+      $debug and warn "Anonymous LDAP bind failed: ". description($res);
+      return 0;
+    }
+
+    # Perform a LDAP search for the given username
+    my $search = search_method($db, $userid) or return 0;   # warnings are in the sub
+    $userldapentry = $search->shift_entry;
+
+    # Perform a LDAP bind for the given username using the matched DN
+    $res = $db->bind( $userldapentry->dn, password => $password );
+    if ( $res->code ) {
+      $debug and warn "LDAP bind failed as kohauser $userid: ". description($res);
+      return 0;
+    }
+
+  } else {
+               my $res = ($config{anonymous}) ? $db->bind : $db->bind($ldapname, password=>$ldappassword);
+               if ($res->code) {               # connection refused
+                       warn "LDAP bind failed as ldapuser " . ($ldapname || '[ANONYMOUS]') . ": " . description($res);
+                       return 0;
+               }
         my $search = search_method($db, $userid) or return 0;   # warnings are in the sub
         $userldapentry = $search->shift_entry;
                my $cmpmesg = $db->compare( $userldapentry, attr=>'userpassword', value => $password );
@@ -150,6 +158,7 @@ sub checkpw_ldap {
             ($cardnumber eq $c2) or warn "update_local returned cardnumber '$c2' instead of '$cardnumber'";
         } else { # C1, D1
             # maybe update just the password?
+               return(1, $cardnumber, $local_userid);
         }
     } elsif ($config{replicate}) { # A2, C2
         $borrowernumber = AddMember(%borrower) or die "AddMember failed";
@@ -157,9 +166,13 @@ sub checkpw_ldap {
         return 0;   # B2, D2
     }
        if (C4::Context->preference('ExtendedPatronAttributes') && $borrowernumber && ($config{update} ||$config{replicate})) {
-               my @types = C4::Members::AttributeTypes::GetAttributeTypes();
-               my @attributes = grep{my $key=$_; any{$_ eq $key}@types;} keys %borrower;
-               my $extended_patron_attributes = map{{code=>$_,value=>$borrower{$_}}}@attributes;
+        my $extended_patron_attributes;
+        foreach my $attribute_type ( C4::Members::AttributeTypes::GetAttributeTypes() ) {
+                my $code = $attribute_type->{code};
+                if ( exists($borrower{$code}) && $borrower{$code} !~ m/^\s*$/ ) { # skip empty values
+                        push @$extended_patron_attributes, { code => $code, value => $borrower{$code} };
+                }
+        }
                my @errors;
                #Check before add
                for (my $i; $i< scalar(@$extended_patron_attributes)-1;$i++) {
@@ -175,7 +188,7 @@ sub checkpw_ldap {
                }
            C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
        }
-return(1, $cardnumber);
+return(1, $cardnumber, $userid);
 }
 
 # Pass LDAP entry object and local cardnumber (userid).
@@ -183,7 +196,7 @@ return(1, $cardnumber);
 # Edit KOHA_CONF so $memberhash{'xxx'} fits your ldap structure.
 # Ensure that mandatory fields are correctly filled!
 #
-sub ldap_entry_2_hash ($$) {
+sub ldap_entry_2_hash {
        my $userldapentry = shift;
        my %borrower = ( cardnumber => shift );
        my %memberhash;
@@ -195,7 +208,7 @@ sub ldap_entry_2_hash ($$) {
                        hashdump("LDAP key: ",$userldapentry->{$_});
                }
        }
-       my $x = $userldapentry->{attrs} or return undef;
+       my $x = $userldapentry->{attrs} or return;
        foreach (keys %$x) {
                $memberhash{$_} = join ' ', @{$x->{$_}};        
                $debug and print STDERR sprintf("building \$memberhash{%s} = ", $_, join(' ', @{$x->{$_}})), "\n";
@@ -203,7 +216,7 @@ sub ldap_entry_2_hash ($$) {
        $debug and print STDERR "Finsihed \%memberhash has ", scalar(keys %memberhash), " keys\n",
                                        "Referencing \%mapping with ", scalar(keys %mapping), " keys\n";
        foreach my $key (keys %mapping) {
-               my  $data = $memberhash{$mapping{$key}->{is}}; 
+               my  $data = $memberhash{ lc($mapping{$key}->{is}) }; # Net::LDAP returns all names in lowercase
                $debug and printf STDERR "mapping %20s ==> %-20s (%s)\n", $key, $mapping{$key}->{is}, $data;
                unless (defined $data) { 
                        $data = $mapping{$key}->{content} || '';        # default or failsafe ''
@@ -214,10 +227,21 @@ sub ldap_entry_2_hash ($$) {
                ( substr($borrower{'firstname'},0,1)
                . substr($borrower{ 'surname' },0,1)
                . " ");
+
+       # check if categorycode exists, if not, fallback to default from koha-conf.xml
+       my $dbh = C4::Context->dbh;
+       my $sth = $dbh->prepare("SELECT categorycode FROM categories WHERE categorycode = ?");
+       $sth->execute( uc($borrower{'categorycode'}) );
+       unless ( my $row = $sth->fetchrow_hashref ) {
+               my $default = $mapping{'categorycode'}->{content};
+               $debug && warn "Can't find ", $borrower{'categorycode'}, " default to: $default for ", $borrower{userid};
+               $borrower{'categorycode'} = $default
+       }
+
        return %borrower;
 }
 
-sub exists_local($) {
+sub exists_local {
        my $arg = shift;
        my $dbh = C4::Context->dbh;
        my $select = "SELECT borrowernumber,cardnumber,userid,password FROM borrowers ";
@@ -246,16 +270,16 @@ sub _do_changepassword {
                my ($md5password, $cardnum) = $sth->fetchrow;
         ($digest eq $md5password) and return $cardnum;
                warn "Password mismatch after update to cardnumber=$cardnum (borrowernumber=$borrowerid)";
-               return undef;
+               return;
        }
        die "Unexpected error after password update to userid/borrowernumber: $userid / $borrowerid.";
 }
 
-sub update_local($$$$) {
-       my   $userid   = shift             or return undef;
-       my   $digest   = md5_base64(shift) or return undef;
-       my $borrowerid = shift             or return undef;
-       my $borrower   = shift             or return undef;
+sub update_local {
+       my   $userid   = shift             or return;
+       my   $digest   = md5_base64(shift) or return;
+       my $borrowerid = shift             or return;
+       my $borrower   = shift             or return;
        my @keys = keys %$borrower;
        my $dbh = C4::Context->dbh;
        my $query = "UPDATE  borrowers\nSET     " . 
@@ -301,62 +325,78 @@ C4::Auth - Authenticates Koha users
        What are the required fields?  Well, in mysql you can check the database table "borrowers" like this:
 
        mysql> show COLUMNS from borrowers;
-               +------------------+--------------+------+-----+---------+----------------+
-               | Field            | Type         | Null | Key | Default | Extra          |
-               +------------------+--------------+------+-----+---------+----------------+
-               | borrowernumber   | int(11)      | NO   | PRI | NULL    | auto_increment | 
-               | cardnumber       | varchar(16)  | YES  | UNI | NULL    |                | 
-               | surname          | mediumtext   | NO   |     |         |                | 
-               | firstname        | text         | YES  |     | NULL    |                | 
-               | title            | mediumtext   | YES  |     | NULL    |                | 
-               | othernames       | mediumtext   | YES  |     | NULL    |                | 
-               | initials         | text         | YES  |     | NULL    |                | 
-               | streetnumber     | varchar(10)  | YES  |     | NULL    |                | 
-               | streettype       | varchar(50)  | YES  |     | NULL    |                | 
-               | address          | mediumtext   | NO   |     |         |                | 
-               | address2         | text         | YES  |     | NULL    |                | 
-               | city             | mediumtext   | NO   |     |         |                | 
-               | zipcode          | varchar(25)  | YES  |     | NULL    |                | 
-               | email            | mediumtext   | YES  |     | NULL    |                | 
-               | phone            | text         | YES  |     | NULL    |                | 
-               | mobile           | varchar(50)  | YES  |     | NULL    |                | 
-               | fax              | mediumtext   | YES  |     | NULL    |                | 
-               | emailpro         | text         | YES  |     | NULL    |                | 
-               | phonepro         | text         | YES  |     | NULL    |                | 
-               | B_streetnumber   | varchar(10)  | YES  |     | NULL    |                | 
-               | B_streettype     | varchar(50)  | YES  |     | NULL    |                | 
-               | B_address        | varchar(100) | YES  |     | NULL    |                | 
-               | B_city           | mediumtext   | YES  |     | NULL    |                | 
-               | B_zipcode        | varchar(25)  | YES  |     | NULL    |                | 
-               | B_email          | text         | YES  |     | NULL    |                | 
-               | B_phone          | mediumtext   | YES  |     | NULL    |                | 
-               | dateofbirth      | date         | YES  |     | NULL    |                | 
-               | branchcode       | varchar(10)  | NO   | MUL |         |                | 
-               | categorycode     | varchar(10)  | NO   | MUL |         |                | 
-               | dateenrolled     | date         | YES  |     | NULL    |                | 
-               | dateexpiry       | date         | YES  |     | NULL    |                | 
-               | gonenoaddress    | tinyint(1)   | YES  |     | NULL    |                | 
-               | lost             | tinyint(1)   | YES  |     | NULL    |                | 
-               | debarred         | tinyint(1)   | YES  |     | NULL    |                | 
-               | contactname      | mediumtext   | YES  |     | NULL    |                | 
-               | contactfirstname | text         | YES  |     | NULL    |                | 
-               | contacttitle     | text         | YES  |     | NULL    |                | 
-               | guarantorid      | int(11)      | YES  |     | NULL    |                | 
-               | borrowernotes    | mediumtext   | YES  |     | NULL    |                | 
-               | relationship     | varchar(100) | YES  |     | NULL    |                | 
-               | ethnicity        | varchar(50)  | YES  |     | NULL    |                | 
-               | ethnotes         | varchar(255) | YES  |     | NULL    |                | 
-               | sex              | varchar(1)   | YES  |     | NULL    |                | 
-               | password         | varchar(30)  | YES  |     | NULL    |                | 
-               | flags            | int(11)      | YES  |     | NULL    |                | 
-               | userid           | varchar(30)  | YES  | MUL | NULL    |                |  # UNIQUE in next release.
-               | opacnote         | mediumtext   | YES  |     | NULL    |                | 
-               | contactnote      | varchar(255) | YES  |     | NULL    |                | 
-               | sort1            | varchar(80)  | YES  |     | NULL    |                | 
-               | sort2            | varchar(80)  | YES  |     | NULL    |                | 
-               +------------------+--------------+------+-----+---------+----------------+
-               50 rows in set (0.01 sec)
-       
+               +---------------------+--------------+------+-----+---------+----------------+
+               | Field               | Type         | Null | Key | Default | Extra          |
+               +---------------------+--------------+------+-----+---------+----------------+
+               | borrowernumber      | int(11)      | NO   | PRI | NULL    | auto_increment |
+               | cardnumber          | varchar(16)  | YES  | UNI | NULL    |                |
+               | surname             | mediumtext   | NO   |     | NULL    |                |
+               | firstname           | text         | YES  |     | NULL    |                |
+               | title               | mediumtext   | YES  |     | NULL    |                |
+               | othernames          | mediumtext   | YES  |     | NULL    |                |
+               | initials            | text         | YES  |     | NULL    |                |
+               | streetnumber        | varchar(10)  | YES  |     | NULL    |                |
+               | streettype          | varchar(50)  | YES  |     | NULL    |                |
+               | address             | mediumtext   | NO   |     | NULL    |                |
+               | address2            | text         | YES  |     | NULL    |                |
+               | city                | mediumtext   | NO   |     | NULL    |                |
+               | state               | mediumtext   | YES  |     | NULL    |                |
+               | zipcode             | varchar(25)  | YES  |     | NULL    |                |
+               | country             | text         | YES  |     | NULL    |                |
+               | email               | mediumtext   | YES  |     | NULL    |                |
+               | phone               | text         | YES  |     | NULL    |                |
+               | mobile              | varchar(50)  | YES  |     | NULL    |                |
+               | fax                 | mediumtext   | YES  |     | NULL    |                |
+               | emailpro            | text         | YES  |     | NULL    |                |
+               | phonepro            | text         | YES  |     | NULL    |                |
+               | B_streetnumber      | varchar(10)  | YES  |     | NULL    |                |
+               | B_streettype        | varchar(50)  | YES  |     | NULL    |                |
+               | B_address           | varchar(100) | YES  |     | NULL    |                |
+               | B_address2          | text         | YES  |     | NULL    |                |
+               | B_city              | mediumtext   | YES  |     | NULL    |                |
+               | B_state             | mediumtext   | YES  |     | NULL    |                |
+               | B_zipcode           | varchar(25)  | YES  |     | NULL    |                |
+               | B_country           | text         | YES  |     | NULL    |                |
+               | B_email             | text         | YES  |     | NULL    |                |
+               | B_phone             | mediumtext   | YES  |     | NULL    |                |
+               | dateofbirth         | date         | YES  |     | NULL    |                |
+               | branchcode          | varchar(10)  | NO   | MUL |         |                |
+               | categorycode        | varchar(10)  | NO   | MUL |         |                |
+               | dateenrolled        | date         | YES  |     | NULL    |                |
+               | dateexpiry          | date         | YES  |     | NULL    |                |
+               | gonenoaddress       | tinyint(1)   | YES  |     | NULL    |                |
+               | lost                | tinyint(1)   | YES  |     | NULL    |                |
+               | debarred            | date         | YES  |     | NULL    |                |
+               | debarredcomment     | varchar(255) | YES  |     | NULL    |                |
+               | contactname         | mediumtext   | YES  |     | NULL    |                |
+               | contactfirstname    | text         | YES  |     | NULL    |                |
+               | contacttitle        | text         | YES  |     | NULL    |                |
+               | guarantorid         | int(11)      | YES  | MUL | NULL    |                |
+               | borrowernotes       | mediumtext   | YES  |     | NULL    |                |
+               | relationship        | varchar(100) | YES  |     | NULL    |                |
+               | ethnicity           | varchar(50)  | YES  |     | NULL    |                |
+               | ethnotes            | varchar(255) | YES  |     | NULL    |                |
+               | sex                 | varchar(1)   | YES  |     | NULL    |                |
+               | password            | varchar(30)  | YES  |     | NULL    |                |
+               | flags               | int(11)      | YES  |     | NULL    |                |
+               | userid              | varchar(30)  | YES  | MUL | NULL    |                |
+               | opacnote            | mediumtext   | YES  |     | NULL    |                |
+               | contactnote         | varchar(255) | YES  |     | NULL    |                |
+               | sort1               | varchar(80)  | YES  |     | NULL    |                |
+               | sort2               | varchar(80)  | YES  |     | NULL    |                |
+               | altcontactfirstname | varchar(255) | YES  |     | NULL    |                |
+               | altcontactsurname   | varchar(255) | YES  |     | NULL    |                |
+               | altcontactaddress1  | varchar(255) | YES  |     | NULL    |                |
+               | altcontactaddress2  | varchar(255) | YES  |     | NULL    |                |
+               | altcontactaddress3  | varchar(255) | YES  |     | NULL    |                |
+               | altcontactstate     | mediumtext   | YES  |     | NULL    |                |
+               | altcontactzipcode   | varchar(50)  | YES  |     | NULL    |                |
+               | altcontactcountry   | text         | YES  |     | NULL    |                |
+               | altcontactphone     | varchar(50)  | YES  |     | NULL    |                |
+               | smsalertnumber      | varchar(50)  | YES  |     | NULL    |                |
+               | privacy             | int(11)      | NO   |     | 1       |                |
+               +---------------------+--------------+------+-----+---------+----------------+
+               66 rows in set (0.00 sec)
                Where Null="NO", the field is required.
 
 =head1 KOHA_CONF and field mapping
@@ -376,8 +416,6 @@ Example XML stanza for LDAP configuration in KOHA_CONF.
     <update>1</update>             <!-- update existing users in Koha database -->
     <auth_by_bind>0</auth_by_bind> <!-- set to 1 to authenticate by binding instead of
                                         password comparison, e.g., to use Active Directory -->
-    <principal_name>%s@my_domain.com</principal_name>
-                                   <!-- optional, for auth_by_bind: a printf format to make userPrincipalName from koha userid -->
     <mapping>                  <!-- match koha SQL field names to your LDAP record field names -->
       <firstname    is="givenname"      ></firstname>
       <surname      is="sn"             ></surname>