3 namespace SimpleSAML\Module\fsfdrupalauth\Auth\Source
;
12 * Extension of simple SQL authentication source
14 * @package SimpleSAMLphp
17 class FSFDrupalAuth
extends \SimpleSAML\Module\core\Auth\UserPassBase
20 * The DSN we should connect to.
25 * The username we should connect to the database with.
30 * The password we should connect to the database with.
35 * The options that we should connect to the database with.
40 * The query we should use to retrieve the attributes for the user.
42 * The username and password will be available as :username and :password.
45 private $query_membership;
48 private $query_nomination_process_donations;
49 private $query_nomination_process_gift_receipt;
50 private $query_nomination_process_adhoc;
52 private $query_discussion_process_donations;
53 private $query_discussion_process_gift_receipt;
54 private $query_discussion_process_adhoc;
57 * SQL query parameters, or variables that help determine which attributes
61 private $gift_redeem_page_id;
63 private $nomination_process_active;
64 private $nomination_process_contrib_start_date;
65 private $nomination_process_contrib_end_date;
66 private $nomination_process_adhoc_access_group_id;
67 private $membership_monthly_rate;
68 private $student_membership_monthly_rate;
70 private $discussion_process_active;
71 private $discussion_process_contrib_start_date;
72 private $discussion_process_contrib_end_date;
73 private $discussion_process_adhoc_access_group_id;
74 private $discussion_process_adhoc_no_access_group_id;
77 * Constructor for this authentication source.
79 * @param array $info Information about this authentication source.
80 * @param array $config Configuration.
82 public function __construct($info, $config)
84 assert(is_array($info));
85 assert(is_array($config));
87 // Call the parent constructor first, as required by the interface
88 parent
::__construct($info, $config);
90 // Make sure that all required parameters are present.
99 'query_nomination_process_donations',
100 'query_nomination_process_gift_receipt',
101 'query_nomination_process_adhoc',
104 'gift_redeem_page_id',
106 'nomination_process_active',
107 'nomination_process_contrib_start_date',
108 'nomination_process_contrib_end_date',
109 'nomination_process_adhoc_access_group_id',
110 'membership_monthly_rate',
111 'student_membership_monthly_rate',
113 'query_discussion_process_donations',
114 'query_discussion_process_gift_receipt',
115 'query_discussion_process_adhoc',
117 'discussion_process_active',
118 'discussion_process_contrib_start_date',
119 'discussion_process_contrib_end_date',
120 'discussion_process_adhoc_access_group_id',
121 'discussion_process_adhoc_no_access_group_id',]
124 if (!array_key_exists($param, $config)) {
125 throw new Exception('Missing required attribute \''.$param.
126 '\' for authentication source '.$this->authId
);
129 if (!is_string($config[$param])) {
130 throw new Exception('Expected parameter \''.$param.
131 '\' for authentication source '.$this->authId
.
132 ' to be a string. Instead it was: '.
133 var_export($config[$param], true));
136 $this->$param = $config[$param];
139 if (isset($config['options'])) {
140 $this->options
= $config['options'];
146 * Create a database connection.
148 * @return PDO The database connection.
150 private function connect()
153 $db = new PDO($this->dsn
, $this->username
, $this->password
, $this->options
);
154 } catch (PDOException
$e) {
155 // Obfuscate the password if it's part of the dsn
156 $obfuscated_dsn = preg_replace('/(user|password)=(.*?([;]|$))/', '${1}=***', $this->dsn
);
158 throw new Exception('fsfdrupalauth:' . $this->authId
. ': - Failed to connect to \'' .
159 $obfuscated_dsn . '\': ' . $e->getMessage());
162 $db->setAttribute(PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_EXCEPTION
);
164 $driver = explode(':', $this->dsn
, 2);
165 $driver = strtolower($driver[0]);
167 // Driver specific initialization
171 $db->exec("SET NAMES 'utf8mb4'");
175 $db->exec("SET NAMES 'UTF8'");
183 * Check the password against a Drupal hash
186 private function check_password($password, $hash) {
189 // The reason for running a separate process is so that the PHP global
190 // env doesn't get clobbered by include / require.
193 // pipes code based off of https://www.php.net/manual/en/function.proc-open.php
194 // CC-BY 3.0 or later
195 $descriptorspec = array(
196 0 => array("pipe", "r"), // stdin is a pipe that the child may read from
197 1 => array("pipe", "w"), // stdout is a pipe that the child may write to
198 2 => array("pipe", "w") // stderr is a pipe that the child may write to
201 $cwd = "../modules/fsfdrupalauth/extlib";
202 //$env = array('some_option' => 'aeiou');
205 $process = proc_open('php drupal-pw-check.php', $descriptorspec, $pipes, $cwd, $env);
207 if (is_resource($process)) {
208 // $pipes now looks like this:
209 // 0 => writeable handle connected to child stdin
210 // 1 => readable handle connected to child stdout
212 fwrite($pipes[0], json_encode([$password, $hash]));
215 $result = stream_get_contents($pipes[1]);
218 $errors = stream_get_contents($pipes[2]);
221 // It is important that you close any pipes before calling
222 // proc_close in order to avoid a deadlock
223 $return_value = proc_close($process);
225 //Logger::debug('fsfdrupalauth:'.$this->authId.': authenticator stdout: '.$result);
227 $errors_found_yet = false;
229 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator stderr: '.$errors);
230 $errors_found_yet = true;
233 if ($return_value != 0) {
234 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator non-zero return code: '.$return_value);
235 $errors_found_yet = true;
238 return (!$errors_found_yet && is_string($result) && rtrim($result) == "true");
242 Logger
::error('fsfdrupalauth:'.$this->authId
.': unable to launch authenticator');
250 * query the database with arbitrary queries that only require a user name.
253 private function query_db($queryname, $query_params)
255 assert(is_string($queryname));
256 assert(is_string($username));
258 $db = $this->connect();
261 $sth = $db->prepare($this->$queryname);
262 } catch (PDOException
$e) {
263 throw new Exception('fsfdrupalauth:'.$this->authId
.
264 ': - Failed to prepare queryname: '.$queryname.': '.$e->getMessage());
268 $sth->execute($query_params);
269 } catch (PDOException
$e) {
270 throw new Exception('fsfdrupalauth:'.$this->authId
.
271 ': - Failed to execute queryname: '.$queryname.': '.$e->getMessage());
275 $data = $sth->fetchAll(PDO
::FETCH_ASSOC
);
276 } catch (PDOException
$e) {
277 throw new Exception('fsfdrupalauth:'.$this->authId
.
278 ': - Failed to fetch result set: '.$e->getMessage());
281 Logger
::info('fsfdrupalauth:'.$this->authId
.': Got '.count($data).
282 ' rows from database');
288 * add more CAS attributes to user, such as is_staff and is_member
290 private function add_more_attributes(&$attributes, $username) {
293 // query on membership
296 $membership_data = $this->query_db('query_membership', ['username' => $username]);
298 if (count($membership_data) === 0) {
299 // No rows returned - invalid username
300 Logger
::debug('fsfdrupalauth:'.$this->authId
.
301 ': No rows in result set. Probably no membership.');
304 $attributes['is_member'] = ['false'];
305 $attributes['was_member'] = ['false'];
307 foreach ($membership_data as $row) {
308 foreach ($row as $key => $value) {
309 if ($value === null) {
312 $value = (string) $value;
314 if ($value === '1' ||
$value === '2' ||
$value === '3') {
315 $attributes['is_member'] = ['true'];
316 $attributes['was_member'] = ['true'];
317 } elseif ($value === '4') {
318 $attributes['was_member'] = ['true'];
324 // helper functions for access to board nomination / discussion process
328 * @param string $query_name Name of query in authsources
329 * @param array $extra_params Associative array of parameters to include in query
331 $donation_query = function ($query_name, $extra_params)
334 $parameters = ['username' => $username];
336 foreach ($extra_params as $key => $value) {
337 $parameters[$key] = $value;
340 return $this->query_db($query_name, $parameters);
343 $compare_res = function ($result, $amount) {
344 foreach ($result[0] as $key => $value) {
345 if (intval($value) >= $amount) {
352 // looks for memberships / comparable donations in time window. also
353 // looks for a membership or donation (included as a param) that
354 // occurred up to a year before, and that would have carried over into
355 // the time window with a single donation. this approximates whether
356 // the person was, or would have been, a member during the configured
358 $nomination_process_analyze_history = function ($selective_donations_history)
359 use ($start_date, $end_date) {
363 $start_date_obj = new \
DateTime($start_date);
364 $end_date_obj = new \
DateTime($end_date);
366 foreach ($selective_donations_history as $row) {
368 $amount = intval($row['amount']);
369 $member_type_id = $row['member_type_id'];
370 $receive_date_obj = new \
DateTime($row['receive_date']);
375 } elseif ($receive_date_obj >= $start_date_obj and $receive_date_obj <= $end_date_obj) {
378 } elseif ($receive_date_obj < $start_date_obj) {
379 switch ($member_type_id) {
382 $rate = intval($this->student_membership_monthly_rate
);
388 $rate = intval($this->membership_monthly_rate
);
391 $membership_end_date_obj = new \
DateTime($row['receive_date']);
392 $membership_end_date_obj->add(new \
DateInterval("P" . ceil($amount / $rate) . "M"));
394 if ($membership_end_date_obj >= $start_date_obj) {
402 $discussion_process_analyze_history = function ($selective_donations_history)
403 use ($start_date, $end_date) {
408 $start_date_obj = new \
DateTime($start_date);
409 $end_date_obj = new \
DateTime($end_date);
411 foreach ($selective_donations_history as $row) {
413 $amount = intval($row['amount']);
414 $member_type_id = $row['member_type_id'];
415 $receive_date_obj = new \
DateTime($row['receive_date']);
417 if (($receive_date_obj > $start_date_obj) && ($receive_date < $end_date_obj)) {
430 // nomination form participation specific checks
433 $start_date = $this->nomination_process_contrib_start_date
;
434 $end_date = $this->nomination_process_contrib_end_date
;
436 $donation_params = ['start_date' => $start_date, 'end_date' => $end_date];
437 $gift_member_params = ['start_date' => $start_date, 'end_date' => $end_date, 'gift_redeem_page_id' => intval($this->gift_redeem_page_id
)];
438 $adhoc_params = ['adhoc_access_group_id' => intval($this->nomination_process_adhoc_access_group_id
)];
440 if ($this->nomination_process_active
== 'true' ) {
441 if ($compare_res($donation_query('query_nomination_process_adhoc', $adhoc_params), 1)) {
442 $attributes['nomination_process'] = ['true'];
444 } elseif ($attributes['is_member'] == ['true']
445 && ($nomination_process_analyze_history($donation_query('query_nomination_process_donations', $donation_params))
446 ||
$compare_res($donation_query('query_nomination_process_gift_receipt', $gift_member_params), 1))) {
448 $attributes['nomination_process'] = ['true'];
450 Logger
::debug('fsfdrupalauth:'.$this->authId
.
451 ': Not a member / comparable donor during window for board process.');
452 $attributes['nomination_process'] = ['false'];
455 $attributes['nomination_process'] = ['false'];
459 // discussion form participation specific checks
462 $start_date = $this->discussion_process_contrib_start_date
;
463 $end_date = $this->discussion_process_contrib_end_date
;
465 $donation_params = ['start_date' => $start_date, 'end_date' => $end_date];
466 $gift_member_params = ['start_date' => $start_date, 'end_date' => $end_date, 'gift_redeem_page_id' => intval($this->gift_redeem_page_id
)];
467 $adhoc_params = ['adhoc_access_group_id' => intval($this->discussion_process_adhoc_access_group_id
)];
468 $adhoc_params_no = ['adhoc_access_group_id' => intval($this->discussion_process_adhoc_no_access_group_id
)];
470 if ($this->discussion_process_active
== 'true' ) {
471 if ($compare_res($donation_query('query_discussion_process_adhoc', $adhoc_params_no), 1)) {
472 Logger
::debug('fsfdrupalauth:'.$this->authId
.
473 ': Nominee not eligible for board nominee discussion process.');
474 $attributes['discussion_process'] = ['false'];
476 } elseif ($compare_res($donation_query('query_discussion_process_adhoc', $adhoc_params), 1)) {
477 $attributes['discussion_process'] = ['true'];
479 } elseif ($attributes['is_member'] == ['true']
480 && ($discussion_process_analyze_history($donation_query('query_discussion_process_donations', $donation_params))
481 ||
$compare_res($donation_query('query_discussion_process_gift_receipt', $gift_member_params), 1))) {
483 $attributes['discussion_process'] = ['true'];
486 Logger
::debug('fsfdrupalauth:'.$this->authId
.
487 ': Not eligible for board nominee discussion process.');
488 $attributes['discussion_process'] = ['false'];
491 $attributes['discussion_process'] = ['false'];
498 $staff_data = $this->query_db('query_staff', ['username' => $username, 'fsf_org_id' => $this->fsf_org_id
]);
500 if (count($staff_data) === 0) {
501 // No rows returned - invalid username
502 Logger
::debug('fsfdrupalauth:'.$this->authId
.
503 ': No rows in result set. Probably not FSF staff.');
506 $attributes['is_fsf_staff'] = ['false'];
508 foreach ($staff_data as $row) {
509 foreach ($row as $key => $value) {
511 if ($value === null) {
514 $value = (string) $value;
516 if (strtolower($value) === strtolower($username)) {
518 $attributes['is_fsf_staff'] = ['true'];
525 // aggregate attribute
530 foreach ($attributes as $key => $value) {
531 if ($value == ['true']) {
533 $groups_list .= ', ';
535 $groups_list .= $key;
540 $attributes['groups_list'] = [$groups_list];
544 * Attempt to log in using the given username and password.
546 * On a successful login, this function should return the users attributes. On failure,
547 * it should throw an exception. If the error was caused by the user entering the wrong
548 * username or password, a Error\Error('WRONGUSERPASS') should be thrown.
550 * Note that both the username and the password are UTF-8 encoded.
552 * @param string $username The username the user wrote.
553 * @param string $password The password the user wrote.
554 * @return array Associative array with the users attributes.
556 protected function login($username, $password)
558 assert(is_string($username));
559 assert(is_string($password));
561 //// keep this commented when it's not in use. it prints user passwords to the log file
562 //Logger::debug('fsfdrupalauth:'.$this->authId.': entered password: '.$password);
565 $user_data = $this->query_db('query_main', ['username' => $username]);
568 if (count($user_data) === 0) {
569 // No rows returned - invalid username
570 Logger
::error('fsfdrupalauth:'.$this->authId
.
571 ': No rows in result set. Probably wrong username.');
572 throw new Error\
Error('WRONGUSERPASS');
575 /* Extract attributes. We allow the resultset to consist of multiple rows. Attributes
576 * which are present in more than one row will become multivalued. null values and
577 * duplicate values will be skipped. All values will be converted to strings.
581 // use the entered user name so we don't forcibly change it to all
582 // lower case. this is to preserve the behavior of the old cas server,
583 // and to remain compatible with our MW and Discourse sites that are
585 $attributes['name'][] = $username;
587 foreach ($user_data as $row) {
588 foreach ($row as $key => $value) {
589 if ($value === null) {
593 $value = (string) $value;
595 if (!array_key_exists($key, $attributes)) {
596 $attributes[$key] = [];
599 if (in_array($value, $attributes[$key], true)) {
600 // Value already exists in attribute
604 $attributes[$key][] = $value;
608 if (!$this->check_password($password, $attributes['pass'][0])) {
609 throw new Error\
Error('WRONGUSERPASS');
612 unset($attributes['pass']);
615 $this->add_more_attributes($attributes, $username);
618 Logger
::info('fsfdrupalauth:'.$this->authId
.': Attributes: '.
619 implode(',', array_keys($attributes)));