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