-
Notifications
You must be signed in to change notification settings - Fork 348
/
ILSAuthenticator.php
386 lines (357 loc) · 11.9 KB
/
ILSAuthenticator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
/**
* Class for managing ILS-specific authentication.
*
* PHP version 8
*
* Copyright (C) Villanova University 2007.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Authentication
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Auth;
use Laminas\Config\Config;
use Laminas\Crypt\BlockCipher;
use Laminas\Crypt\Symmetric\Openssl;
use VuFind\Db\Entity\UserEntityInterface;
use VuFind\Exception\ILS as ILSException;
use VuFind\ILS\Connection as ILSConnection;
/**
* Class for managing ILS-specific authentication.
*
* @category VuFind
* @package Authentication
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class ILSAuthenticator
{
/**
* Callback for retrieving the authentication manager
*
* @var callable
*/
protected $authManagerCallback;
/**
* Authentication manager
*
* @var Manager
*/
protected $authManager = null;
/**
* Cache for ILS account information (keyed by username)
*
* @var array
*/
protected $ilsAccount = [];
/**
* Is encryption enabled?
*
* @var bool
*/
protected $encryptionEnabled = null;
/**
* Encryption key used for catalog passwords (null if encryption disabled):
*
* @var string
*/
protected $encryptionKey = null;
/**
* Constructor
*
* @param callable $authCB Auth manager callback
* @param ILSConnection $catalog ILS connection
* @param ?EmailAuthenticator $emailAuthenticator Email authenticator
* @param ?Config $config Configuration from config.ini
*/
public function __construct(
callable $authCB,
protected ILSConnection $catalog,
protected ?EmailAuthenticator $emailAuthenticator = null,
protected ?Config $config = null
) {
$this->authManagerCallback = $authCB;
}
/**
* Is ILS password encryption enabled?
*
* @return bool
*/
public function passwordEncryptionEnabled()
{
if (null === $this->encryptionEnabled) {
$this->encryptionEnabled
= $this->config->Authentication->encrypt_ils_password ?? false;
}
return $this->encryptionEnabled;
}
/**
* Decrypt text.
*
* @param ?string $text The text to decrypt (null values will be returned as null)
*
* @return ?string|bool The decrypted string (null if empty or false if invalid)
* @throws \VuFind\Exception\PasswordSecurity
*/
public function decrypt(?string $text)
{
return $this->encryptOrDecrypt($text, false);
}
/**
* Encrypt text.
*
* @param ?string $text The text to encrypt (null values will be returned as null)
*
* @return ?string|bool The encrypted string (null if empty or false if invalid)
* @throws \VuFind\Exception\PasswordSecurity
*/
public function encrypt(?string $text)
{
return $this->encryptOrDecrypt($text, true);
}
/**
* This is a central function for encrypting and decrypting so that
* logic is all in one location
*
* @param ?string $text The text to be encrypted or decrypted
* @param bool $encrypt True if we wish to encrypt text, False if we wish to
* decrypt text.
*
* @return ?string|bool The encrypted/decrypted string (null = empty input; false = error)
* @throws \VuFind\Exception\PasswordSecurity
*/
protected function encryptOrDecrypt(?string $text, bool $encrypt = true)
{
// Ignore empty text:
if ($text === null || $text === '') {
return null;
}
$configAuth = $this->config->Authentication ?? new \Laminas\Config\Config([]);
// Load encryption key from configuration if not already present:
if ($this->encryptionKey === null) {
if (empty($configAuth->ils_encryption_key)) {
throw new \VuFind\Exception\PasswordSecurity(
'ILS password encryption on, but no key set.'
);
}
$this->encryptionKey = $configAuth->ils_encryption_key;
}
// Perform encryption:
$algo = $configAuth->ils_encryption_algo ?? 'blowfish';
// Check if OpenSSL error is caused by blowfish support
try {
$cipher = new BlockCipher(new Openssl(['algorithm' => $algo]));
if ($algo == 'blowfish') {
trigger_error(
'Deprecated encryption algorithm (blowfish) detected',
E_USER_DEPRECATED
);
}
} catch (\InvalidArgumentException $e) {
if ($algo == 'blowfish') {
throw new \VuFind\Exception\PasswordSecurity(
'The blowfish encryption algorithm ' .
'is not supported by your version of OpenSSL. ' .
'Please visit /Upgrade/CriticalFixBlowfish for further details.'
);
} else {
throw $e;
}
}
$cipher->setKey($this->encryptionKey);
return $encrypt ? $cipher->encrypt($text) : $cipher->decrypt($text);
}
/**
* Given a user object, retrieve the decrypted password (or null if unset/invalid).
*
* @param UserEntityInterface $user User
*
* @return ?string
*/
public function getCatPasswordForUser(UserEntityInterface $user)
{
if ($this->passwordEncryptionEnabled()) {
$encrypted = $user->getCatPassEnc();
$decrypted = !empty($encrypted) ? $this->decrypt($encrypted) : null;
if ($decrypted === false) {
// Unexpected error decrypting password; let's treat it as unset for now:
return null;
}
return $decrypted;
}
return $user->getRawCatPassword();
}
/**
* Get stored catalog credentials for the current user.
*
* Returns associative array of cat_username and cat_password if they are
* available, false otherwise. This method does not verify that the credentials
* are valid.
*
* @return array|bool
*/
public function getStoredCatalogCredentials()
{
// Fail if no username is found, but allow a missing password (not every ILS
// requires a password to connect).
if (($user = $this->getAuthManager()->getUserObject()) && ($username = $user->getCatUsername())) {
return [
'cat_username' => $username,
'cat_password' => $this->getCatPasswordForUser($user),
];
}
return false;
}
/**
* Log the current user into the catalog using stored credentials; if this
* fails, clear the user's stored credentials so they can enter new, corrected
* ones.
*
* Returns associative array of patron data on success, false on failure.
*
* @return array|bool
*/
public function storedCatalogLogin()
{
// Fail if no username is found, but allow a missing password (not every ILS
// requires a password to connect).
if (($user = $this->getAuthManager()->getUserObject()) && ($username = $user->getCatUsername())) {
// Do we have a previously cached ILS account?
if (isset($this->ilsAccount[$username])) {
return $this->ilsAccount[$username];
}
$patron = $this->catalog->patronLogin(
$username,
$this->getCatPasswordForUser($user)
);
if (empty($patron)) {
// Problem logging in -- clear user credentials so they can be
// prompted again; perhaps their password has changed in the
// system!
$user->clearCredentials();
} else {
// cache for future use
$this->ilsAccount[$username] = $patron;
return $patron;
}
}
return false;
}
/**
* Attempt to log in the user to the ILS, and save credentials if it works.
*
* @param string $username Catalog username
* @param string $password Catalog password
*
* Returns associative array of patron data on success, false on failure.
*
* @return array|bool
* @throws ILSException
*/
public function newCatalogLogin($username, $password)
{
$result = $this->catalog->patronLogin($username, $password);
if ($result) {
$this->updateUser($username, $password, $result);
return $result;
}
return false;
}
/**
* Send email authentication link
*
* @param string $email Email address
* @param string $route Route for the login link
* @param array $routeParams Route parameters
* @param array $urlParams URL parameters
*
* @return void
*/
public function sendEmailLoginLink($email, $route, $routeParams = [], $urlParams = [])
{
if (null === $this->emailAuthenticator) {
throw new \Exception('Email authenticator not set');
}
$userData = $this->catalog->patronLogin($email, '');
if ($userData) {
$this->emailAuthenticator->sendAuthenticationLink(
$userData['email'],
compact('userData'),
['auth_method' => 'ILS'] + $urlParams,
$route,
$routeParams
);
}
}
/**
* Process email login
*
* @param string $hash Login hash
*
* @return array|bool
* @throws ILSException
*/
public function processEmailLoginHash($hash)
{
if (null === $this->emailAuthenticator) {
throw new \Exception('Email authenticator not set');
}
try {
$loginData = $this->emailAuthenticator->authenticate($hash);
// Check if we have more granular data available:
$patron = $loginData['userData'] ?? $loginData;
} catch (\VuFind\Exception\Auth $e) {
return false;
}
$this->updateUser($patron['cat_username'], '', $patron);
return $patron;
}
/**
* Update current user account with the patron information
*
* @param string $catUsername Catalog username
* @param string $catPassword Catalog password
* @param array $patron Patron
*
* @return void
*/
protected function updateUser($catUsername, $catPassword, $patron)
{
$user = $this->getAuthManager()->getUserObject();
if ($user) {
$user->saveCredentials($catUsername, $catPassword);
$this->getAuthManager()->updateSession($user);
// cache for future use
$this->ilsAccount[$catUsername] = $patron;
}
}
/**
* Get authentication manager
*
* @return Manager
*/
protected function getAuthManager(): Manager
{
if (null === $this->authManager) {
$this->authManager = ($this->authManagerCallback)();
}
return $this->authManager;
}
}