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