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;
51 * SQL query parameters, or variables that help determine which attributes
55 private $nomination_process_contrib_start_date;
56 private $nomination_process_contrib_end_date;
57 private $gift_redeem_page_id;
58 private $donation_threshold;
59 private $membership_donation_threshold;
62 * Constructor for this authentication source.
64 * @param array $info Information about this authentication source.
65 * @param array $config Configuration.
67 public function __construct($info, $config)
69 assert(is_array($info));
70 assert(is_array($config));
72 // Call the parent constructor first, as required by the interface
73 parent
::__construct($info, $config);
75 // Make sure that all required parameters are present.
76 foreach (['dsn', 'username', 'password', 'query_main',
77 'query_membership', 'query_staff',
78 'query_nomination_process_donations',
79 'query_nomination_process_gift_receipt', 'gift_redeem_page_id',
80 'fsf_org_id', 'donation_threshold',
81 'membership_donation_threshold',
82 'nomination_process_contrib_start_date',
83 'nomination_process_contrib_end_date'] as $param) {
85 if (!array_key_exists($param, $config)) {
86 throw new Exception('Missing required attribute \''.$param.
87 '\' for authentication source '.$this->authId
);
90 if (!is_string($config[$param])) {
91 throw new Exception('Expected parameter \''.$param.
92 '\' for authentication source '.$this->authId
.
93 ' to be a string. Instead it was: '.
94 var_export($config[$param], true));
97 $this->$param = $config[$param];
100 if (isset($config['options'])) {
101 $this->options
= $config['options'];
107 * Create a database connection.
109 * @return PDO The database connection.
111 private function connect()
114 $db = new PDO($this->dsn
, $this->username
, $this->password
, $this->options
);
115 } catch (PDOException
$e) {
116 // Obfuscate the password if it's part of the dsn
117 $obfuscated_dsn = preg_replace('/(user|password)=(.*?([;]|$))/', '${1}=***', $this->dsn
);
119 throw new Exception('fsfdrupalauth:' . $this->authId
. ': - Failed to connect to \'' .
120 $obfuscated_dsn . '\': ' . $e->getMessage());
123 $db->setAttribute(PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_EXCEPTION
);
125 $driver = explode(':', $this->dsn
, 2);
126 $driver = strtolower($driver[0]);
128 // Driver specific initialization
132 $db->exec("SET NAMES 'utf8mb4'");
136 $db->exec("SET NAMES 'UTF8'");
144 * Check the password against a Drupal hash
147 private function check_password($password, $hash) {
150 // The reason for running a separate process is so that the PHP global
151 // env doesn't get clobbered by include / require.
154 // pipes code based off of https://www.php.net/manual/en/function.proc-open.php
155 // CC-BY 3.0 or later
156 $descriptorspec = array(
157 0 => array("pipe", "r"), // stdin is a pipe that the child may read from
158 1 => array("pipe", "w"), // stdout is a pipe that the child may write to
159 2 => array("pipe", "w") // stderr is a pipe that the child may write to
162 $cwd = "../modules/fsfdrupalauth/extlib";
163 //$env = array('some_option' => 'aeiou');
166 $process = proc_open('php drupal-pw-check.php', $descriptorspec, $pipes, $cwd, $env);
168 if (is_resource($process)) {
169 // $pipes now looks like this:
170 // 0 => writeable handle connected to child stdin
171 // 1 => readable handle connected to child stdout
173 fwrite($pipes[0], json_encode([$password, $hash]));
176 $result = stream_get_contents($pipes[1]);
179 $errors = stream_get_contents($pipes[2]);
182 // It is important that you close any pipes before calling
183 // proc_close in order to avoid a deadlock
184 $return_value = proc_close($process);
186 //Logger::debug('fsfdrupalauth:'.$this->authId.': authenticator stdout: '.$result);
188 $errors_found_yet = false;
190 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator stderr: '.$errors);
191 $errors_found_yet = true;
194 if ($return_value != 0) {
195 Logger
::error('fsfdrupalauth:'.$this->authId
.': authenticator non-zero return code: '.$return_value);
196 $errors_found_yet = true;
199 return (!$errors_found_yet && is_string($result) && rtrim($result) == "true");
203 Logger
::error('fsfdrupalauth:'.$this->authId
.': unable to launch authenticator');
211 * query the database with arbitrary queries that only require a user name.
214 private function query_db($queryname, $query_params)
216 assert(is_string($queryname));
217 assert(is_string($username));
219 $db = $this->connect();
222 $sth = $db->prepare($this->$queryname);
223 } catch (PDOException
$e) {
224 throw new Exception('fsfdrupalauth:'.$this->authId
.
225 ': - Failed to prepare queryname: '.$queryname.': '.$e->getMessage());
229 $sth->execute($query_params);
230 } catch (PDOException
$e) {
231 throw new Exception('fsfdrupalauth:'.$this->authId
.
232 ': - Failed to execute queryname: '.$queryname.': '.$e->getMessage());
236 $data = $sth->fetchAll(PDO
::FETCH_ASSOC
);
237 } catch (PDOException
$e) {
238 throw new Exception('fsfdrupalauth:'.$this->authId
.
239 ': - Failed to fetch result set: '.$e->getMessage());
242 Logger
::info('fsfdrupalauth:'.$this->authId
.': Got '.count($data).
243 ' rows from database');
249 * add more CAS attributes to user, such as is_staff and is_member
251 private function add_more_attributes(&$attributes, $username) {
254 // query on membership
257 $membership_data = $this->query_db('query_membership', ['username' => $username]);
259 if (count($membership_data) === 0) {
260 // No rows returned - invalid username
261 Logger
::debug('fsfdrupalauth:'.$this->authId
.
262 ': No rows in result set. Probably no membership.');
265 $attributes['is_member'] = ['false'];
266 $attributes['was_member'] = ['false'];
268 foreach ($membership_data as $row) {
269 foreach ($row as $key => $value) {
270 if ($value === null) {
273 $value = (string) $value;
275 if ($value === '1' ||
$value === '2' ||
$value === '3') {
276 $attributes['is_member'] = ['true'];
277 $attributes['was_member'] = ['true'];
278 } elseif ($value === '4') {
279 $attributes['was_member'] = ['true'];
285 // query for access to board nomination process
288 $start_date = $this->nomination_process_contrib_start_date
;
289 $end_date = $this->nomination_process_contrib_end_date
;
292 * @param string $query_name Name of query in authsources
293 * @param number $amount Amount to compare result to
294 * @param boolean $all_contribs Pass as 'all_contribs' param. The var may also be null to exclude it
295 * @param boolean $gift_redeem_page_id Pass as 'gift_redeem_page_id' param. The var may also be null to exclude it
297 $meets_a_donation_criterion = function ($query_name, $amount, $all_contribs, $gift_redeem_page_id)
298 use ($username, $start_date, $end_date, $attributes) {
301 ['username' => $username,
302 'start_date' => $start_date,
303 'end_date' => $end_date];
305 if ($all_contribs !== null) {
306 $parameters['all_contribs'] = $all_contribs;
308 if ($gift_redeem_page_id !== null) {
309 $parameters['gift_redeem_page_id'] = $gift_redeem_page_id;
312 $result = $this->query_db($query_name, $parameters);
314 foreach ($result[0] as $key => $value) {
315 if ($value < $amount) {
317 } elseif ($attributes['is_member'] == ['true']) {
325 if ($meets_a_donation_criterion('query_nomination_process_donations', intval($this->donation_threshold
), true, null)
326 ||
$meets_a_donation_criterion('query_nomination_process_donations', intval($this->membership_donation_threshold
), false, null)
327 ||
$meets_a_donation_criterion('query_nomination_process_gift_receipt', 1, null, intval($this->gift_redeem_page_id
))) {
329 $attributes['nomination_process'] = ['true'];
331 $attributes['nomination_process'] = ['false'];
338 $staff_data = $this->query_db('query_staff', ['username' => $username, 'fsf_org_id' => $this->fsf_org_id
]);
340 if (count($staff_data) === 0) {
341 // No rows returned - invalid username
342 Logger
::debug('fsfdrupalauth:'.$this->authId
.
343 ': No rows in result set. Probably not FSF staff.');
346 $attributes['is_fsf_staff'] = ['false'];
348 foreach ($staff_data as $row) {
349 foreach ($row as $key => $value) {
351 if ($value === null) {
354 $value = (string) $value;
356 if ($value === $username) {
358 $attributes[$key] = ['true'];
365 // aggregate attribute
370 foreach ($attributes as $key => $value) {
371 if ($value == ['true']) {
373 $groups_list .= ', ';
375 $groups_list .= $key;
380 $attributes['groups_list'] = [$groups_list];
384 * Attempt to log in using the given username and password.
386 * On a successful login, this function should return the users attributes. On failure,
387 * it should throw an exception. If the error was caused by the user entering the wrong
388 * username or password, a Error\Error('WRONGUSERPASS') should be thrown.
390 * Note that both the username and the password are UTF-8 encoded.
392 * @param string $username The username the user wrote.
393 * @param string $password The password the user wrote.
394 * @return array Associative array with the users attributes.
396 protected function login($username, $password)
398 assert(is_string($username));
399 assert(is_string($password));
401 //// keep this commented when it's not in use. it prints user passwords to the log file
402 //Logger::debug('fsfdrupalauth:'.$this->authId.': entered password: '.$password);
405 $user_data = $this->query_db('query_main', ['username' => $username]);
408 if (count($user_data) === 0) {
409 // No rows returned - invalid username
410 Logger
::error('fsfdrupalauth:'.$this->authId
.
411 ': No rows in result set. Probably wrong username.');
412 throw new Error\
Error('WRONGUSERPASS');
415 /* Extract attributes. We allow the resultset to consist of multiple rows. Attributes
416 * which are present in more than one row will become multivalued. null values and
417 * duplicate values will be skipped. All values will be converted to strings.
421 // use the entered user name so we don't forcibly change it to all
422 // lower case. this is to preserve the behavior of the old cas server,
423 // and to remain compatible with our MW and Discourse sites that are
425 $attributes['name'][] = $username;
427 foreach ($user_data as $row) {
428 foreach ($row as $key => $value) {
429 if ($value === null) {
433 $value = (string) $value;
435 if (!array_key_exists($key, $attributes)) {
436 $attributes[$key] = [];
439 if (in_array($value, $attributes[$key], true)) {
440 // Value already exists in attribute
444 $attributes[$key][] = $value;
448 if (!$this->check_password($password, $attributes['pass'][0])) {
449 throw new Error\
Error('WRONGUSERPASS');
452 unset($attributes['pass']);
455 $this->add_more_attributes($attributes, $username);
458 Logger
::info('fsfdrupalauth:'.$this->authId
.': Attributes: '.
459 implode(',', array_keys($attributes)));