Commit | Line | Data |
---|---|---|
d46a42f1 RK |
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 | // | |
74b24877 | 10 | // function __construct($settings) |
ac442755 | 11 | // CONSTRUCTOR |
558e9862 | 12 | // Settings are an associative array with a numeric pwd_cost field and an array pwd_nonces field. |
74b24877 RK |
13 | // |
14 | // public $settings | |
15 | // Ab array of settings for the auth server website. | |
558e9862 RK |
16 | // |
17 | // public $db | |
18 | // A PDO database object for interaction. | |
be1082a6 | 19 | // |
77f0f9ff RK |
20 | // public $running_on_localhost |
21 | // A boolean telling if the system is running on localhost (where https is not required). | |
22 | // | |
ea0452ad RK |
23 | // public $client_reg_email_whitelist |
24 | // An array of emails that are whitelisted for registering clients. | |
25 | // | |
ac442755 RK |
26 | // private $pwd_cost |
27 | // The cost parameter for use with PHP password_hash function. | |
28 | // | |
29 | // private $pwd_nonces | |
30 | // The array of nonces to use for "peppering" passwords. For new hashes, the last one of those will be used. | |
087085d6 | 31 | // Generate a nonce with this command: |openssl rand -base64 48| |
ac442755 | 32 | // |
558e9862 RK |
33 | // function log($code, $additional_info) |
34 | // Log an entry for admin purposes, with a code and some additional info. | |
35 | // | |
77f0f9ff RK |
36 | // function checkForSecureConnection() |
37 | // Check is the connection is secure and return an array of error messages (empty if it's secure). | |
38 | // | |
2b9aa8f3 RK |
39 | // function sendSecurityHeaders() |
40 | // Rend HTTP headers for improving security. | |
41 | // | |
4c6d8064 RK |
42 | // function initSession() |
43 | // Initialize a session. Returns an associative array of all the DB fields of the session. | |
44 | // | |
60e46184 RK |
45 | // function getLoginSession($user) |
46 | // 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). | |
47 | // | |
48 | // function setRedirect($session, $redirect) | |
49 | // Set a redirect on the session for performing later. Returns true if a redirect was saved, otherwise false. | |
50 | // | |
51 | // function doRedirectIfSet($session) | |
52 | // If the session has a redirect set, perform it. Returns true if a redirect was performed, otherwise false. | |
53 | // | |
54 | // function resetRedirect($session) | |
55 | // If the session has a redirect set, remove it. Returns true if a redirect was removed, otherwise false. | |
56 | // | |
409b55f4 RK |
57 | // function getDomainBaseURL() |
58 | // Get the base URL of the current domain, e.g. 'https://example.com'. | |
59 | // | |
ac442755 | 60 | // function checkPasswordConstraints($new_password, $user_email) |
d46a42f1 RK |
61 | // Check password constraints and return an array of error messages (empty if all constraints are met). |
62 | // | |
ac442755 | 63 | // function createSessionKey() |
d46a42f1 RK |
64 | // Return a random session key. |
65 | // | |
ac442755 | 66 | // function createVerificationCode() |
d46a42f1 RK |
67 | // Return a random acount/email verification code. |
68 | // | |
ea0452ad RK |
69 | // function createClientSecret() |
70 | // Return a random client secret. | |
71 | // | |
ac442755 | 72 | // function createTimeCode($session, [$offset], [$validity_minutes]) |
d46a42f1 RK |
73 | // Return a time-based code based on the key and ID of the given session. |
74 | // An offset can be given to create a specific code for verification, otherwise and offset will be generated. | |
75 | // Also, an amount of minutes for the code to stay valid can be handed over, by default 10 minutes will be used. | |
76 | // | |
ac442755 | 77 | // function verifyTimeCode($timecode_to_verify, $session, [$validity_minutes]) |
d46a42f1 RK |
78 | // Verify a given time-based code and return true if it's valid or false if it's not. |
79 | // See createTimeCode() documentation for the session and validity paramerters. | |
be1082a6 | 80 | // |
ac442755 | 81 | // function pwdHash($new_password) |
be1082a6 RK |
82 | // Return a hash for the given password. |
83 | // | |
ac442755 | 84 | // function pwdVerify($password_to_verify, $user) |
be1082a6 RK |
85 | // Return true if the password verifies against the pwdhash field of the user, false if not. |
86 | // | |
ac442755 | 87 | // function pwdNeedsRehash($user) |
be1082a6 | 88 | // Return true if the pwdhash field of the user uses an outdated standard and needs to be rehashed. |
409b55f4 | 89 | // |
74b24877 RK |
90 | // function setUpL10n() |
91 | // Set up the localization stack (gettext). | |
92 | // | |
8b69f29c RK |
93 | // function negotiateLocale($supportedLanguages) |
94 | // Return the language to use out of the given array of supported locales, via netotiation based on the HTTP Accept-Language header. | |
95 | // | |
60e46184 RK |
96 | // function getGroupedEmails($group_id, [$exclude_email]) |
97 | // Return all emails grouped in the specified group ID, optionally exclude a specific email (e.g. because you only want non-current entries) | |
98 | // | |
74b24877 RK |
99 | // function getOAuthServer() |
100 | // Return an OAuth2 server object to use for all our actual OAuth2 interaction. | |
101 | // | |
7be13777 RK |
102 | // function initHTMLDocument($titletext, [$headlinetext]) { |
103 | // initialize the HTML document for the auth system, with some elements we always use, esp. all the scripts and stylesheet. | |
104 | // Sets the title of the document to the given title, the main headline will be the same as the title if not set explicitly. | |
105 | // Returns an associative array with the following elements: 'document', 'html', 'head', 'title', 'body'. | |
106 | // | |
60e46184 RK |
107 | // function appendLoginForm($dom_element, $session, $user, [$addfields]) |
108 | // Append a login form for the given session to the given DOM element, possibly prefilling the email from the given user info array. | |
109 | // The optional $addfields parameter is an array of name=>value pairs of hidden fields to add to the form. | |
be1082a6 | 110 | |
74b24877 | 111 | function __construct($settings) { |
ac442755 | 112 | // *** constructor *** |
74b24877 RK |
113 | $this->settings = $settings; |
114 | $this->db = new PDO($this->settings['dbdata']['dsn'], $this->settings['dbdata']['username'], $this->settings['dbdata']['password']); | |
4c6d8064 | 115 | $this->db->exec("SET time_zone='+00:00';"); // Execute directly on PDO object, set session to UTC to make our gmdate() values match correctly. |
a5d730af | 116 | // For debugging, potentially add |robert\.box\.kairo\.at to that regex temporarily. |
77f0f9ff | 117 | $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']); |
ac442755 | 118 | if (array_key_exists('pwd_cost', $settings)) { |
74b24877 | 119 | $this->pwd_cost = $this->settings['pwd_cost']; |
ac442755 | 120 | } |
558e9862 | 121 | if (array_key_exists('pwd_nonces', $settings)) { |
74b24877 | 122 | $this->pwd_nonces = $this->settings['pwd_nonces']; |
558e9862 | 123 | } |
ac442755 RK |
124 | } |
125 | ||
74b24877 | 126 | public $settings = null; |
558e9862 | 127 | public $db = null; |
77f0f9ff | 128 | public $running_on_localhost = false; |
ea0452ad | 129 | public $client_reg_email_whitelist = array('kairo@kairo.at', 'com@kairo.at'); |
ac442755 RK |
130 | private $pwd_cost = 10; |
131 | private $pwd_nonces = array(); | |
d46a42f1 | 132 | |
558e9862 RK |
133 | function log($code, $info) { |
134 | $result = $this->db->prepare('INSERT INTO `auth_log` (`code`, `info`, `ip_addr`) VALUES (:code, :info, :ipaddr);'); | |
135 | if (!$result->execute(array(':code' => $code, ':info' => $info, ':ipaddr' => $_SERVER['REMOTE_ADDR']))) { | |
136 | // print($result->errorInfo()[2]); | |
137 | } | |
138 | } | |
139 | ||
77f0f9ff RK |
140 | function checkForSecureConnection() { |
141 | $errors = array(); | |
142 | if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) { | |
143 | $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.'); | |
144 | } | |
145 | return $errors; | |
146 | } | |
147 | ||
b0e48c35 RK |
148 | function sendSecurityHeaders() { |
149 | // Send various headers that we want to have for security resons, mostly as recommended by https://observatory.mozilla.org/ | |
150 | ||
151 | // CSP - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy | |
152 | // Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) from ourselves; also disable framing. | |
153 | header('Content-Security-Policy: default-src \'none\';img-src \'self\'; script-src \'self\'; style-src \'self\'; frame-ancestors \'none\''); | |
154 | ||
155 | // X-Content-Type-Options - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Content-Type-Options | |
156 | // Prevent browsers from incorrectly detecting non-scripts as scripts | |
157 | header('X-Content-Type-Options: nosniff'); | |
158 | ||
159 | // X-Frame-Options (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-Frame-Options | |
160 | // Block site from being framed | |
161 | header('X-Frame-Options: DENY'); | |
162 | ||
163 | // X-XSS-Protection (for older browsers) - see https://wiki.mozilla.org/Security/Guidelines/Web_Security#X-XSS-Protection | |
164 | // Block pages from loading when they detect reflected XSS attacks | |
165 | header('X-XSS-Protection: 1; mode=block'); | |
166 | } | |
167 | ||
4c6d8064 RK |
168 | function initSession() { |
169 | $session = null; | |
170 | if (strlen(@$_COOKIE['sessionkey'])) { | |
171 | // Fetch the session - or at least try to. | |
172 | $result = $this->db->prepare('SELECT * FROM `auth_sessions` WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); | |
173 | $result->execute(array(':sesskey' => $_COOKIE['sessionkey'], ':expire' => gmdate('Y-m-d H:i:s'))); | |
174 | $row = $result->fetch(PDO::FETCH_ASSOC); | |
175 | if ($row) { | |
176 | $session = $row; | |
177 | } | |
178 | } | |
179 | if (is_null($session)) { | |
180 | // Create new session and set cookie. | |
181 | $sesskey = $this->createSessionKey(); | |
182 | setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. | |
183 | $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);'); | |
184 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes')))); | |
185 | // After insert, actually fetch the session row from the DB so we have all values. | |
186 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); | |
187 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); | |
188 | $row = $result->fetch(PDO::FETCH_ASSOC); | |
189 | if ($row) { | |
190 | $session = $row; | |
191 | } | |
192 | else { | |
193 | $this->log('session_create_failure', 'key: '.$sesskey); | |
194 | } | |
195 | } | |
196 | return $session; | |
197 | } | |
198 | ||
60e46184 RK |
199 | function getLoginSession($userid, $prev_session) { |
200 | $session = $prev_session; | |
201 | $sesskey = $this->createSessionKey(); | |
202 | setcookie('sessionkey', $sesskey, 0, "", "", !$this->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. | |
203 | // If the previous session has a user set, create a new one - otherwise take existing session entry. | |
204 | if (intval($session['user'])) { | |
205 | $result = $this->db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);'); | |
206 | $result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')))); | |
207 | // After insert, actually fetch the session row from the DB so we have all values. | |
208 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); | |
209 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); | |
210 | $row = $result->fetch(PDO::FETCH_ASSOC); | |
211 | if ($row) { | |
212 | $session = $row; | |
213 | } | |
214 | else { | |
215 | $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$userid); | |
9cab985c | 216 | $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.'); |
60e46184 RK |
217 | } |
218 | } | |
219 | else { | |
220 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;'); | |
221 | if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $userid, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) { | |
222 | $utils->log('login_failure', 'session: '.$session['id'].', user: '.$userid); | |
9cab985c | 223 | $errors[] = _('Login failed unexpectedly.').' '._('Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.'); |
60e46184 RK |
224 | } |
225 | else { | |
226 | // After update, actually fetch the session row from the DB so we have all values. | |
227 | $result = $this->db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;'); | |
228 | $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s'))); | |
229 | $row = $result->fetch(PDO::FETCH_ASSOC); | |
230 | if ($row) { | |
231 | $session = $row; | |
232 | } | |
233 | } | |
234 | } | |
235 | return $session; | |
236 | } | |
237 | ||
238 | function setRedirect($session, $redirect) { | |
239 | $success = false; | |
240 | // Save the request in the session so we can get back to fulfilling it if one of the links is clicked. | |
241 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); | |
242 | if (!$result->execute(array(':redir' => $redirect, ':sessid' => $session['id']))) { | |
243 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: '.$redirect); | |
244 | } | |
245 | else { | |
246 | $success = true; | |
247 | } | |
248 | return $success; | |
249 | } | |
250 | ||
251 | function doRedirectIfSet($session) { | |
252 | $success = false; | |
253 | // If the session has a redirect set, make sure it's performed. | |
254 | if (strlen(@$session['saved_redirect'])) { | |
255 | // Remove redirect. | |
256 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); | |
257 | if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) { | |
258 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)'); | |
259 | } | |
260 | else { | |
261 | $success = true; | |
262 | } | |
263 | header('Location: '.$this->getDomainBaseURL().$session['saved_redirect']); | |
264 | } | |
265 | return $success; | |
266 | } | |
267 | ||
268 | function resetRedirect($session) { | |
269 | $success = false; | |
270 | // If the session has a redirect set, remove it. | |
271 | if (strlen(@$session['saved_redirect'])) { | |
272 | $result = $this->db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;'); | |
273 | if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) { | |
274 | $this->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)'); | |
275 | } | |
276 | else { | |
277 | $success = true; | |
278 | } | |
279 | } | |
280 | return $success; | |
281 | } | |
282 | ||
409b55f4 RK |
283 | function getDomainBaseURL() { |
284 | return ($this->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME']; | |
285 | } | |
286 | ||
ac442755 | 287 | function checkPasswordConstraints($new_password, $user_email) { |
d46a42f1 RK |
288 | $errors = array(); |
289 | if ($new_password != trim($new_password)) { | |
290 | $errors[] = _('Password must not start or end with a whitespace character like a space.'); | |
291 | } | |
292 | if (strlen($new_password) < 8) { $errors[] = sprintf(_('Password too short (min. %s characters).'), 8); } | |
293 | if (strlen($new_password) > 70) { $errors[] = sprintf(_('Password too long (max. %s characters).'), 70); } | |
294 | if ((strtolower($new_password) == strtolower($user_email)) || | |
295 | in_array(strtolower($new_password), preg_split("/[@\.]+/", strtolower($user_email)))) { | |
296 | $errors[] = _('The passwort can not be equal to your email or any part of it.'); | |
297 | } | |
298 | if ((strlen($new_password) < 15) && (preg_match('/^[a-zA-Z]+$/', $new_password))) { | |
299 | $errors[] = sprintf(_('Your password must use characters other than normal letters or contain least %s characters.'), 15); | |
300 | } | |
301 | if (preg_match('/^\d+$/', $new_password)) { | |
302 | $errors[] = sprintf(_('Your password cannot consist only of numbers.'), 15); | |
303 | } | |
304 | if (strlen(count_chars($new_password, 3)) < 5) { | |
305 | $errors[] = sprintf(_('Password does have to contain at least %s different characters.'), 5); | |
306 | } | |
307 | return $errors; | |
308 | } | |
309 | ||
ac442755 | 310 | function createSessionKey() { |
d46a42f1 RK |
311 | return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string). |
312 | } | |
313 | ||
ac442755 | 314 | function createVerificationCode() { |
d46a42f1 RK |
315 | return bin2hex(openssl_random_pseudo_bytes(512 / 8)); // Get 512 bits of randomness (128 byte hex string). |
316 | } | |
317 | ||
ea0452ad RK |
318 | function createClientSecret() { |
319 | return bin2hex(openssl_random_pseudo_bytes(160 / 8)); // Get 160 bits of randomness (40 byte hex string). | |
320 | } | |
321 | ||
ac442755 | 322 | function createTimeCode($session, $offset = null, $validity_minutes = 10) { |
d46a42f1 RK |
323 | // Matches TOTP algorithms, see https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm |
324 | $valid_seconds = intval($validity_minutes) * 60; | |
325 | if ($valid_seconds < 60) { $valid_seconds = 60; } | |
326 | $code_digits = 8; | |
327 | $time = time(); | |
328 | $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. | |
329 | $counter = floor(($time - $rest) / $valid_seconds); | |
330 | $hmac = mhash(MHASH_SHA1, $counter, $session['id'].$session['sesskey']); | |
331 | $offset = hexdec(substr(bin2hex(substr($hmac, -1)), -1)); // Get the last 4 bits as a number. | |
332 | $totp = hexdec(bin2hex(substr($hmac, $offset, 4))) & 0x7FFFFFFF; // Take 4 bytes at the offset, discard highest bit. | |
333 | $totp_value = sprintf('%0'.$code_digits.'d', substr($totp, -$code_digits)); | |
334 | return $rest.'.'.$totp_value; | |
335 | } | |
336 | ||
ac442755 | 337 | function verifyTimeCode($timecode_to_verify, $session, $validity_minutes = 10) { |
d46a42f1 | 338 | if (preg_match('/^(\d+)\.\d+$/', $timecode_to_verify, $regs)) { |
ac442755 | 339 | return ($timecode_to_verify === $this->createTimeCode($session, $regs[1], $validity_minutes)); |
d46a42f1 RK |
340 | } |
341 | return false; | |
342 | } | |
be1082a6 | 343 | |
ac442755 RK |
344 | function pwdHash($new_password) { |
345 | $hash_prefix = ''; | |
346 | if (count($this->pwd_nonces)) { | |
347 | $new_password .= $this->pwd_nonces[count($this->pwd_nonces) - 1]; | |
348 | $hash_prefix = (count($this->pwd_nonces) - 1).'|'; | |
349 | } | |
350 | return $hash_prefix.password_hash($new_password, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost)); | |
be1082a6 RK |
351 | } |
352 | ||
ac442755 | 353 | function pwdVerify($password_to_verify, $userdata) { |
087085d6 RK |
354 | $pwdhash = $userdata['pwdhash']; |
355 | if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) { | |
ac442755 | 356 | $password_to_verify .= $this->pwd_nonces[$regs[1]]; |
087085d6 | 357 | $pwdhash = $regs[2]; |
ac442755 | 358 | } |
087085d6 | 359 | return password_verify($password_to_verify, $pwdhash); |
be1082a6 RK |
360 | } |
361 | ||
ac442755 RK |
362 | function pwdNeedsRehash($userdata) { |
363 | $nonceid = -1; | |
364 | $pwdhash = $userdata['pwdhash']; | |
365 | if (preg_match('/^(\d+)\|(.+)$/', $userdata['pwdhash'], $regs)) { | |
366 | $nonceid = $regs[1]; | |
367 | $pwdhash = $regs[2]; | |
368 | } | |
369 | if ($nonceid == count($this->pwd_nonces) - 1) { | |
370 | return password_needs_rehash($pwdhash, PASSWORD_DEFAULT, array('cost' => $this->pwd_cost)); | |
371 | } | |
372 | else { | |
373 | return true; | |
374 | } | |
be1082a6 | 375 | } |
409b55f4 | 376 | |
74b24877 RK |
377 | function setUpL10n() { |
378 | // This is an array of locale tags in browser style mapping to unix system locale codes to use with gettext. | |
379 | $supported_locales = array( | |
380 | 'en-US' => 'en_US', | |
381 | 'de' => 'de_DE', | |
382 | ); | |
383 | ||
384 | $textdomain = 'kairo_auth'; | |
385 | $textlocale = $this->negotiateLocale(array_keys($supported_locales)); | |
386 | putenv('LC_ALL='.$supported_locales[$textlocale]); | |
387 | $selectedlocale = setlocale(LC_ALL, $supported_locales[$textlocale]); | |
388 | bindtextdomain($textdomain, '../locale'); | |
389 | bind_textdomain_codeset($textdomain, 'utf-8'); | |
390 | textdomain($textdomain); | |
391 | } | |
392 | ||
8b69f29c RK |
393 | function negotiateLocale($supportedLanguages) { |
394 | $nlocale = $supportedLanguages[0]; | |
395 | $headers = getAllHeaders(); | |
9cab985c | 396 | $accLcomp = explode(',', @$headers['Accept-Language']); |
8b69f29c RK |
397 | $accLang = array(); |
398 | foreach ($accLcomp as $lcomp) { | |
399 | if (strlen($lcomp)) { | |
400 | $ldef = explode(';', $lcomp); | |
401 | $accLang[$ldef[0]] = (float)((strpos(@$ldef[1],'q=')===0)?substr($ldef[1],2):1); | |
402 | } | |
403 | } | |
404 | if (count($accLang)) { | |
405 | $pLang = ''; $pLang_q = 0; | |
406 | foreach ($supportedLanguages as $wantedLang) { | |
407 | if (isset($accLang[$wantedLang]) && ($accLang[$wantedLang] > $pLang_q)) { | |
408 | $pLang = $wantedLang; | |
409 | $pLang_q = $accLang[$wantedLang]; | |
410 | } | |
411 | } | |
412 | if (strlen($pLang)) { $nlocale = $pLang; } | |
413 | } | |
414 | return $nlocale; | |
415 | } | |
416 | ||
60e46184 RK |
417 | function getGroupedEmails($group_id, $exclude_email = '') { |
418 | $emails = array(); | |
419 | if (intval($group_id)) { | |
420 | $result = $this->db->prepare('SELECT `email` FROM `auth_users` WHERE `group_id` = :groupid AND `status` = \'ok\' AND `email` != :excludemail ORDER BY `email` ASC;'); | |
421 | $result->execute(array(':groupid' => $group_id, ':excludemail' => $exclude_email)); | |
422 | foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) { | |
423 | $emails[] = $row['email']; | |
424 | } | |
425 | } | |
426 | return $emails; | |
427 | } | |
428 | ||
74b24877 RK |
429 | function getOAuthServer() { |
430 | // Simple server based on https://bshaffer.github.io/oauth2-server-php-docs/cookbook | |
431 | ||
432 | // dbata needs to be set and be an associative array with the members 'dsn', 'username', and 'password'. | |
433 | // dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost" | |
434 | $oauth2_storage = new OAuth2\Storage\Pdo($this->settings['dbdata']); | |
435 | ||
436 | // Set configuration | |
437 | $oauth2_config = array( | |
438 | 'require_exact_redirect_uri' => false, | |
439 | 'always_issue_new_refresh_token' => true, // Needs to be handed below as well as there it's not constructed from within the server object. | |
440 | 'refresh_token_lifetime' => 90*24*3600, | |
441 | ); | |
442 | ||
443 | // Pass a storage object or array of storage objects to the OAuth2 server class | |
444 | $server = new OAuth2\Server($oauth2_storage, $oauth2_config); | |
445 | ||
446 | // Add the "Client Credentials" grant type (it is the simplest of the grant types) | |
447 | //$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage)); | |
448 | ||
449 | // Add the "Authorization Code" grant type (this is where the oauth magic happens) | |
450 | $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($oauth2_storage)); | |
451 | ||
452 | // Add the "Refresh Token" grant type (required to get longer-living resource access by generating new access tokens) | |
453 | $server->addGrantType(new OAuth2\GrantType\RefreshToken($oauth2_storage, array('always_issue_new_refresh_token' => true))); | |
454 | ||
455 | return $server; | |
456 | } | |
457 | ||
7be13777 RK |
458 | function initHTMLDocument($titletext, $headlinetext = null) { |
459 | global $settings; | |
460 | if (is_null($headlinetext)) { $headlinetext = $titletext; } | |
461 | // Start HTML document as a DOM object. | |
462 | extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body | |
463 | $document->formatOutput = true; // we want a nice output | |
464 | ||
465 | $style = $head->appendElement('link'); | |
466 | $style->setAttribute('rel', 'stylesheet'); | |
467 | $style->setAttribute('href', 'authsystem.css'); | |
468 | $head->appendJSFile('authsystem.js'); | |
469 | if ($settings['piwik_enabled']) { | |
470 | $head->setAttribute('data-piwiksite', $settings['piwik_site_id']); | |
471 | $head->setAttribute('data-piwikurl', $settings['piwik_url']); | |
472 | $head->appendJSFile('piwik.js', true, true); | |
473 | } | |
474 | $title->appendText($titletext); | |
475 | $h1 = $body->appendElement('h1', $headlinetext); | |
476 | ||
477 | if ($settings['piwik_enabled']) { | |
478 | // Piwik noscript element | |
479 | $noscript = $body->appendElement('noscript'); | |
480 | $para = $noscript->appendElement('p'); | |
481 | $img = $para->appendImage($settings['piwik_url'].'piwik.php?idsite='.$settings['piwik_site_id']); | |
482 | $img->setAttribute('style', 'border:0;'); | |
483 | } | |
484 | ||
485 | // Make the document not be scaled on mobile devices. | |
486 | $vpmeta = $head->appendElement('meta'); | |
487 | $vpmeta->setAttribute('name', 'viewport'); | |
488 | $vpmeta->setAttribute('content', 'width=device-width, height=device-height'); | |
489 | ||
490 | $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.')); | |
491 | $para->setAttribute('id', 'jswarning'); | |
492 | $para->setAttribute('class', 'warn'); | |
493 | ||
494 | return array('document' => $document, | |
495 | 'html' => $html, | |
496 | 'head' => $head, | |
497 | 'title' => $title, | |
498 | 'body' => $body); | |
499 | } | |
500 | ||
60e46184 | 501 | function appendLoginForm($dom_element, $session, $user, $addfields = array()) { |
409b55f4 RK |
502 | $form = $dom_element->appendForm('./', 'POST', 'loginform'); |
503 | $form->setAttribute('id', 'loginform'); | |
504 | $form->setAttribute('class', 'loginarea hidden'); | |
505 | $ulist = $form->appendElement('ul'); | |
506 | $ulist->setAttribute('class', 'flat login'); | |
507 | $litem = $ulist->appendElement('li'); | |
508 | $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', (intval(@$user['id'])?$user['email']:'')); | |
509 | $inptxt->setAttribute('autocomplete', 'email'); | |
510 | $inptxt->setAttribute('required', ''); | |
511 | $inptxt->setAttribute('placeholder', _('Email')); | |
512 | $inptxt->setAttribute('class', 'login'); | |
513 | $litem = $ulist->appendElement('li'); | |
514 | $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', ''); | |
515 | $inptxt->setAttribute('required', ''); | |
516 | $inptxt->setAttribute('placeholder', _('Password')); | |
517 | $inptxt->setAttribute('class', 'login'); | |
518 | $litem = $ulist->appendElement('li'); | |
519 | $litem->appendLink('./?reset', _('Forgot password?')); | |
a98340a5 | 520 | /* |
409b55f4 RK |
521 | $litem = $ulist->appendElement('li'); |
522 | $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false); | |
523 | $cbox->setAttribute('class', 'logincheck'); | |
524 | $label = $litem->appendLabel('login_remember', _('Remember me')); | |
525 | $label->setAttribute('id', 'rememprompt'); | |
526 | $label->setAttribute('class', 'loginprompt'); | |
a98340a5 | 527 | */ |
409b55f4 RK |
528 | $litem = $ulist->appendElement('li'); |
529 | $litem->appendInputHidden('tcode', $this->createTimeCode($session)); | |
60e46184 RK |
530 | foreach ($addfields as $fname => $fvalue) { |
531 | $litem->appendInputHidden($fname, $fvalue); | |
532 | } | |
409b55f4 RK |
533 | $submit = $litem->appendInputSubmit(_('Log in / Register')); |
534 | $submit->setAttribute('class', 'loginbutton'); | |
535 | } | |
d46a42f1 RK |
536 | } |
537 | ?> |