4 * Authentication library
6 * Including this file will automatically try to login
7 * a user by calling auth_login()
9 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
10 * @author Andreas Gohr <andi@splitbrain.org>
14 use phpseclib\Crypt\AES
;
15 use dokuwiki\Utf8\PhpString
;
16 use dokuwiki\Extension\AuthPlugin
;
17 use dokuwiki\Extension\Event
;
18 use dokuwiki\Extension\PluginController
;
19 use dokuwiki\PassHash
;
20 use dokuwiki\Subscriptions\RegistrationSubscriptionSender
;
23 * Initialize the auth system.
25 * This function is automatically called at the end of init.php
27 * This used to be the main() of the auth.php
29 * @todo backend loading maybe should be handled by the class autoloader
30 * @todo maybe split into multiple functions at the XXX marked positions
31 * @triggers AUTH_LOGIN_CHECK
37 /* @var AuthPlugin $auth */
39 /* @var Input $INPUT */
43 /* @var PluginController $plugin_controller */
44 global $plugin_controller;
47 if (!$conf['useacl']) return false;
49 // try to load auth backend from plugins
50 foreach ($plugin_controller->getList('auth') as $plugin) {
51 if ($conf['authtype'] === $plugin) {
52 $auth = $plugin_controller->load('auth', $plugin);
57 if (!$auth instanceof AuthPlugin
) {
58 msg($lang['authtempfail'], -1);
62 if ($auth->success
== false) {
63 // degrade to unauthenticated user
66 msg($lang['authtempfail'], -1);
70 // do the login either by cookie or provided credentials XXX
71 $INPUT->set('http_credentials', false);
72 if (!$conf['rememberme']) $INPUT->set('r', false);
74 // Populate Basic Auth user/password from Authorization header
75 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
76 $header = $INPUT->server
->str('HTTP_AUTHORIZATION') ?
: $INPUT->server
->str('REDIRECT_HTTP_AUTHORIZATION');
77 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
78 $userpass = explode(':', base64_decode($matches[1]));
79 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
82 // if no credentials were given try to use HTTP auth (for SSO)
83 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE
]) && !empty($INPUT->server
->str('PHP_AUTH_USER'))) {
84 $INPUT->set('u', $INPUT->server
->str('PHP_AUTH_USER'));
85 $INPUT->set('p', $INPUT->server
->str('PHP_AUTH_PW'));
86 $INPUT->set('http_credentials', true);
89 // apply cleaning (auth specific user names, remove control chars)
90 if (true === $auth->success
) {
91 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
92 $INPUT->set('p', stripctl($INPUT->str('p')));
95 if (!auth_tokenlogin()) {
98 if ($auth instanceof AuthPlugin
&& $auth->canDo('external')) {
99 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
103 // external trust mechanism not in place, or returns no result,
104 // then attempt auth_login
106 'user' => $INPUT->str('u'),
107 'password' => $INPUT->str('p'),
108 'sticky' => $INPUT->bool('r'),
109 'silent' => $INPUT->bool('http_credentials')
111 Event
::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
115 //load ACL into a global array XXX
116 $AUTH_ACL = auth_loadACL();
122 * Loads the ACL setup and handle user wildcards
124 * @author Andreas Gohr <andi@splitbrain.org>
128 function auth_loadACL()
130 global $config_cascade;
132 /* @var Input $INPUT */
135 if (!is_readable($config_cascade['acl']['default'])) return [];
137 $acl = file($config_cascade['acl']['default']);
140 foreach ($acl as $line) {
142 if (empty($line) ||
($line[0] == '#')) continue; // skip blank lines & comments
143 [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
145 // substitute user wildcard first (its 1:1)
146 if (strstr($line, '%USER%')) {
147 // if user is not logged in, this ACL line is meaningless - skip it
148 if (!$INPUT->server
->has('REMOTE_USER')) continue;
150 $id = str_replace('%USER%', cleanID($INPUT->server
->str('REMOTE_USER')), $id);
151 $rest = str_replace('%USER%', auth_nameencode($INPUT->server
->str('REMOTE_USER')), $rest);
154 // substitute group wildcard (its 1:m)
155 if (strstr($line, '%GROUP%')) {
156 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
157 if (isset($USERINFO['grps'])) {
158 foreach ((array) $USERINFO['grps'] as $grp) {
159 $nid = str_replace('%GROUP%', cleanID($grp), $id);
160 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
161 $out[] = "$nid\t$nrest";
165 $out[] = "$id\t$rest";
175 * @return bool true if token login succeeded
177 function auth_tokenlogin()
181 /** @var DokuWiki_Auth_Plugin $auth */
183 if (!$auth) return false;
185 // see if header has token
187 if (function_exists('getallheaders')) {
188 // Authorization headers are not in $_SERVER for mod_php
189 $headers = array_change_key_case(getallheaders());
190 if (isset($headers['authorization'])) $header = $headers['authorization'];
192 $header = $INPUT->server
->str('HTTP_AUTHORIZATION');
194 if (!$header) return false;
195 [$type, $token] = sexplode(' ', $header, 2);
196 if ($type !== 'Bearer') return false;
200 $authtoken = JWT
::validate($token);
201 } catch (Exception
$e) {
202 msg(hsc($e->getMessage()), -1);
206 // fetch user info from backend
207 $user = $authtoken->getUser();
208 $USERINFO = $auth->getUserData($user);
209 if (!$USERINFO) return false;
211 // the code is correct, set up user
212 $INPUT->server
->set('REMOTE_USER', $user);
213 $_SESSION[DOKU_COOKIE
]['auth']['user'] = $user;
214 $_SESSION[DOKU_COOKIE
]['auth']['pass'] = 'nope';
215 $_SESSION[DOKU_COOKIE
]['auth']['info'] = $USERINFO;
221 * Event hook callback for AUTH_LOGIN_CHECK
223 * @param array $evdata
227 function auth_login_wrapper($evdata)
238 * This tries to login the user based on the sent auth credentials
240 * The authentication works like this: if a username was given
241 * a new login is assumed and user/password are checked. If they
242 * are correct the password is encrypted with blowfish and stored
243 * together with the username in a cookie - the same info is stored
244 * in the session, too. Additonally a browserID is stored in the
247 * If no username was given the cookie is checked: if the username,
248 * crypted password and browserID match between session and cookie
249 * no further testing is done and the user is accepted
251 * If a cookie was found but no session info was availabe the
252 * blowfish encrypted password from the cookie is decrypted and
253 * together with username rechecked by calling this function again.
255 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
258 * @param string $user Username
259 * @param string $pass Cleartext Password
260 * @param bool $sticky Cookie should not expire
261 * @param bool $silent Don't show error on bad auth
262 * @return bool true on successful auth
265 * @author Andreas Gohr <andi@splitbrain.org>
267 function auth_login($user, $pass, $sticky = false, $silent = false)
272 /* @var AuthPlugin $auth */
274 /* @var Input $INPUT */
277 if (!$auth instanceof AuthPlugin
) return false;
281 if (!empty($pass) && $auth->checkPass($user, $pass)) {
282 // make logininfo globally available
283 $INPUT->server
->set('REMOTE_USER', $user);
284 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
285 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
288 //invalid credentials - log off
290 http_status(403, 'Login failed');
291 msg($lang['badlogin'], -1);
297 // read cookie information
298 [$user, $sticky, $pass] = auth_getCookie();
299 if ($user && $pass) {
300 // we got a cookie - see if we can trust it
303 if (isset($_SESSION[DOKU_COOKIE
])) {
304 $session = $_SESSION[DOKU_COOKIE
]['auth'];
307 $auth->useSessionCache($user) &&
308 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
309 ($session['user'] == $user) &&
310 ($session['pass'] == sha1($pass)) && //still crypted
311 ($session['buid'] == auth_browseruid())
313 // he has session, cookie and browser right - let him in
314 $INPUT->server
->set('REMOTE_USER', $user);
315 $USERINFO = $session['info']; //FIXME move all references to session
319 // no we don't trust it yet - recheck pass but silent
320 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
321 $pass = auth_decrypt($pass, $secret);
322 return auth_login($user, $pass, $sticky, true);
331 * Builds a pseudo UID from browser and IP data
333 * This is neither unique nor unfakable - still it adds some
334 * security. Using the first part of the IP makes sure
335 * proxy farms like AOLs are still okay.
337 * @author Andreas Gohr <andi@splitbrain.org>
339 * @return string a SHA256 sum of various browser headers
341 function auth_browseruid()
343 /* @var Input $INPUT */
346 $ip = clientIP(true);
347 // convert IP string to packed binary representation
348 $pip = inet_pton($ip);
350 $uid = implode("\n", [
351 $INPUT->server
->str('HTTP_USER_AGENT'),
352 $INPUT->server
->str('HTTP_ACCEPT_LANGUAGE'),
353 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
355 return hash('sha256', $uid);
359 * Creates a random key to encrypt the password in cookies
361 * This function tries to read the password for encrypting
362 * cookies from $conf['metadir'].'/_htcookiesalt'
363 * if no such file is found a random key is created and
364 * and stored in this file.
366 * @param bool $addsession if true, the sessionid is added to the salt
367 * @param bool $secure if security is more important than keeping the old value
371 * @author Andreas Gohr <andi@splitbrain.org>
373 function auth_cookiesalt($addsession = false, $secure = false)
375 if (defined('SIMPLE_TEST')) {
379 $file = $conf['metadir'] . '/_htcookiesalt';
380 if ($secure ||
!file_exists($file)) {
381 $file = $conf['metadir'] . '/_htcookiesalt2';
383 $salt = io_readFile($file);
385 $salt = bin2hex(auth_randombytes(64));
386 io_saveFile($file, $salt);
389 $salt .= session_id();
395 * Return cryptographically secure random bytes.
397 * @param int $length number of bytes
398 * @return string cryptographically secure random bytes
401 * @author Niklas Keller <me@kelunik.com>
403 function auth_randombytes($length)
405 return random_bytes($length);
409 * Cryptographically secure random number generator.
416 * @author Niklas Keller <me@kelunik.com>
418 function auth_random($min, $max)
420 return random_int($min, $max);
424 * Encrypt data using the given secret using AES
426 * The mode is CBC with a random initialization vector, the key is derived
429 * @param string $data The data that shall be encrypted
430 * @param string $secret The secret/password that shall be used
431 * @return string The ciphertext
434 function auth_encrypt($data, $secret)
436 $iv = auth_randombytes(16);
438 $cipher->setPassword($secret);
441 this uses the encrypted IV as IV as suggested in
442 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
443 for unique but necessarily random IVs. The resulting ciphertext is
444 compatible to ciphertext that was created using a "normal" IV.
446 return $cipher->encrypt($iv . $data);
450 * Decrypt the given AES ciphertext
452 * The mode is CBC, the key is derived using pbkdf2
454 * @param string $ciphertext The encrypted data
455 * @param string $secret The secret/password that shall be used
456 * @return string The decrypted data
458 function auth_decrypt($ciphertext, $secret)
460 $iv = substr($ciphertext, 0, 16);
462 $cipher->setPassword($secret);
465 return $cipher->decrypt(substr($ciphertext, 16));
469 * Log out the current user
471 * This clears all authentication data and thus log the user
472 * off. It also clears session data.
474 * @author Andreas Gohr <andi@splitbrain.org>
476 * @param bool $keepbc - when true, the breadcrumb data is not cleared
478 function auth_logoff($keepbc = false)
482 /* @var AuthPlugin $auth */
484 /* @var Input $INPUT */
487 // make sure the session is writable (it usually is)
490 if (isset($_SESSION[DOKU_COOKIE
]['auth']['user']))
491 unset($_SESSION[DOKU_COOKIE
]['auth']['user']);
492 if (isset($_SESSION[DOKU_COOKIE
]['auth']['pass']))
493 unset($_SESSION[DOKU_COOKIE
]['auth']['pass']);
494 if (isset($_SESSION[DOKU_COOKIE
]['auth']['info']))
495 unset($_SESSION[DOKU_COOKIE
]['auth']['info']);
496 if (!$keepbc && isset($_SESSION[DOKU_COOKIE
]['bc']))
497 unset($_SESSION[DOKU_COOKIE
]['bc']);
498 $INPUT->server
->remove('REMOTE_USER');
499 $USERINFO = null; //FIXME
501 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL
: $conf['cookiedir'];
502 setcookie(DOKU_COOKIE
, '', [
503 'expires' => time() - 600000,
504 'path' => $cookieDir,
505 'secure' => ($conf['securecookie'] && is_ssl()),
507 'samesite' => $conf['samesitecookie'] ?
: null, // null means browser default
510 if ($auth instanceof AuthPlugin
) {
516 * Check if a user is a manager
518 * Should usually be called without any parameters to check the current
521 * The info is available through $INFO['ismanager'], too
523 * @param string $user Username
524 * @param array $groups List of groups the user is in
525 * @param bool $adminonly when true checks if user is admin
526 * @param bool $recache set to true to refresh the cache
530 * @author Andreas Gohr <andi@splitbrain.org>
532 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
536 /* @var AuthPlugin $auth */
538 /* @var Input $INPUT */
542 if (!$auth instanceof AuthPlugin
) return false;
543 if (is_null($user)) {
544 if (!$INPUT->server
->has('REMOTE_USER')) {
547 $user = $INPUT->server
->str('REMOTE_USER');
550 if (is_null($groups)) {
551 // checking the logged in user, or another one?
552 if ($USERINFO && $user === $INPUT->server
->str('REMOTE_USER')) {
553 $groups = (array) $USERINFO['grps'];
555 $groups = $auth->getUserData($user);
556 $groups = $groups ?
$groups['grps'] : [];
560 // prefer cached result
562 $cachekey = serialize([$user, $adminonly, $groups]);
563 if (!isset($cache[$cachekey]) ||
$recache) {
564 // check superuser match
565 $ok = auth_isMember($conf['superuser'], $user, $groups);
568 if (!$ok && !$adminonly) {
569 $ok = auth_isMember($conf['manager'], $user, $groups);
572 $cache[$cachekey] = $ok;
575 return $cache[$cachekey];
579 * Check if a user is admin
581 * Alias to auth_ismanager with adminonly=true
583 * The info is available through $INFO['isadmin'], too
585 * @param string $user Username
586 * @param array $groups List of groups the user is in
587 * @param bool $recache set to true to refresh the cache
589 * @author Andreas Gohr <andi@splitbrain.org>
590 * @see auth_ismanager()
593 function auth_isadmin($user = null, $groups = null, $recache = false)
595 return auth_ismanager($user, $groups, true, $recache);
599 * Match a user and his groups against a comma separated list of
600 * users and groups to determine membership status
602 * Note: all input should NOT be nameencoded.
604 * @param string $memberlist commaseparated list of allowed users and groups
605 * @param string $user user to match against
606 * @param array $groups groups the user is member of
607 * @return bool true for membership acknowledged
609 function auth_isMember($memberlist, $user, array $groups)
611 /* @var AuthPlugin $auth */
613 if (!$auth instanceof AuthPlugin
) return false;
615 // clean user and groups
616 if (!$auth->isCaseSensitive()) {
617 $user = PhpString
::strtolower($user);
618 $groups = array_map([PhpString
::class, 'strtolower'], $groups);
620 $user = $auth->cleanUser($user);
621 $groups = array_map([$auth, 'cleanGroup'], $groups);
623 // extract the memberlist
624 $members = explode(',', $memberlist);
625 $members = array_map('trim', $members);
626 $members = array_unique($members);
627 $members = array_filter($members);
629 // compare cleaned values
630 foreach ($members as $member) {
631 if ($member == '@ALL') return true;
632 if (!$auth->isCaseSensitive()) $member = PhpString
::strtolower($member);
633 if ($member[0] == '@') {
634 $member = $auth->cleanGroup(substr($member, 1));
635 if (in_array($member, $groups)) return true;
637 $member = $auth->cleanUser($member);
638 if ($member == $user) return true;
642 // still here? not a member!
647 * Convinience function for auth_aclcheck()
649 * This checks the permissions for the current user
651 * @author Andreas Gohr <andi@splitbrain.org>
653 * @param string $id page ID (needs to be resolved and cleaned)
654 * @return int permission level
656 function auth_quickaclcheck($id)
660 /* @var Input $INPUT */
662 # if no ACL is used always return upload rights
663 if (!$conf['useacl']) return AUTH_UPLOAD
;
664 return auth_aclcheck($id, $INPUT->server
->str('REMOTE_USER'), is_array($USERINFO) ?
$USERINFO['grps'] : []);
668 * Returns the maximum rights a user has for the given ID or its namespace
670 * @author Andreas Gohr <andi@splitbrain.org>
672 * @triggers AUTH_ACL_CHECK
673 * @param string $id page ID (needs to be resolved and cleaned)
674 * @param string $user Username
675 * @param array|null $groups Array of groups the user is in
676 * @return int permission level
678 function auth_aclcheck($id, $user, $groups)
686 return Event
::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
690 * default ACL check method
692 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
694 * @author Andreas Gohr <andi@splitbrain.org>
696 * @param array $data event data
697 * @return int permission level
699 function auth_aclcheck_cb($data)
702 $user =& $data['user'];
703 $groups =& $data['groups'];
707 /* @var AuthPlugin $auth */
710 // if no ACL is used always return upload rights
711 if (!$conf['useacl']) return AUTH_UPLOAD
;
712 if (!$auth instanceof AuthPlugin
) return AUTH_NONE
;
713 if (!is_array($AUTH_ACL)) return AUTH_NONE
;
715 //make sure groups is an array
716 if (!is_array($groups)) $groups = [];
718 //if user is superuser or in superusergroup return 255 (acl_admin)
719 if (auth_isadmin($user, $groups)) {
723 if (!$auth->isCaseSensitive()) {
724 $user = PhpString
::strtolower($user);
725 $groups = array_map([PhpString
::class, 'strtolower'], $groups);
727 $user = auth_nameencode($auth->cleanUser($user));
728 $groups = array_map([$auth, 'cleanGroup'], $groups);
730 //prepend groups with @ and nameencode
731 foreach ($groups as &$group) {
732 $group = '@' . auth_nameencode($group);
742 if ($user) $groups[] = $user;
744 //check exact match first
745 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
746 if (count($matches)) {
747 foreach ($matches as $match) {
748 $match = preg_replace('/#.*$/', '', $match); //ignore comments
749 $acl = preg_split('/[ \t]+/', $match);
750 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
751 $acl[1] = PhpString
::strtolower($acl[1]);
753 if (!in_array($acl[1], $groups)) {
756 if ($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
757 if ($acl[2] > $perm) {
762 //we had a match - return it
767 //still here? do the namespace checks
771 $path = '*'; //root document
775 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
776 if (count($matches)) {
777 foreach ($matches as $match) {
778 $match = preg_replace('/#.*$/', '', $match); //ignore comments
779 $acl = preg_split('/[ \t]+/', $match);
780 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
781 $acl[1] = PhpString
::strtolower($acl[1]);
783 if (!in_array($acl[1], $groups)) {
786 if ($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
787 if ($acl[2] > $perm) {
791 //we had a match - return it
796 //get next higher namespace
801 if ($path == ':*') $path = '*';
803 //we did this already
804 //looks like there is something wrong with the ACL
806 msg('No ACL setup yet! Denying access to everyone.');
809 } while (1); //this should never loop endless
814 * Encode ASCII special chars
816 * Some auth backends allow special chars in their user and groupnames
817 * The special chars are encoded with this function. Only ASCII chars
818 * are encoded UTF-8 multibyte are left as is (different from usual
821 * Decoding can be done with rawurldecode
823 * @author Andreas Gohr <gohr@cosmocode.de>
824 * @see rawurldecode()
826 * @param string $name
827 * @param bool $skip_group
830 function auth_nameencode($name, $skip_group = false)
832 global $cache_authname;
833 $cache =& $cache_authname;
834 $name = (string) $name;
836 // never encode wildcard FS#1955
837 if ($name == '%USER%') return $name;
838 if ($name == '%GROUP%') return $name;
840 if (!isset($cache[$name][$skip_group])) {
841 if ($skip_group && $name[0] == '@') {
842 $cache[$name][$skip_group] = '@' . preg_replace_callback(
843 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
844 'auth_nameencode_callback',
848 $cache[$name][$skip_group] = preg_replace_callback(
849 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
850 'auth_nameencode_callback',
856 return $cache[$name][$skip_group];
860 * callback encodes the matches
862 * @param array $matches first complete match, next matching subpatterms
865 function auth_nameencode_callback($matches)
867 return '%' . dechex(ord(substr($matches[1], -1)));
871 * Create a pronouncable password
873 * The $foruser variable might be used by plugins to run additional password
874 * policy checks, but is not used by the default implementation
876 * @param string $foruser username for which the password is generated
877 * @return string pronouncable password
880 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
881 * @triggers AUTH_PASSWORD_GENERATE
883 * @author Andreas Gohr <andi@splitbrain.org>
885 function auth_pwgen($foruser = '')
889 'foruser' => $foruser
892 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
893 if ($evt->advise_before(true)) {
894 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
895 $v = 'aeiou'; //vowels
897 $s = '!$%&?+*~#-_:.;,'; // specials
899 //use thre syllables...
900 for ($i = 0; $i < 3; $i++
) {
901 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
902 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
903 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
905 //... and add a nice number and special
906 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
908 $evt->advise_after();
910 return $data['password'];
914 * Sends a password to the given user
916 * @author Andreas Gohr <andi@splitbrain.org>
918 * @param string $user Login name of the user
919 * @param string $password The new password in clear text
920 * @return bool true on success
922 function auth_sendPassword($user, $password)
925 /* @var AuthPlugin $auth */
927 if (!$auth instanceof AuthPlugin
) return false;
929 $user = $auth->cleanUser($user);
930 $userinfo = $auth->getUserData($user, false);
932 if (!$userinfo['mail']) return false;
934 $text = rawLocale('password');
936 'FULLNAME' => $userinfo['name'],
938 'PASSWORD' => $password
941 $mail = new Mailer();
942 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
943 $mail->subject($lang['regpwmail']);
944 $mail->setBody($text, $trep);
945 return $mail->send();
949 * Register a new user
951 * This registers a new user - Data is read directly from $_POST
953 * @return bool true on success, false on any error
956 * @author Andreas Gohr <andi@splitbrain.org>
962 /* @var AuthPlugin $auth */
966 if (!$INPUT->post
->bool('save')) return false;
967 if (!actionOK('register')) return false;
970 $login = trim($auth->cleanUser($INPUT->post
->str('login')));
971 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post
->str('fullname')));
972 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post
->str('email')));
973 $pass = $INPUT->post
->str('pass');
974 $passchk = $INPUT->post
->str('passchk');
976 if (empty($login) ||
empty($fullname) ||
empty($email)) {
977 msg($lang['regmissing'], -1);
981 if ($conf['autopasswd']) {
982 $pass = auth_pwgen($login); // automatically generate password
983 } elseif (empty($pass) ||
empty($passchk)) {
984 msg($lang['regmissing'], -1); // complain about missing passwords
986 } elseif ($pass != $passchk) {
987 msg($lang['regbadpass'], -1); // complain about misspelled passwords
992 if (!mail_isvalid($email)) {
993 msg($lang['regbadmail'], -1);
997 //okay try to create the user
998 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
999 msg($lang['regfail'], -1);
1003 // send notification about the new user
1004 $subscription = new RegistrationSubscriptionSender();
1005 $subscription->sendRegister($login, $fullname, $email);
1008 if (!$conf['autopasswd']) {
1009 msg($lang['regsuccess2'], 1);
1013 // autogenerated password? then send password to user
1014 if (auth_sendPassword($login, $pass)) {
1015 msg($lang['regsuccess'], 1);
1018 msg($lang['regmailfail'], -1);
1024 * Update user profile
1028 * @author Christopher Smith <chris@jalakai.co.uk>
1030 function updateprofile()
1034 /* @var AuthPlugin $auth */
1036 /* @var Input $INPUT */
1039 if (!$INPUT->post
->bool('save')) return false;
1040 if (!checkSecurityToken()) return false;
1042 if (!actionOK('profile')) {
1043 msg($lang['profna'], -1);
1048 $changes['pass'] = $INPUT->post
->str('newpass');
1049 $changes['name'] = $INPUT->post
->str('fullname');
1050 $changes['mail'] = $INPUT->post
->str('email');
1052 // check misspelled passwords
1053 if ($changes['pass'] != $INPUT->post
->str('passchk')) {
1054 msg($lang['regbadpass'], -1);
1058 // clean fullname and email
1059 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1060 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1062 // no empty name and email (except the backend doesn't support them)
1064 (empty($changes['name']) && $auth->canDo('modName')) ||
1065 (empty($changes['mail']) && $auth->canDo('modMail'))
1067 msg($lang['profnoempty'], -1);
1070 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1071 msg($lang['regbadmail'], -1);
1075 $changes = array_filter($changes);
1077 // check for unavailable capabilities
1078 if (!$auth->canDo('modName')) unset($changes['name']);
1079 if (!$auth->canDo('modMail')) unset($changes['mail']);
1080 if (!$auth->canDo('modPass')) unset($changes['pass']);
1083 if ($changes === []) {
1084 msg($lang['profnochange'], -1);
1088 if ($conf['profileconfirm']) {
1089 if (!$auth->checkPass($INPUT->server
->str('REMOTE_USER'), $INPUT->post
->str('oldpass'))) {
1090 msg($lang['badpassconfirm'], -1);
1095 if (!$auth->triggerUserMod('modify', [$INPUT->server
->str('REMOTE_USER'), &$changes])) {
1096 msg($lang['proffail'], -1);
1100 if (array_key_exists('pass', $changes) && $changes['pass']) {
1101 // update cookie and session with the changed data
1102 [/* user */, $sticky, /* pass */] = auth_getCookie();
1103 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1104 auth_setCookie($INPUT->server
->str('REMOTE_USER'), $pass, (bool) $sticky);
1106 // make sure the session is writable
1108 // invalidate session cache
1109 $_SESSION[DOKU_COOKIE
]['auth']['time'] = 0;
1110 session_write_close();
1117 * Delete the current logged-in user
1119 * @return bool true on success, false on any error
1121 function auth_deleteprofile()
1125 /* @var AuthPlugin $auth */
1127 /* @var Input $INPUT */
1130 if (!$INPUT->post
->bool('delete')) return false;
1131 if (!checkSecurityToken()) return false;
1133 // action prevented or auth module disallows
1134 if (!actionOK('profile_delete') ||
!$auth->canDo('delUser')) {
1135 msg($lang['profnodelete'], -1);
1139 if (!$INPUT->post
->bool('confirm_delete')) {
1140 msg($lang['profconfdeletemissing'], -1);
1144 if ($conf['profileconfirm']) {
1145 if (!$auth->checkPass($INPUT->server
->str('REMOTE_USER'), $INPUT->post
->str('oldpass'))) {
1146 msg($lang['badpassconfirm'], -1);
1152 $deleted[] = $INPUT->server
->str('REMOTE_USER');
1153 if ($auth->triggerUserMod('delete', [$deleted])) {
1154 // force and immediate logout including removing the sticky cookie
1163 * Send a new password
1165 * This function handles both phases of the password reset:
1167 * - handling the first request of password reset
1168 * - validating the password reset auth token
1170 * @return bool true on success, false on any error
1173 * @author Andreas Gohr <andi@splitbrain.org>
1174 * @author Benoit Chesneau <benoit@bchesneau.info>
1175 * @author Chris Smith <chris@jalakai.co.uk>
1177 function act_resendpwd()
1181 /* @var AuthPlugin $auth */
1183 /* @var Input $INPUT */
1186 if (!actionOK('resendpwd')) {
1187 msg($lang['resendna'], -1);
1191 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1194 // we're in token phase - get user info from token
1196 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1197 if (!file_exists($tfile)) {
1198 msg($lang['resendpwdbadauth'], -1);
1199 $INPUT->remove('pwauth');
1202 // token is only valid for 3 days
1203 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1204 msg($lang['resendpwdbadauth'], -1);
1205 $INPUT->remove('pwauth');
1210 $user = io_readfile($tfile);
1211 $userinfo = $auth->getUserData($user, false);
1212 if (!$userinfo['mail']) {
1213 msg($lang['resendpwdnouser'], -1);
1217 if (!$conf['autopasswd']) { // we let the user choose a password
1218 $pass = $INPUT->str('pass');
1220 // password given correctly?
1221 if (!$pass) return false;
1222 if ($pass != $INPUT->str('passchk')) {
1223 msg($lang['regbadpass'], -1);
1228 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1229 msg($lang['proffail'], -1);
1232 } else { // autogenerate the password and send by mail
1233 $pass = auth_pwgen($user);
1234 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1235 msg($lang['proffail'], -1);
1239 if (auth_sendPassword($user, $pass)) {
1240 msg($lang['resendpwdsuccess'], 1);
1242 msg($lang['regmailfail'], -1);
1249 // we're in request phase
1251 if (!$INPUT->post
->bool('save')) return false;
1253 if (!$INPUT->post
->str('login')) {
1254 msg($lang['resendpwdmissing'], -1);
1257 $user = trim($auth->cleanUser($INPUT->post
->str('login')));
1260 $userinfo = $auth->getUserData($user, false);
1261 if (!$userinfo['mail']) {
1262 msg($lang['resendpwdnouser'], -1);
1266 // generate auth token
1267 $token = md5(auth_randombytes(16)); // random secret
1268 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1269 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1271 io_saveFile($tfile, $user);
1273 $text = rawLocale('pwconfirm');
1274 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
1276 $mail = new Mailer();
1277 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1278 $mail->subject($lang['regpwmail']);
1279 $mail->setBody($text, $trep);
1280 if ($mail->send()) {
1281 msg($lang['resendpwdconfirm'], 1);
1283 msg($lang['regmailfail'], -1);
1291 * Encrypts a password using the given method and salt
1293 * If the selected method needs a salt and none was given, a random one
1296 * @author Andreas Gohr <andi@splitbrain.org>
1298 * @param string $clear The clear text password
1299 * @param string $method The hashing method
1300 * @param string $salt A salt, null for random
1301 * @return string The crypted password
1303 function auth_cryptPassword($clear, $method = '', $salt = null)
1306 if (empty($method)) $method = $conf['passcrypt'];
1308 $pass = new PassHash();
1309 $call = 'hash_' . $method;
1311 if (!method_exists($pass, $call)) {
1312 msg("Unsupported crypt method $method", -1);
1316 return $pass->$call($clear, $salt);
1320 * Verifies a cleartext password against a crypted hash
1322 * @param string $clear The clear text password
1323 * @param string $crypt The hash to compare with
1324 * @return bool true if both match
1327 * @author Andreas Gohr <andi@splitbrain.org>
1329 function auth_verifyPassword($clear, $crypt)
1331 $pass = new PassHash();
1332 return $pass->verify_hash($clear, $crypt);
1336 * Set the authentication cookie and add user identification data to the session
1338 * @param string $user username
1339 * @param string $pass encrypted password
1340 * @param bool $sticky whether or not the cookie will last beyond the session
1343 function auth_setCookie($user, $pass, $sticky)
1346 /* @var AuthPlugin $auth */
1350 if (!$auth instanceof AuthPlugin
) return false;
1351 $USERINFO = $auth->getUserData($user);
1354 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1355 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL
: $conf['cookiedir'];
1356 $time = $sticky ?
(time() +
60 * 60 * 24 * 365) : 0; //one year
1357 setcookie(DOKU_COOKIE
, $cookie, [
1359 'path' => $cookieDir,
1360 'secure' => ($conf['securecookie'] && is_ssl()),
1362 'samesite' => $conf['samesitecookie'] ?
: null, // null means browser default
1366 $_SESSION[DOKU_COOKIE
]['auth']['user'] = $user;
1367 $_SESSION[DOKU_COOKIE
]['auth']['pass'] = sha1($pass);
1368 $_SESSION[DOKU_COOKIE
]['auth']['buid'] = auth_browseruid();
1369 $_SESSION[DOKU_COOKIE
]['auth']['info'] = $USERINFO;
1370 $_SESSION[DOKU_COOKIE
]['auth']['time'] = time();
1376 * Returns the user, (encrypted) password and sticky bit from cookie
1380 function auth_getCookie()
1382 if (!isset($_COOKIE[DOKU_COOKIE
])) {
1383 return [null, null, null];
1385 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE
], 3, '');
1386 $sticky = (bool) $sticky;
1387 $pass = base64_decode($pass);
1388 $user = base64_decode($user);
1389 return [$user, $sticky, $pass];
1392 //Setup VIM: ex: et ts=2 :