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;
47 private $query_nomination_process_donations;
48 private $query_nomination_process_gift_receipt;
49 private $query_nomination_process_adhoc;
52 * SQL query parameters, or variables that help determine which attributes
56 private $gift_redeem_page_id;
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;
66 * Constructor for this authentication source.
68 * @param array $info Information about this authentication source.
69 * @param array $config Configuration.
71 public function __construct($info, $config)
73 assert(is_array($info));
74 assert(is_array($config));
76 // Call the parent constructor first, as required by the interface
77 parent
::__construct($info, $config);
79 // Make sure that all required parameters are present.
88 'query_nomination_process_donations',
89 'query_nomination_process_gift_receipt',
90 'query_nomination_process_adhoc',
93 'gift_redeem_page_id',
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']
103 if (!array_key_exists($param, $config)) {
104 throw new Exception('Missing required attribute \''.$param.
105 '\' for authentication source '.$this->authId
);
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));
115 $this->$param = $config[$param];
118 if (isset($config['options'])) {
119 $this->options
= $config['options'];
125 * Create a database connection.
127 * @return PDO The database connection.
129 private function connect()
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
);
137 throw new Exception('fsfdrupalauth:' . $this->authId
. ': - Failed to connect to \'' .
138 $obfuscated_dsn . '\': ' . $e->getMessage());
141 $db->setAttribute(PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_EXCEPTION
);
143 $driver = explode(':', $this->dsn
, 2);
144 $driver = strtolower($driver[0]);
146 // Driver specific initialization
150 $db->exec("SET NAMES 'utf8mb4'");
154 $db->exec("SET NAMES 'UTF8'");
162 * Check the password against a Drupal hash
165 private function check_password($password, $hash) {
168 // The reason for running a separate process is so that the PHP global
169 // env doesn't get clobbered by include / require.
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
180 $cwd = "../modules/fsfdrupalauth/extlib";
181 //$env = array('some_option' => 'aeiou');
184 $process = proc_open('php drupal-pw-check.php', $descriptorspec, $pipes, $cwd, $env);
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
191 fwrite($pipes[0], json_encode([$password, $hash]));
194 $result = stream_get_contents($pipes[1]);
197 $errors = stream_get_contents($pipes[2]);
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);
204 //Logger::debug('fsfdrupalauth:'.$this->authId.': authenticator stdout: '.$result);
206 $errors_found_yet = false;
208 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator stderr: '.$errors);
209 $errors_found_yet = true;
212 if ($return_value != 0) {
213 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator non-zero return code: '.$return_value);
214 $errors_found_yet = true;
217 return (!$errors_found_yet && is_string($result) && rtrim($result) == "true");
221 Logger
::error('fsfdrupalauth:'.$this->authId
.': unable to launch authenticator');
229 * query the database with arbitrary queries that only require a user name.
232 private function query_db($queryname, $query_params)
234 assert(is_string($queryname));
235 assert(is_string($username));
237 $db = $this->connect();
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());
247 $sth->execute($query_params);
248 } catch (PDOException
$e) {
249 throw new Exception('fsfdrupalauth:'.$this->authId
.
250 ': - Failed to execute queryname: '.$queryname.': '.$e->getMessage());
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());
260 Logger
::info('fsfdrupalauth:'.$this->authId
.': Got '.count($data).
261 ' rows from database');
267 * add more CAS attributes to user, such as is_staff and is_member
269 private function add_more_attributes(&$attributes, $username) {
272 // query on membership
275 $membership_data = $this->query_db('query_membership', ['username' => $username]);
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.');
283 $attributes['is_member'] = ['false'];
284 $attributes['was_member'] = ['false'];
286 foreach ($membership_data as $row) {
287 foreach ($row as $key => $value) {
288 if ($value === null) {
291 $value = (string) $value;
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'];
303 // query for access to board nomination process
306 $start_date = $this->nomination_process_contrib_start_date
;
307 $end_date = $this->nomination_process_contrib_end_date
;
310 * @param string $query_name Name of query in authsources
311 * @param array $extra_params Associative array of parameters to include in query
313 $donation_query = function ($query_name, $extra_params)
316 $parameters = ['username' => $username];
318 foreach ($extra_params as $key => $value) {
319 $parameters[$key] = $value;
322 return $this->query_db($query_name, $parameters);
325 $compare_res = function ($result, $amount) {
326 foreach ($result[0] as $key => $value) {
327 if (intval($value) >= $amount) {
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
340 $analyze_history = function ($selective_donations_history)
341 use ($start_date, $end_date) {
345 $start_date_obj = new \
DateTime($start_date);
346 $end_date_obj = new \
DateTime($end_date);
348 foreach ($selective_donations_history as $row) {
350 $amount = intval($row['amount']);
351 $member_type_id = $row['member_type_id'];
352 $receive_date_obj = new \
DateTime($row['receive_date']);
357 } elseif ($receive_date_obj >= $start_date_obj and $receive_date_obj <= $end_date_obj) {
360 } elseif ($receive_date_obj < $start_date_obj) {
361 switch ($member_type_id) {
364 $rate = intval($this->student_membership_monthly_rate
);
370 $rate = intval($this->membership_monthly_rate
);
373 $membership_end_date_obj = new \
DateTime($row['receive_date']);
374 $membership_end_date_obj->add(new \
DateInterval("P" . ceil($amount / $rate) . "M"));
376 if ($membership_end_date_obj >= $start_date_obj) {
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
)];
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)))) {
393 $attributes['nomination_process'] = ['true'];
395 Logger
::debug('fsfdrupalauth:'.$this->authId
.
396 ': Not a member / comparable donor during window for board process.');
397 $attributes['nomination_process'] = ['false'];
400 $attributes['nomination_process'] = ['false'];
407 $staff_data = $this->query_db('query_staff', ['username' => $username, 'fsf_org_id' => $this->fsf_org_id
]);
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.');
415 $attributes['is_fsf_staff'] = ['false'];
417 foreach ($staff_data as $row) {
418 foreach ($row as $key => $value) {
420 if ($value === null) {
423 $value = (string) $value;
425 if ($value === $username) {
427 $attributes[$key] = ['true'];
434 // aggregate attribute
439 foreach ($attributes as $key => $value) {
440 if ($value == ['true']) {
442 $groups_list .= ', ';
444 $groups_list .= $key;
449 $attributes['groups_list'] = [$groups_list];
453 * Attempt to log in using the given username and password.
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.
459 * Note that both the username and the password are UTF-8 encoded.
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.
465 protected function login($username, $password)
467 assert(is_string($username));
468 assert(is_string($password));
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);
474 $user_data = $this->query_db('query_main', ['username' => $username]);
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');
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.
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
494 $attributes['name'][] = $username;
496 foreach ($user_data as $row) {
497 foreach ($row as $key => $value) {
498 if ($value === null) {
502 $value = (string) $value;
504 if (!array_key_exists($key, $attributes)) {
505 $attributes[$key] = [];
508 if (in_array($value, $attributes[$key], true)) {
509 // Value already exists in attribute
513 $attributes[$key][] = $value;
517 if (!$this->check_password($password, $attributes['pass'][0])) {
518 throw new Error\
Error('WRONGUSERPASS');
521 unset($attributes['pass']);
524 $this->add_more_attributes($attributes, $username);
527 Logger
::info('fsfdrupalauth:'.$this->authId
.': Attributes: '.
528 implode(',', array_keys($attributes)));