option to disable nomination process status check
[fsfdrupalauth.git] / lib / Auth / Source / FSFDrupalAuth.php
1 <?php
2
3 namespace SimpleSAML\Module\fsfdrupalauth\Auth\Source;
4
5 use Exception;
6 use PDO;
7 use PDOException;
8 use SimpleSAML\Error;
9 use SimpleSAML\Logger;
10
11 /**
12 * Extension of simple SQL authentication source
13 *
14 * @package SimpleSAMLphp
15 */
16
17 class FSFDrupalAuth extends \SimpleSAML\Module\core\Auth\UserPassBase
18 {
19 /**
20 * The DSN we should connect to.
21 */
22 private $dsn;
23
24 /**
25 * The username we should connect to the database with.
26 */
27 private $username;
28
29 /**
30 * The password we should connect to the database with.
31 */
32 private $password;
33
34 /**
35 * The options that we should connect to the database with.
36 */
37 private $options;
38
39 /**
40 * The query we should use to retrieve the attributes for the user.
41 *
42 * The username and password will be available as :username and :password.
43 */
44 private $query_main;
45 private $query_membership;
46 private $query_staff;
47 private $query_nomination_process_donations;
48 private $query_nomination_process_gift_receipt;
49 private $query_nomination_process_adhoc;
50
51 /**
52 * SQL query parameters, or variables that help determine which attributes
53 * someone has
54 */
55 private $fsf_org_id;
56 private $gift_redeem_page_id;
57
58 private $nomination_process_active;
59 private $nomination_process_contrib_start_date;
60 private $nomination_process_contrib_end_date;
61 private $nomination_process_adhoc_access_group_id;
62 private $membership_monthly_rate;
63 private $student_membership_monthly_rate;
64
65 /**
66 * Constructor for this authentication source.
67 *
68 * @param array $info Information about this authentication source.
69 * @param array $config Configuration.
70 */
71 public function __construct($info, $config)
72 {
73 assert(is_array($info));
74 assert(is_array($config));
75
76 // Call the parent constructor first, as required by the interface
77 parent::__construct($info, $config);
78
79 // Make sure that all required parameters are present.
80 foreach (['dsn',
81 'username',
82 'password',
83
84 'query_main',
85 'query_membership',
86 'query_staff',
87
88 'query_nomination_process_donations',
89 'query_nomination_process_gift_receipt',
90 'query_nomination_process_adhoc',
91
92 'fsf_org_id',
93 'gift_redeem_page_id',
94
95 'nomination_process_active',
96 'nomination_process_contrib_start_date',
97 'nomination_process_contrib_end_date',
98 'nomination_process_adhoc_access_group_id',
99 'membership_monthly_rate',
100 'student_membership_monthly_rate']
101 as $param) {
102
103 if (!array_key_exists($param, $config)) {
104 throw new Exception('Missing required attribute \''.$param.
105 '\' for authentication source '.$this->authId);
106 }
107
108 if (!is_string($config[$param])) {
109 throw new Exception('Expected parameter \''.$param.
110 '\' for authentication source '.$this->authId.
111 ' to be a string. Instead it was: '.
112 var_export($config[$param], true));
113 }
114
115 $this->$param = $config[$param];
116 }
117
118 if (isset($config['options'])) {
119 $this->options = $config['options'];
120 }
121 }
122
123
124 /**
125 * Create a database connection.
126 *
127 * @return PDO The database connection.
128 */
129 private function connect()
130 {
131 try {
132 $db = new PDO($this->dsn, $this->username, $this->password, $this->options);
133 } catch (PDOException $e) {
134 // Obfuscate the password if it's part of the dsn
135 $obfuscated_dsn = preg_replace('/(user|password)=(.*?([;]|$))/', '${1}=***', $this->dsn);
136
137 throw new Exception('fsfdrupalauth:' . $this->authId . ': - Failed to connect to \'' .
138 $obfuscated_dsn . '\': ' . $e->getMessage());
139 }
140
141 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
142
143 $driver = explode(':', $this->dsn, 2);
144 $driver = strtolower($driver[0]);
145
146 // Driver specific initialization
147 switch ($driver) {
148 case 'mysql':
149 // Use UTF-8
150 $db->exec("SET NAMES 'utf8mb4'");
151 break;
152 case 'pgsql':
153 // Use UTF-8
154 $db->exec("SET NAMES 'UTF8'");
155 break;
156 }
157
158 return $db;
159 }
160
161 /*
162 * Check the password against a Drupal hash
163 *
164 */
165 private function check_password($password, $hash) {
166
167 //
168 // The reason for running a separate process is so that the PHP global
169 // env doesn't get clobbered by include / require.
170 //
171
172 // pipes code based off of https://www.php.net/manual/en/function.proc-open.php
173 // CC-BY 3.0 or later
174 $descriptorspec = array(
175 0 => array("pipe", "r"), // stdin is a pipe that the child may read from
176 1 => array("pipe", "w"), // stdout is a pipe that the child may write to
177 2 => array("pipe", "w") // stderr is a pipe that the child may write to
178 );
179
180 $cwd = "../modules/fsfdrupalauth/extlib";
181 //$env = array('some_option' => 'aeiou');
182 $env = array();
183
184 $process = proc_open('php drupal-pw-check.php', $descriptorspec, $pipes, $cwd, $env);
185
186 if (is_resource($process)) {
187 // $pipes now looks like this:
188 // 0 => writeable handle connected to child stdin
189 // 1 => readable handle connected to child stdout
190
191 fwrite($pipes[0], json_encode([$password, $hash]));
192 fclose($pipes[0]);
193
194 $result = stream_get_contents($pipes[1]);
195 fclose($pipes[1]);
196
197 $errors = stream_get_contents($pipes[2]);
198 fclose($pipes[2]);
199
200 // It is important that you close any pipes before calling
201 // proc_close in order to avoid a deadlock
202 $return_value = proc_close($process);
203
204 //Logger::debug('fsfdrupalauth:'.$this->authId.': authenticator stdout: '.$result);
205
206 $errors_found_yet = false;
207 if ($errors != "") {
208 Logger::error('fsfdrupalauth:'.$this->authId.': authenticator stderr: '.$errors);
209 $errors_found_yet = true;
210 }
211
212 if ($return_value != 0) {
213 Logger::error('fsfdrupalauth:'.$this->authId.': authenticator non-zero return code: '.$return_value);
214 $errors_found_yet = true;
215 }
216
217 return (!$errors_found_yet && is_string($result) && rtrim($result) == "true");
218
219 } else {
220
221 Logger::error('fsfdrupalauth:'.$this->authId.': unable to launch authenticator');
222
223 return false;
224 }
225 }
226
227 /**
228 *
229 * query the database with arbitrary queries that only require a user name.
230 *
231 */
232 private function query_db($queryname, $query_params)
233 {
234 assert(is_string($queryname));
235 assert(is_string($username));
236
237 $db = $this->connect();
238
239 try {
240 $sth = $db->prepare($this->$queryname);
241 } catch (PDOException $e) {
242 throw new Exception('fsfdrupalauth:'.$this->authId.
243 ': - Failed to prepare queryname: '.$queryname.': '.$e->getMessage());
244 }
245
246 try {
247 $sth->execute($query_params);
248 } catch (PDOException $e) {
249 throw new Exception('fsfdrupalauth:'.$this->authId.
250 ': - Failed to execute queryname: '.$queryname.': '.$e->getMessage());
251 }
252
253 try {
254 $data = $sth->fetchAll(PDO::FETCH_ASSOC);
255 } catch (PDOException $e) {
256 throw new Exception('fsfdrupalauth:'.$this->authId.
257 ': - Failed to fetch result set: '.$e->getMessage());
258 }
259
260 Logger::info('fsfdrupalauth:'.$this->authId.': Got '.count($data).
261 ' rows from database');
262
263 return $data;
264 }
265
266 /**
267 * add more CAS attributes to user, such as is_staff and is_member
268 */
269 private function add_more_attributes(&$attributes, $username) {
270
271 //
272 // query on membership
273 //
274
275 $membership_data = $this->query_db('query_membership', ['username' => $username]);
276
277 if (count($membership_data) === 0) {
278 // No rows returned - invalid username
279 Logger::debug('fsfdrupalauth:'.$this->authId.
280 ': No rows in result set. Probably no membership.');
281 }
282
283 $attributes['is_member'] = ['false'];
284 $attributes['was_member'] = ['false'];
285
286 foreach ($membership_data as $row) {
287 foreach ($row as $key => $value) {
288 if ($value === null) {
289 continue;
290 }
291 $value = (string) $value;
292
293 if ($value === '1' || $value === '2' || $value === '3') {
294 $attributes['is_member'] = ['true'];
295 $attributes['was_member'] = ['true'];
296 } elseif ($value === '4') {
297 $attributes['was_member'] = ['true'];
298 }
299 }
300 }
301
302 //
303 // query for access to board nomination process
304 //
305
306 $start_date = $this->nomination_process_contrib_start_date;
307 $end_date = $this->nomination_process_contrib_end_date;
308
309 /**
310 * @param string $query_name Name of query in authsources
311 * @param array $extra_params Associative array of parameters to include in query
312 */
313 $donation_query = function ($query_name, $extra_params)
314 use ($username) {
315
316 $parameters = ['username' => $username];
317
318 foreach ($extra_params as $key => $value) {
319 $parameters[$key] = $value;
320 }
321
322 return $this->query_db($query_name, $parameters);
323 };
324
325 $compare_res = function ($result, $amount) {
326 foreach ($result[0] as $key => $value) {
327 if (intval($value) >= $amount) {
328 return true;
329 }
330 }
331 return false;
332 };
333
334 // looks for memberships / comparable donations in time window. also
335 // looks for a membership or donation (included as a param) that
336 // occurred up to a year before, and that would have carried over into
337 // the time window with a single donation. this approximates whether
338 // the person was, or would have been, a member during the configured
339 // time window.
340 $analyze_history = function ($selective_donations_history)
341 use ($start_date, $end_date) {
342
343 $eligible = false;
344
345 $start_date_obj = new \DateTime($start_date);
346 $end_date_obj = new \DateTime($end_date);
347
348 foreach ($selective_donations_history as $row) {
349
350 $amount = intval($row['amount']);
351 $member_type_id = $row['member_type_id'];
352 $receive_date_obj = new \DateTime($row['receive_date']);
353
354 if ($amount < 5) {
355 continue;
356
357 } elseif ($receive_date_obj >= $start_date_obj and $receive_date_obj <= $end_date_obj) {
358 return true;
359
360 } elseif ($receive_date_obj < $start_date_obj) {
361 switch ($member_type_id) {
362 case '1':
363 case '2':
364 $rate = intval($this->student_membership_monthly_rate);
365 break;
366 case '8':
367 case '9':
368 case null:
369 default:
370 $rate = intval($this->membership_monthly_rate);
371 break;
372 }
373 $membership_end_date_obj = new \DateTime($row['receive_date']);
374 $membership_end_date_obj->add(new \DateInterval("P" . ceil($amount / $rate) . "M"));
375
376 if ($membership_end_date_obj >= $start_date_obj) {
377 return true;
378 }
379 }
380 }
381 return false;
382 };
383
384 $donation_params = ['start_date' => $start_date, 'end_date' => $end_date];
385 $gift_member_params = ['start_date' => $start_date, 'end_date' => $end_date, 'gift_redeem_page_id' => intval($this->gift_redeem_page_id)];
386 $adhoc_params = ['adhoc_access_group_id' => intval($this->nomination_process_adhoc_access_group_id)];
387
388 if ($this->nomination_process_active == 'true' ) {
389 if ($compare_res($donation_query('query_nomination_process_adhoc', $adhoc_params), 1) || ($attributes['is_member'] == ['true']
390 && ($analyze_history($donation_query('query_nomination_process_donations', $donation_params))
391 || $compare_res($donation_query('query_nomination_process_gift_receipt', $gift_member_params), 1)))) {
392
393 $attributes['nomination_process'] = ['true'];
394 } else {
395 Logger::debug('fsfdrupalauth:'.$this->authId.
396 ': Not a member / comparable donor during window for board process.');
397 $attributes['nomination_process'] = ['false'];
398 }
399 } else {
400 $attributes['nomination_process'] = ['false'];
401 }
402
403 //
404 // query on staff
405 //
406
407 $staff_data = $this->query_db('query_staff', ['username' => $username, 'fsf_org_id' => $this->fsf_org_id]);
408
409 if (count($staff_data) === 0) {
410 // No rows returned - invalid username
411 Logger::debug('fsfdrupalauth:'.$this->authId.
412 ': No rows in result set. Probably not FSF staff.');
413 }
414
415 $attributes['is_fsf_staff'] = ['false'];
416
417 foreach ($staff_data as $row) {
418 foreach ($row as $key => $value) {
419
420 if ($value === null) {
421 continue;
422 }
423 $value = (string) $value;
424
425 if ($value === $username) {
426 // they are staff
427 $attributes[$key] = ['true'];
428 break;
429 }
430 }
431 }
432
433 //
434 // aggregate attribute
435 //
436
437 $groups_list = '';
438 $first = true;
439 foreach ($attributes as $key => $value) {
440 if ($value == ['true']) {
441 if (!$first) {
442 $groups_list .= ', ';
443 }
444 $groups_list .= $key;
445 $first = false;
446 }
447 }
448
449 $attributes['groups_list'] = [$groups_list];
450 }
451
452 /**
453 * Attempt to log in using the given username and password.
454 *
455 * On a successful login, this function should return the users attributes. On failure,
456 * it should throw an exception. If the error was caused by the user entering the wrong
457 * username or password, a Error\Error('WRONGUSERPASS') should be thrown.
458 *
459 * Note that both the username and the password are UTF-8 encoded.
460 *
461 * @param string $username The username the user wrote.
462 * @param string $password The password the user wrote.
463 * @return array Associative array with the users attributes.
464 */
465 protected function login($username, $password)
466 {
467 assert(is_string($username));
468 assert(is_string($password));
469
470 //// keep this commented when it's not in use. it prints user passwords to the log file
471 //Logger::debug('fsfdrupalauth:'.$this->authId.': entered password: '.$password);
472
473
474 $user_data = $this->query_db('query_main', ['username' => $username]);
475
476
477 if (count($user_data) === 0) {
478 // No rows returned - invalid username
479 Logger::error('fsfdrupalauth:'.$this->authId.
480 ': No rows in result set. Probably wrong username.');
481 throw new Error\Error('WRONGUSERPASS');
482 }
483
484 /* Extract attributes. We allow the resultset to consist of multiple rows. Attributes
485 * which are present in more than one row will become multivalued. null values and
486 * duplicate values will be skipped. All values will be converted to strings.
487 */
488 $attributes = [];
489
490 // use the entered user name so we don't forcibly change it to all
491 // lower case. this is to preserve the behavior of the old cas server,
492 // and to remain compatible with our MW and Discourse sites that are
493 // case sensitive.
494 $attributes['name'][] = $username;
495
496 foreach ($user_data as $row) {
497 foreach ($row as $key => $value) {
498 if ($value === null) {
499 continue;
500 }
501
502 $value = (string) $value;
503
504 if (!array_key_exists($key, $attributes)) {
505 $attributes[$key] = [];
506 }
507
508 if (in_array($value, $attributes[$key], true)) {
509 // Value already exists in attribute
510 continue;
511 }
512
513 $attributes[$key][] = $value;
514 }
515 }
516
517 if (!$this->check_password($password, $attributes['pass'][0])) {
518 throw new Error\Error('WRONGUSERPASS');
519 }
520
521 unset($attributes['pass']);
522
523
524 $this->add_more_attributes($attributes, $username);
525
526
527 Logger::info('fsfdrupalauth:'.$this->authId.': Attributes: '.
528 implode(',', array_keys($attributes)));
529
530 return $attributes;
531 }
532 }