81ae2a7fdc9fb47df2b16d53e3d93bc75997d064
[authserver.git] / app / authutils.php-class
1 <?php
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 class AuthUtils {
7   // KaiRo.at authentication utilities PHP class
8   // This class contains helper functions for the authentication system.
9   //
10   // function __construct()
11   //   CONSTRUCTOR
12   //
13   // public $settings
14   //   An array of settings for the auth server website.
15   //
16   // public $db
17   //   A PDO database object for interaction.
18   //
19   // public $running_on_localhost
20   //   A boolean telling if the system is running on localhost (where https is not required).
21   //
22   // public $client_reg_email_whitelist
23   //   An array of emails that are whitelisted for registering clients.
24   //
25   // private $pwd_cost
26   //   The cost parameter for use with PHP password_hash function.
27   //
28   // private $pwd_nonces
29   //   The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used.
30   //     Generate a nonce with this command: |openssl rand -base64 48|
31   //
32   // function log($code, $additional_info)
33   //   Log an entry for admin purposes, with a code and some additional info.
34   //
35   // function checkForSecureConnection()
36   //   Check is the connection is secure and return an array of error messages (empty if it's secure).
37   //
38   // function sendSecurityHeaders()
39   //   Rend HTTP headers for improving security.
40   //
41   // function initSession()
42   //   Initialize a session. Returns an associative array of all the DB fields of the session.
43   //
44   // function getLoginSession($user)
45   //   Return an associative array of a session with the given user logged in (new if user changed compared to given previous session, otherwise updated variant of that previous session).
46   //
47   // function setRedirect($session, $redirect)
48   //   Set a redirect on the session for performing later. Returns true if a redirect was saved, otherwise false.
49   //
50   // function doRedirectIfSet($session)
51   //   If the session has a redirect set, perform it. Returns true if a redirect was performed, otherwise false.
52   //
53   // function resetRedirect($session)
54   //   If the session has a redirect set, remove it. Returns true if a redirect was removed, otherwise false.
55   //
56   // function getDomainBaseURL()
57   //   Get the base URL of the current domain, e.g. 'https://example.com'.
58   //
59   // function checkPasswordConstraints($new_password, $user_email)
60   //   Check password constraints and return an array of error messages (empty if all constraints are met).
61   //
62   // function createSessionKey()
63   //   Return a random session key.
64   //
65   // function createVerificationCode()
66   //   Return a random acount/email verification code.
67   //
68   // function createClientSecret()
69   //   Return a random client secret.
70   //
71   // function createTimeCode($session, [$offset], [$validity_minutes])
72   //   Return a time-based code based on the key and ID of the given session.
73   //     An offset can be given to create a specific code for verification, otherwise and offset will be generated.
74   //     Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used.
75   //
76   // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes])
77   //   Verify a given time-based code and return true if it's valid or false if it's not.
78   //     See createTimeCode() documentation for the session and validity paramerters.
79   //
80   // function pwdHash($new_password)
81   //   Return a hash for the given password.
82   //
83   // function pwdVerify($password_to_verify, $user)
84   //   Return true if the password verifies against the pwdhash field of the user, false if not.
85   //
86   // function pwdNeedsRehash($user)
87   //   Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed.
88   //
89   // function setUpL10n()
90   //   Set up the localization stack (gettext).
91   //
92   // function negotiateLocale($supportedLanguages)
93   //   Return the language to use out of the given array of supported locales, via netotiation based on the HTTP Accept-Language header.
94   //
95   // function getGroupedEmails($group_id, [$exclude_email])
96   //   Return all emails grouped in the specified group ID, optionally exclude a specific email (e.g. because you only want non-current entries)
97   //
98   // function getOAuthServer()
99   //   Return an OAuth2 server object to use for all our actual OAuth2 interaction.
100   //
101   // function initHTMLDocument($titletext, [$headlinetext]) {
102   //   initialize the HTML document for the auth system, with some elements we always use, esp. all the scripts and stylesheet.
103   //     Sets the title of the document to the given title, the main headline will be the same as the title if not set explicitly.
104   //     Returns an associative array with the following elements: 'document', 'html', 'head', 'title', 'body'.
105   //
106   // function appendLoginForm($dom_element, $session, $user, [$addfields])
107   //   Append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array.
108   //     The optional $addfields parameter is an array of name=>value pairs of hidden fields to add to the form.
109   //
110   // function updateDBSchema()
111   //   update DB Schema to current requirements as specified by getDBSchema().
112   //
113   // function getDBSchema()
114   //   Return a DB schema with all tables, fields, etc. that the app requires.
115
116   function __construct() {
117     // *** constructor ***
118     $this->settings = json_decode(@file_get_contents('/etc/kairo/auth_settings.json'), true);
119     if (!is_array($this->settings)) { throw new ErrorException('Authentication system settings not found', 0); }
120
121     // Sanitize settings.
122     $this->settings['piwik_enabled'] = $this->settings['piwik_enabled'] ?? false;
123     $this->settings['piwik_site_id'] = intval($this->settings['piwik_site_id'] ?? 0);
124     $this->settings['piwik_url'] = strlen($this->settings['piwik_url'] ?? '') ? $this->settings['piwik_url'] : '/matomo/';
125     $this->settings['piwik_tracker_path'] = strlen($this->settings['piwik_tracker_path'] ?? '') ? $this->settings['piwik_tracker_path'] : '../vendor/matomo/matomo-php-tracker/';
126     $this->settings['skin'] = (($this->settings['skin'] ?? false) && is_dir('skin/'.$this->settings['skin'])) ? $this->settings['skin'] : 'default';
127     $this->settings['operator_name'] = $this->settings['operator_name'] ?? 'Example';
128     $this->settings['operator_contact_url'] = $this->settings['operator_contact_url'] ?? 'https://github.com/KaiRo_at/authserver/';
129     $this->settings['info_from_email'] = $this->settings['info_from_email'] ?? 'noreply@example.com';
130
131     // Initialize database.
132     $config = new \Doctrine\DBAL\Configuration();
133     $connectionParams = array(
134         'dbname' => $this->settings['db_name'],
135         'user' => $this->settings['db_username'],
136         'password' => $this->settings['db_password'],
137         'host' => $this->settings['db_host'],
138         'driver' => 'pdo_mysql',
139     );
140     $this->db = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
141     $this->db->executeQuery('SET time_zone = "+00:00";'); // Make sure the DB runs on UTC for this connection.
142     // Update DB schema if needed (if the utils PHP file has been changed since we last checked the DB, we trigger the update functionality).
143     try {
144       $last_log = $this->db->fetchColumn('SELECT time_logged FROM auth_log WHERE code = \'db_checked\' ORDER BY id DESC LIMIT 1', array(1), 0);
145       $utils_mtime = filemtime(__FILE__);
146     }
147     catch (Exception $e) {
148       $last_log = false;
149     }
150     if (!$last_log || strtotime($last_log) < $utils_mtime) {
151       $this->updateDBSchema();
152     }
153
154     // Set local variables.
155     // For debugging, potentially add |robert\.box\.kairo\.at to that regex temporarily.
156     $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']);
157     if (array_key_exists('pwd_cost', $this->settings)) {
158       $this->pwd_cost = $this->settings['pwd_cost'];
159     }
160     if (array_key_exists('pwd_nonces', $this->settings)) {
161       $this->pwd_nonces = $this->settings['pwd_nonces'];
162     }
163     if (array_key_exists('client_reg_email_whitelist', $this->settings) && is_array($this->settings['client_reg_email_whitelist'])) {
164       // If the config lists any emails, set whitelist to them, otherwise there is no whitelist and any user can add OAuth2 clients.
165       $this->client_reg_email_whitelist = $this->settings['client_reg_email_whitelist'];
166     }
167   }
168
169   public $settings = null;
170   public $db = null;
171   public $running_on_localhost = false;
172   public $client_reg_email_whitelist = false;
173   private $pwd_cost = 10;
174   private $pwd_nonces = array();
175
176   function log($code, $info) {
177     $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);');
178     if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) {
179       // print($result->errorInfo()[2]);
180     }
181   }
182
183   function checkForSecureConnection() {
184     $errors = array();
185     if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) {
186       $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.');
187     }
188     return $errors;
189   }
190
191   function sendSecurityHeaders() {
192     // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/
193
194     // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy
195     // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing.
196     header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\'');
197
198     // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options
199     // Prevent browsers from incorrectly detecting non-scripts as scripts
200     header('X-Content-Type-Options: nosniff');
201
202     // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options
203     // Block site from being framed
204     header('X-Frame-Options: DENY');
205
206     // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection
207     // Block pages from loading when they detect reflected XSS attacks
208     header('X-XSS-Protection: 1; mode=block');
209   }
210
211   function initSession() {
212     $session = null;
213     if (strlen($_COOKIE['sessionkey'] ?? '')) {
214       // Fetch the session - or at least try to.
215       $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
216       $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s')));
217       $row = $result->fetch(PDO::FETCH_ASSOC);
218       if ($row) {
219         $session = $row;
220       }
221     }
222     if (is_null($session)) {
223       // Create new session and set cookie.
224       $sesskey = $this->createSessionKey();
225       setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
226       $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);');
227       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes'))));
228       // After insert, actually fetch the session row from the DB so we have all values.
229       $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
230       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
231       $row = $result->fetch(PDO::FETCH_ASSOC);
232       if ($row) {
233         $session = $row;
234       }
235       else {
236         $this->log('session_create_failure', 'key: '.$sesskey);
237       }
238     }
239     return $session;
240   }
241
242   function getLoginSession($userid, $prev_session) {
243     $session = $prev_session;
244     $sesskey = $this->createSessionKey();
245     setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
246     // If the previous session has a user set, create a new one - otherwise take existing session entry.
247     if (intval($session['user'])) {
248       $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
249       $result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
250       // After insert, actually fetch the session row from the DB so we have all values.
251       $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
252       $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
253       $row = $result->fetch(PDO::FETCH_ASSOC);
254       if ($row) {
255         $session = $row;
256       }
257       else {
258         $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$userid);
259         $errors[] = _('The session system is not working.').' '
260                     .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $this->settings['operator_contact_url'], $this->settings['operator_name']);
261       }
262     }
263     else {
264       $result = $this->db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
265       if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
266         $utils->log('login_failure', 'session: '.$session['id'].', user: '.$userid);
267         $errors[] = _('Login failed unexpectedly.').' '
268                     .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $this->settings['operator_contact_url'], $this->settings['operator_name']);
269       }
270       else {
271         // After update, actually fetch the session row from the DB so we have all values.
272         $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
273         $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
274         $row = $result->fetch(PDO::FETCH_ASSOC);
275         if ($row) {
276           $session = $row;
277         }
278       }
279     }
280     return $session;
281   }
282
283   function setRedirect($session, $redirect) {
284     $success = false;
285     // Save the request in the session so we can get back to fulfilling it if one of the links is clicked.
286     $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
287     if (!$result->execute(array(':redir' => $redirect, ':sessid' => $session['id']))) {
288       $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: '.$redirect);
289     }
290     else {
291       $success = true;
292     }
293     return $success;
294   }
295
296   function doRedirectIfSet($session) {
297     $success = false;
298     // If the session has a redirect set, make sure it's performed.
299     if (strlen($session['saved_redirect'] ?? '')) {
300       // Remove redirect.
301       $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
302       if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
303         $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
304       }
305       else {
306         $success = true;
307       }
308       header('Location: '.$this->getDomainBaseURL().$session['saved_redirect']);
309     }
310     return $success;
311   }
312
313   function resetRedirect($session) {
314     $success = false;
315     // If the session has a redirect set, remove it.
316     if (strlen($session['saved_redirect'] ?? '')) {
317       $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
318       if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
319         $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
320       }
321       else {
322         $success = true;
323       }
324     }
325     return $success;
326   }
327
328   function getDomainBaseURL() {
329     return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'];
330   }
331
332   function checkPasswordConstraints($new_password, $user_email) {
333     $errors = array();
334     if ($new_password != trim($new_password)) {
335       $errors[] = _('Password must not start or end with a whitespace character like a space.');
336     }
337     if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); }
338     if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); }
339     if ((strtolower($new_password) == strtolower($user_email)) ||
340         in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) {
341       $errors[] = _('The passwort can not be equal to your email or any part of it.');
342     }
343     if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) {
344       $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15);
345     }
346     if (preg_match('/^\d+$/', $new_password)) {
347       $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15);
348     }
349     if (strlen(count_chars($new_password, 3)) < 5) {
350       $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5);
351     }
352     return $errors;
353   }
354
355   function createSessionKey() {
356     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
357   }
358
359   function createVerificationCode() {
360     return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string).
361   }
362
363   function createClientSecret() {
364     return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string).
365   }
366
367   function createTimeCode($session, $offset = null, $validity_minutes = 10) {
368     // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
369     $valid_seconds = intval($validity_minutes) * 60;
370     if ($valid_seconds < 60) { $valid_seconds = 60; }
371     $code_digits = 8;
372     $time = time();
373     $rest = is_null($offset)?($time % $valid_seconds):intval($offset); // T0, will be sent as part of code to make it valid for the full duration.
374     $counter = floor(($time - $rest) / $valid_seconds);
375     $hmac_hex = hash_hmac('sha1', $counter, $session['id'].$session['sesskey']);
376     $offset = hexdec(substr($hmac_hex, -1)); // Get the last 4 bits as a number.
377     $totp = hexdec(substr($hmac_hex, $offset, 8)) & 0x7FFFFFFF; // Take 4 bytes (8 hex chars) at the offset, discard highest bit.
378     $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits));
379     return $rest.'.'.$totp_value;
380   }
381
382   function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) {
383     if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) {
384       return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes));
385     }
386     return false;
387   }
388
389   /*
390     Some resources for how to store passwords:
391     - https://blog.mozilla.org/webdev/2012/06/08/lets-talk-about-password-storage/
392     - https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines
393     oauth-server-php: https://bshaffer.github.io/oauth2-server-php-docs/cookbook
394   */
395   function pwdHash($new_password) {
396     $hash_prefix = '';
397     if (count($this->pwd_nonces)) {
398       $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1];
399       $hash_prefix = (count($this->pwd_nonces) - 1).'|';
400     }
401     return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
402   }
403
404   function pwdVerify($password_to_verify, $userdata) {
405     $pwdhash = $userdata['pwdhash'];
406     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
407       $password_to_verify .= $this->pwd_nonces[$regs[1]];
408       $pwdhash = $regs[2];
409     }
410     return password_verify($password_to_verify, $pwdhash);
411   }
412
413   function pwdNeedsRehash($userdata) {
414     $nonceid = -1;
415     $pwdhash = $userdata['pwdhash'];
416     if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) {
417       $nonceid = $regs[1];
418       $pwdhash = $regs[2];
419     }
420     if ($nonceid == count($this->pwd_nonces) - 1) {
421       return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost));
422     }
423     else {
424       return true;
425     }
426   }
427
428   function setUpL10n() {
429     // This is an array of locale tags in browser style mapping to unix system locale codes to use with gettext.
430     $supported_locales = array(
431         'en-US' => 'en_US',
432         'de' => 'de_DE',
433     );
434
435     $textdomain = 'kairo_auth';
436     $textlocale = $this->negotiateLocale(array_keys($supported_locales));
437     putenv('LC_ALL='.$supported_locales[$textlocale]);
438     $selectedlocale = setlocale(LC_ALL, $supported_locales[$textlocale]);
439     bindtextdomain($textdomain, '../locale');
440     bind_textdomain_codeset($textdomain, 'utf-8');
441     textdomain($textdomain);
442   }
443
444   function negotiateLocale($supportedLanguages) {
445     $nlocale = $supportedLanguages[0];
446     $headers = getAllHeaders();
447     $accLcomp = explode(',', ($headers['Accept-Language'] ?? ''));
448     $accLang = array();
449     foreach ($accLcomp as $lcomp) {
450       if (strlen($lcomp)) {
451         $ldef = explode(';', $lcomp);
452         if (count($ldef) > 1 && strpos($ldef[1], 'q=') === 0) {
453           $accLang[$ldef[0]] = substr($ldef[1], 2);
454         }
455         else {
456           $accLang[$ldef[0]] = 1;
457         }
458       }
459     }
460     if (count($accLang)) {
461       $pLang = ''; $pLang_q = 0;
462       foreach ($supportedLanguages as $wantedLang) {
463         if (isset($accLang[$wantedLang]) && ($accLang[$wantedLang] > $pLang_q)) {
464           $pLang = $wantedLang;
465           $pLang_q = $accLang[$wantedLang];
466         }
467       }
468       if (strlen($pLang)) { $nlocale = $pLang; }
469     }
470     return $nlocale;
471   }
472
473   function getGroupedEmails($group_id, $exclude_email = '') {
474     $emails = array();
475     if (intval($group_id)) {
476       $result = $this->db->prepare('SELECT `email` FROM `auth_users` WHERE `group_id` = :groupid AND `status` = \'ok\' AND `email` != :excludemail ORDER BY `email` ASC;');
477       $result->execute(array(':groupid' => $group_id, ':excludemail' => $exclude_email));
478       foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
479         $emails[] = $row['email'];
480       }
481     }
482     return $emails;
483   }
484
485   function getOAuthServer() {
486     // Simple server based on https://bshaffer.github.io/oauth2-server-php-docs/cookbook
487     $dbdata = array('dsn' => 'mysql:dbname='.$this->settings['db_name'].';host='.$this->settings['db_host'],
488                     'username' => $this->settings['db_username'],
489                     'password' => $this->settings['db_password']);
490     $oauth2_storage = new OAuth2\Storage\Pdo($dbdata);
491
492     // Set configuration
493     $oauth2_config = array(
494       'require_exact_redirect_uri' => false,
495       'always_issue_new_refresh_token' => true, // Needs to be handed below as well as there it's not constructed from within the server object.
496       'refresh_token_lifetime' => 90*24*3600,
497     );
498
499     // Pass a storage object or array of storage objects to the OAuth2 server class
500     $server = new OAuth2\Server($oauth2_storage, $oauth2_config);
501
502     // Add the "Client Credentials" grant type (it is the simplest of the grant types)
503     //$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
504
505     // Add the "Authorization Code" grant type (this is where the oauth magic happens)
506     $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($oauth2_storage));
507
508     // Add the "Refresh Token" grant type (required to get longer-living resource access by generating new access tokens)
509     $server->addGrantType(new OAuth2\GrantType\RefreshToken($oauth2_storage, array('always_issue_new_refresh_token' => true)));
510
511     // Add 'token' response type (mirroring what getDefaultResponseTypes is doing).
512     $server->addResponseType(new OAuth2\ResponseType\AccessToken($oauth2_storage, $oauth2_storage, $oauth2_config));
513
514     // Add 'code' response type (mirroring what getDefaultResponseTypes is doing).
515     $server->addResponseType(new OAuth2\ResponseType\AuthorizationCode($oauth2_storage));
516
517     return $server;
518   }
519
520   function initHTMLDocument($titletext, $headlinetext = null) {
521     global $settings;
522     if (is_null($headlinetext)) { $headlinetext = $titletext; }
523     // Start HTML document as a DOM object.
524     extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
525     $document->formatOutput = true; // we want a nice output
526
527     $style = $head->appendElement('link');
528     $style->setAttribute('rel', 'stylesheet');
529     $style->setAttribute('href', 'authsystem.css');
530     $style = $head->appendElement('link');
531     $style->setAttribute('rel', 'stylesheet');
532     $style->setAttribute('href', 'skin/'.$settings['skin'].'/authskin.css');
533     $head->appendJSFile('authsystem.js');
534     if ($settings['piwik_enabled']) {
535       $head->setAttribute('data-piwiksite', $settings['piwik_site_id']);
536       $head->setAttribute('data-piwikurl', $settings['piwik_url']);
537       $head->appendJSFile('piwik.js', true, true);
538     }
539     $icon = $head->appendElement('link');
540     $icon->setAttribute('rel', 'shortcut icon');
541     $icon->setAttribute('href', 'skin/'.$settings['skin'].'/icon32.png');
542     $icon->setAttribute('type', 'image/png');
543     $title->appendText($titletext);
544     $h1 = $body->appendElement('h1', $headlinetext);
545
546     if ($settings['piwik_enabled']) {
547       // Piwik noscript element
548       $noscript = $body->appendElement('noscript');
549       $para = $noscript->appendElement('p');
550       $img = $para->appendImage($settings['piwik_url'].'piwik.php?idsite='.$settings['piwik_site_id']);
551       $img->setAttribute('style', 'border:0;');
552     }
553
554     // Make the document not be scaled on mobile devices.
555     $vpmeta = $head->appendElement('meta');
556     $vpmeta->setAttribute('name', 'viewport');
557     $vpmeta->setAttribute('content', 'width=device-width, height=device-height');
558
559     $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
560     $para->setAttribute('id', 'jswarning');
561     $para->setAttribute('class', 'warn');
562
563     return array('document' => $document,
564                  'html' => $html,
565                  'head' => $head,
566                  'title' => $title,
567                  'body' => $body);
568   }
569
570   function appendLoginForm($dom_element, $session, $user, $addfields = array()) {
571     $form = $dom_element->appendForm('./', 'POST', 'loginform');
572     $form->setAttribute('id', 'loginform');
573     $form->setAttribute('class', 'loginarea hidden');
574     $ulist = $form->appendElement('ul');
575     $ulist->setAttribute('class', 'flat login');
576     $litem = $ulist->appendElement('li');
577     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval($user['id'] ?? 0) ? $user['email'] : ''));
578     $inptxt->setAttribute('autocomplete', 'email');
579     $inptxt->setAttribute('required', '');
580     $inptxt->setAttribute('placeholder', _('Email'));
581     $inptxt->setAttribute('class', 'login');
582     $litem = $ulist->appendElement('li');
583     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
584     $inptxt->setAttribute('required', '');
585     $inptxt->setAttribute('placeholder', _('Password'));
586     $inptxt->setAttribute('class', 'login');
587     $litem = $ulist->appendElement('li');
588     $litem->appendLink('./?reset', _('Forgot password?'));
589     /*
590     $litem = $ulist->appendElement('li');
591     $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false);
592     $cbox->setAttribute('class', 'logincheck');
593     $label = $litem->appendLabel('login_remember', _('Remember me'));
594     $label->setAttribute('id', 'rememprompt');
595     $label->setAttribute('class', 'loginprompt');
596     */
597     $litem = $ulist->appendElement('li');
598     $litem->appendInputHidden('tcode', $this->createTimeCode($session));
599     foreach ($addfields as $fname => $fvalue) {
600       $litem->appendInputHidden($fname, $fvalue);
601     }
602     $submit = $litem->appendInputSubmit(_('Log in / Register'));
603     $submit->setAttribute('class', 'loginbutton');
604   }
605
606   function updateDBSchema() {
607     $newSchema = $this->getDBSchema();
608     $synchronizer = new \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer($this->db);
609     $up_sql = $synchronizer->getUpdateSchema($newSchema); // for logging only
610     $synchronizer->updateSchema($newSchema);
611     $this->log('db_checked', implode("\n", $up_sql));
612   }
613
614   function getDBSchema() {
615     $schema = new \Doctrine\DBAL\Schema\Schema();
616
617     $table = $schema->createTable('auth_sessions');
618     $table->addColumn('id', 'bigint', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true));
619     $table->addColumn('sesskey', 'string', array('length' => 150, 'notnull' => true, 'default' => ''));
620     $table->addColumn('user', 'integer', array('unsigned' => true, 'notnull' => false, 'default' => null));
621     $table->addColumn('logged_in', 'boolean', array('notnull' => true, 'default' => false));
622     $table->addColumn('time_created', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP'));
623     $table->addColumn('time_expire', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP'));
624     $table->addColumn('saved_redirect', 'string', array('length' => 2000, 'notnull' => true, 'default' => ''));
625     $table->setPrimaryKey(array('id'), 'id');
626     $table->addIndex(array('sesskey'), 'sesskey');
627     $table->addIndex(array('time_expire'), 'time_expire');
628
629     $table = $schema->createTable('auth_users');
630     $table->addColumn('id', 'integer', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true));
631     $table->addColumn('email', 'string', array('length' => 255, 'notnull' => true, 'default' => ''));
632     $table->addColumn('pwdhash', 'string', array('length' => 255, 'notnull' => true, 'default' => ''));
633     $table->addColumn('status', 'string', array('length' => 20, 'notnull' => true, 'default' => 'unverified'));
634     $table->addColumn('verify_hash', 'string', array('length' => 150, 'notnull' => false, 'default' => null));
635     $table->addColumn('group_id', 'integer', array('unsigned' => true, 'notnull' => true, 'default' => 0));
636     $table->setPrimaryKey(array('id'), 'id');
637     $table->addUniqueIndex(array('email'), 'email');
638
639     $table = $schema->createTable('auth_log');
640     $table->addColumn('id', 'bigint', array('unsigned' => true, 'notnull' => true, 'autoincrement' => true));
641     $table->addColumn('code', 'string', array('length' => 100, 'notnull' => true, 'default' => ''));
642     $table->addColumn('info', 'text', array('notnull' => false, 'default' => null));
643     $table->addColumn('ip_addr', 'string', array('length' => 50, 'notnull' => false, 'default' => null));
644     $table->addColumn('time_logged', 'datetime', array('notnull' => true, 'default' => 'CURRENT_TIMESTAMP'));
645     $table->setPrimaryKey(array('id'), 'id');
646     $table->addIndex(array('time_logged'), 'time_logged');
647
648     /* Doctrine DBAL variant of http://bshaffer.github.io/oauth2-server-php-docs/cookbook/#define-your-schema */
649     $table = $schema->createTable('oauth_clients');
650     $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true));
651     $table->addColumn('client_secret', 'string', array('length' => 80, 'notnull' => false));
652     $table->addColumn('redirect_uri', 'string', array('length' => 2000, 'notnull' => true));
653     $table->addColumn('grant_types', 'string', array('length' => 80, 'notnull' => false));
654     $table->addColumn('scope', 'string', array('length' => 100, 'notnull' => false));
655     $table->addColumn('user_id', 'string', array('length' => 80, 'notnull' => false));
656     $table->setPrimaryKey(array('client_id'), 'clients_client_id_pk');
657
658     $table = $schema->createTable('oauth_access_tokens');
659     $table->addColumn('access_token', 'string', array('length' => 40, 'notnull' => true));
660     $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true));
661     $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false));
662     $table->addColumn('expires', 'datetime', array('notnull' => true));
663     $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false));
664     $table->setPrimaryKey(array('access_token'), 'access_token_pk');
665
666     $table = $schema->createTable('oauth_authorization_codes');
667     $table->addColumn('authorization_code', 'string', array('length' => 40, 'notnull' => true));
668     $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true));
669     $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false));
670     $table->addColumn('redirect_uri', 'string', array('length' => 2000, 'notnull' => false));
671     $table->addColumn('expires', 'datetime', array('notnull' => true));
672     $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false));
673     $table->setPrimaryKey(array('authorization_code'), 'auth_code_pk');
674
675     $table = $schema->createTable('oauth_refresh_tokens');
676     $table->addColumn('refresh_token', 'string', array('length' => 40, 'notnull' => true));
677     $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true));
678     $table->addColumn('user_id', 'string', array('length' => 255, 'notnull' => false));
679     $table->addColumn('expires', 'datetime', array('notnull' => true));
680     $table->addColumn('scope', 'string', array('length' => 2000, 'notnull' => false));
681     $table->setPrimaryKey(array('refresh_token'), 'refresh_token_pk');
682
683     $table = $schema->createTable('oauth_users');
684     $table->addColumn('username', 'string', array('length' => 255, 'notnull' => true));
685     $table->addColumn('password', 'string', array('length' => 2000, 'notnull' => false));
686     $table->addColumn('first_name', 'string', array('length' => 255, 'notnull' => false));
687     $table->addColumn('last_name', 'string', array('length' => 255, 'notnull' => false));
688     $table->setPrimaryKey(array('username'), 'username_pk');
689
690     $table = $schema->createTable('oauth_scopes');
691     $table->addColumn('scope', 'text', array('notnull' => false));
692     $table->addColumn('is_default', 'boolean', array('notnull' => false));
693
694     $table = $schema->createTable('oauth_jwt');
695     $table->addColumn('client_id', 'string', array('length' => 80, 'notnull' => true));
696     $table->addColumn('subject', 'string', array('length' => 80, 'notnull' => false));
697     $table->addColumn('public_key', 'string', array('length' => 2000, 'notnull' => false));
698     $table->setPrimaryKey(array('client_id'), 'client_id_pk');
699
700     return $schema;
701   }
702 }
703 ?>