From e0ccbd77cfd01ada91ab8012656ee83a3704f32c Mon Sep 17 00:00:00 2001
From: Galen Charlton <gmc@esilibrary.com>
Date: Thu, 5 Mar 2015 17:10:50 +0000
Subject: [PATCH] Update Koha driver to recognize either MD5 or bcrypt password
 hashes

Koha 3.14 and later uses bcrypt to hash passwords; previously
it used md5_base64. This patch updates the driver so that it can
handle both.

Thanks to Olugbenga Adara for testing.
---
 module/VuFind/src/VuFind/ILS/Driver/Koha.php | 29 +++++++++++++++++---
 1 file changed, 25 insertions(+), 4 deletions(-)

diff --git a/module/VuFind/src/VuFind/ILS/Driver/Koha.php b/module/VuFind/src/VuFind/ILS/Driver/Koha.php
index 6a609a52dde..1c0e0d380b7 100644
--- a/module/VuFind/src/VuFind/ILS/Driver/Koha.php
+++ b/module/VuFind/src/VuFind/ILS/Driver/Koha.php
@@ -481,10 +481,31 @@ class Koha extends AbstractBase
         $patron = [];
         $row = '';
 
-        // Koha uses MD5_BASE64 encoding to save borrowers' passwords, function
-        // 'rtrim' is used to discard trailing '=' signs, suitable for pushing
-        // into MySQL database
-        $db_pwd = rtrim(base64_encode(pack('H*', md5($password))), '=');
+        $stored_hash = '';
+        try {
+            $sql = "select password from borrowers where userid = :username";
+            $sqlStmt = $this->db->prepare($sql);
+            $sqlStmt->execute([':username' => $username]);
+            $row = $sqlStmt->fetch();
+            if ($row) {
+                $stored_hash = $row['password'];
+            } else {
+                return null;
+            }
+        }
+        catch (PDOException $e) {
+            throw new ILSException($e->getMessage());
+        }
+
+        if ("$2a$" == substr($stored_hash, 0, 4)) {
+            // Newer Koha version that uses bcrypt
+            $db_pwd = crypt($password, $stored_hash);
+        } else {
+            // Koha used to use MD5_BASE64 encoding to save borrowers' passwords, function
+            // 'rtrim' is used to discard trailing '=' signs, suitable for pushing
+            // into MySQL database
+            $db_pwd = rtrim(base64_encode(pack('H*', md5($password))), '=');
+        }
 
         $sql = "select borrowernumber as ID, firstname as FNAME, " .
             "surname as LNAME, email as EMAIL from borrowers " .
-- 
GitLab