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>
13 use phpseclib\Crypt\AES
;
14 use dokuwiki\Utf8\PhpString
;
15 use dokuwiki\Extension\AuthPlugin
;
16 use dokuwiki\Extension\Event
;
17 use dokuwiki\Extension\PluginController
;
18 use dokuwiki\PassHash
;
19 use dokuwiki\Subscriptions\RegistrationSubscriptionSender
;
22 * Initialize the auth system.
24 * This function is automatically called at the end of init.php
26 * This used to be the main() of the auth.php
28 * @todo backend loading maybe should be handled by the class autoloader
29 * @todo maybe split into multiple functions at the XXX marked positions
30 * @triggers AUTH_LOGIN_CHECK
36 /* @var AuthPlugin $auth */
38 /* @var Input $INPUT */
42 /* @var PluginController $plugin_controller */
43 global $plugin_controller;
46 if (!$conf['useacl']) return false;
48 // try to load auth backend from plugins
49 foreach ($plugin_controller->getList('auth') as $plugin) {
50 if ($conf['authtype'] === $plugin) {
51 $auth = $plugin_controller->load('auth', $plugin);
56 if (!$auth instanceof AuthPlugin
) {
57 msg($lang['authtempfail'], -1);
61 if ($auth->success
== false) {
62 // degrade to unauthenticated user
65 msg($lang['authtempfail'], -1);
69 // do the login either by cookie or provided credentials XXX
70 $INPUT->set('http_credentials', false);
71 if (!$conf['rememberme']) $INPUT->set('r', false);
73 // Populate Basic Auth user/password from Authorization header
74 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
75 $header = $INPUT->server
->str('HTTP_AUTHORIZATION') ?
: $INPUT->server
->str('REDIRECT_HTTP_AUTHORIZATION');
76 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
77 $userpass = explode(':', base64_decode($matches[1]));
78 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
81 // if no credentials were given try to use HTTP auth (for SSO)
82 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE
]) && !empty($INPUT->server
->str('PHP_AUTH_USER'))) {
83 $INPUT->set('u', $INPUT->server
->str('PHP_AUTH_USER'));
84 $INPUT->set('p', $INPUT->server
->str('PHP_AUTH_PW'));
85 $INPUT->set('http_credentials', true);
88 // apply cleaning (auth specific user names, remove control chars)
89 if (true === $auth->success
) {
90 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91 $INPUT->set('p', stripctl($INPUT->str('p')));
94 if(!auth_tokenlogin()) {
97 if ($auth instanceof AuthPlugin
&& $auth->canDo('external')) {
98 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
102 // external trust mechanism not in place, or returns no result,
103 // then attempt auth_login
105 'user' => $INPUT->str('u'),
106 'password' => $INPUT->str('p'),
107 'sticky' => $INPUT->bool('r'),
108 'silent' => $INPUT->bool('http_credentials')
110 Event
::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
114 //load ACL into a global array XXX
115 $AUTH_ACL = auth_loadACL();
121 * Loads the ACL setup and handle user wildcards
123 * @author Andreas Gohr <andi@splitbrain.org>
127 function auth_loadACL()
129 global $config_cascade;
131 /* @var Input $INPUT */
134 if (!is_readable($config_cascade['acl']['default'])) return [];
136 $acl = file($config_cascade['acl']['default']);
139 foreach ($acl as $line) {
141 if (empty($line) ||
($line[0] == '#')) continue; // skip blank lines & comments
142 [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
144 // substitute user wildcard first (its 1:1)
145 if (strstr($line, '%USER%')) {
146 // if user is not logged in, this ACL line is meaningless - skip it
147 if (!$INPUT->server
->has('REMOTE_USER')) continue;
149 $id = str_replace('%USER%', cleanID($INPUT->server
->str('REMOTE_USER')), $id);
150 $rest = str_replace('%USER%', auth_nameencode($INPUT->server
->str('REMOTE_USER')), $rest);
153 // substitute group wildcard (its 1:m)
154 if (strstr($line, '%GROUP%')) {
155 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
156 if (isset($USERINFO['grps'])) {
157 foreach ((array) $USERINFO['grps'] as $grp) {
158 $nid = str_replace('%GROUP%', cleanID($grp), $id);
159 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
160 $out[] = "$nid\t$nrest";
164 $out[] = "$id\t$rest";
174 * @return bool true if token login succeeded
176 function auth_tokenlogin() {
179 /** @var DokuWiki_Auth_Plugin $auth */
181 if(!$auth) return false;
183 // see if header has token
185 if(function_exists('apache_request_headers')) {
186 // Authorization headers are not in $_SERVER for mod_php
187 $headers = apache_request_headers();
188 if(isset($headers['Authorization'])) $header = $headers['Authorization'];
190 $header = $INPUT->server
->str('HTTP_AUTHORIZATION');
192 if(!$header) return false;
193 list($type, $token) = sexplode(' ', $header, 2);
194 if($type !== 'Bearer') return false;
198 $authtoken = \dokuwiki\JWT
::validate($token);
199 } catch (Exception
$e) {
200 msg(hsc($e->getMessage()), -1);
204 // fetch user info from backend
205 $user = $authtoken->getUser();
206 $USERINFO = $auth->getUserData($user);
207 if(!$USERINFO) return false;
209 // the code is correct, set up user
210 $INPUT->server
->set('REMOTE_USER', $user);
211 $_SESSION[DOKU_COOKIE
]['auth']['user'] = $user;
212 $_SESSION[DOKU_COOKIE
]['auth']['pass'] = 'nope';
213 $_SESSION[DOKU_COOKIE
]['auth']['info'] = $USERINFO;
219 * Event hook callback for AUTH_LOGIN_CHECK
221 * @param array $evdata
225 function auth_login_wrapper($evdata)
236 * This tries to login the user based on the sent auth credentials
238 * The authentication works like this: if a username was given
239 * a new login is assumed and user/password are checked. If they
240 * are correct the password is encrypted with blowfish and stored
241 * together with the username in a cookie - the same info is stored
242 * in the session, too. Additonally a browserID is stored in the
245 * If no username was given the cookie is checked: if the username,
246 * crypted password and browserID match between session and cookie
247 * no further testing is done and the user is accepted
249 * If a cookie was found but no session info was availabe the
250 * blowfish encrypted password from the cookie is decrypted and
251 * together with username rechecked by calling this function again.
253 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
256 * @param string $user Username
257 * @param string $pass Cleartext Password
258 * @param bool $sticky Cookie should not expire
259 * @param bool $silent Don't show error on bad auth
260 * @return bool true on successful auth
263 * @author Andreas Gohr <andi@splitbrain.org>
265 function auth_login($user, $pass, $sticky = false, $silent = false)
270 /* @var AuthPlugin $auth */
272 /* @var Input $INPUT */
275 if (!$auth instanceof AuthPlugin
) return false;
279 if (!empty($pass) && $auth->checkPass($user, $pass)) {
280 // make logininfo globally available
281 $INPUT->server
->set('REMOTE_USER', $user);
282 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
283 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
286 //invalid credentials - log off
288 http_status(403, 'Login failed');
289 msg($lang['badlogin'], -1);
295 // read cookie information
296 [$user, $sticky, $pass] = auth_getCookie();
297 if ($user && $pass) {
298 // we got a cookie - see if we can trust it
301 if (isset($_SESSION[DOKU_COOKIE
])) {
302 $session = $_SESSION[DOKU_COOKIE
]['auth'];
305 $auth->useSessionCache($user) &&
306 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
307 ($session['user'] == $user) &&
308 ($session['pass'] == sha1($pass)) && //still crypted
309 ($session['buid'] == auth_browseruid())
311 // he has session, cookie and browser right - let him in
312 $INPUT->server
->set('REMOTE_USER', $user);
313 $USERINFO = $session['info']; //FIXME move all references to session
317 // no we don't trust it yet - recheck pass but silent
318 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
319 $pass = auth_decrypt($pass, $secret);
320 return auth_login($user, $pass, $sticky, true);
329 * Builds a pseudo UID from browser and IP data
331 * This is neither unique nor unfakable - still it adds some
332 * security. Using the first part of the IP makes sure
333 * proxy farms like AOLs are still okay.
335 * @author Andreas Gohr <andi@splitbrain.org>
337 * @return string a SHA256 sum of various browser headers
339 function auth_browseruid()
341 /* @var Input $INPUT */
344 $ip = clientIP(true);
345 // convert IP string to packed binary representation
346 $pip = inet_pton($ip);
348 $uid = implode("\n", [
349 $INPUT->server
->str('HTTP_USER_AGENT'),
350 $INPUT->server
->str('HTTP_ACCEPT_LANGUAGE'),
351 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
353 return hash('sha256', $uid);
357 * Creates a random key to encrypt the password in cookies
359 * This function tries to read the password for encrypting
360 * cookies from $conf['metadir'].'/_htcookiesalt'
361 * if no such file is found a random key is created and
362 * and stored in this file.
364 * @param bool $addsession if true, the sessionid is added to the salt
365 * @param bool $secure if security is more important than keeping the old value
369 * @author Andreas Gohr <andi@splitbrain.org>
371 function auth_cookiesalt($addsession = false, $secure = false)
373 if (defined('SIMPLE_TEST')) {
377 $file = $conf['metadir'] . '/_htcookiesalt';
378 if ($secure ||
!file_exists($file)) {
379 $file = $conf['metadir'] . '/_htcookiesalt2';
381 $salt = io_readFile($file);
383 $salt = bin2hex(auth_randombytes(64));
384 io_saveFile($file, $salt);
387 $salt .= session_id();
393 * Return cryptographically secure random bytes.
395 * @param int $length number of bytes
396 * @return string cryptographically secure random bytes
399 * @author Niklas Keller <me@kelunik.com>
401 function auth_randombytes($length)
403 return random_bytes($length);
407 * Cryptographically secure random number generator.
414 * @author Niklas Keller <me@kelunik.com>
416 function auth_random($min, $max)
418 return random_int($min, $max);
422 * Encrypt data using the given secret using AES
424 * The mode is CBC with a random initialization vector, the key is derived
427 * @param string $data The data that shall be encrypted
428 * @param string $secret The secret/password that shall be used
429 * @return string The ciphertext
432 function auth_encrypt($data, $secret)
434 $iv = auth_randombytes(16);
436 $cipher->setPassword($secret);
439 this uses the encrypted IV as IV as suggested in
440 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
441 for unique but necessarily random IVs. The resulting ciphertext is
442 compatible to ciphertext that was created using a "normal" IV.
444 return $cipher->encrypt($iv . $data);
448 * Decrypt the given AES ciphertext
450 * The mode is CBC, the key is derived using pbkdf2
452 * @param string $ciphertext The encrypted data
453 * @param string $secret The secret/password that shall be used
454 * @return string The decrypted data
456 function auth_decrypt($ciphertext, $secret)
458 $iv = substr($ciphertext, 0, 16);
460 $cipher->setPassword($secret);
463 return $cipher->decrypt(substr($ciphertext, 16));
467 * Log out the current user
469 * This clears all authentication data and thus log the user
470 * off. It also clears session data.
472 * @author Andreas Gohr <andi@splitbrain.org>
474 * @param bool $keepbc - when true, the breadcrumb data is not cleared
476 function auth_logoff($keepbc = false)
480 /* @var AuthPlugin $auth */
482 /* @var Input $INPUT */
485 // make sure the session is writable (it usually is)
488 if (isset($_SESSION[DOKU_COOKIE
]['auth']['user']))
489 unset($_SESSION[DOKU_COOKIE
]['auth']['user']);
490 if (isset($_SESSION[DOKU_COOKIE
]['auth']['pass']))
491 unset($_SESSION[DOKU_COOKIE
]['auth']['pass']);
492 if (isset($_SESSION[DOKU_COOKIE
]['auth']['info']))
493 unset($_SESSION[DOKU_COOKIE
]['auth']['info']);
494 if (!$keepbc && isset($_SESSION[DOKU_COOKIE
]['bc']))
495 unset($_SESSION[DOKU_COOKIE
]['bc']);
496 $INPUT->server
->remove('REMOTE_USER');
497 $USERINFO = null; //FIXME
499 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL
: $conf['cookiedir'];
500 setcookie(DOKU_COOKIE
, '', [
501 'expires' => time() - 600000,
502 'path' => $cookieDir,
503 'secure' => ($conf['securecookie'] && is_ssl()),
505 'samesite' => $conf['samesitecookie'] ?
: null, // null means browser default
508 if ($auth instanceof AuthPlugin
) {
514 * Check if a user is a manager
516 * Should usually be called without any parameters to check the current
519 * The info is available through $INFO['ismanager'], too
521 * @param string $user Username
522 * @param array $groups List of groups the user is in
523 * @param bool $adminonly when true checks if user is admin
524 * @param bool $recache set to true to refresh the cache
528 * @author Andreas Gohr <andi@splitbrain.org>
530 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
534 /* @var AuthPlugin $auth */
536 /* @var Input $INPUT */
540 if (!$auth instanceof AuthPlugin
) return false;
541 if (is_null($user)) {
542 if (!$INPUT->server
->has('REMOTE_USER')) {
545 $user = $INPUT->server
->str('REMOTE_USER');
548 if (is_null($groups)) {
549 // checking the logged in user, or another one?
550 if ($USERINFO && $user === $INPUT->server
->str('REMOTE_USER')) {
551 $groups = (array) $USERINFO['grps'];
553 $groups = $auth->getUserData($user);
554 $groups = $groups ?
$groups['grps'] : [];
558 // prefer cached result
560 $cachekey = serialize([$user, $adminonly, $groups]);
561 if (!isset($cache[$cachekey]) ||
$recache) {
562 // check superuser match
563 $ok = auth_isMember($conf['superuser'], $user, $groups);
566 if (!$ok && !$adminonly) {
567 $ok = auth_isMember($conf['manager'], $user, $groups);
570 $cache[$cachekey] = $ok;
573 return $cache[$cachekey];
577 * Check if a user is admin
579 * Alias to auth_ismanager with adminonly=true
581 * The info is available through $INFO['isadmin'], too
583 * @param string $user Username
584 * @param array $groups List of groups the user is in
585 * @param bool $recache set to true to refresh the cache
587 * @author Andreas Gohr <andi@splitbrain.org>
588 * @see auth_ismanager()
591 function auth_isadmin($user = null, $groups = null, $recache = false)
593 return auth_ismanager($user, $groups, true, $recache);
597 * Match a user and his groups against a comma separated list of
598 * users and groups to determine membership status
600 * Note: all input should NOT be nameencoded.
602 * @param string $memberlist commaseparated list of allowed users and groups
603 * @param string $user user to match against
604 * @param array $groups groups the user is member of
605 * @return bool true for membership acknowledged
607 function auth_isMember($memberlist, $user, array $groups)
609 /* @var AuthPlugin $auth */
611 if (!$auth instanceof AuthPlugin
) return false;
613 // clean user and groups
614 if (!$auth->isCaseSensitive()) {
615 $user = PhpString
::strtolower($user);
616 $groups = array_map([PhpString
::class, 'strtolower'], $groups);
618 $user = $auth->cleanUser($user);
619 $groups = array_map([$auth, 'cleanGroup'], $groups);
621 // extract the memberlist
622 $members = explode(',', $memberlist);
623 $members = array_map('trim', $members);
624 $members = array_unique($members);
625 $members = array_filter($members);
627 // compare cleaned values
628 foreach ($members as $member) {
629 if ($member == '@ALL') return true;
630 if (!$auth->isCaseSensitive()) $member = PhpString
::strtolower($member);
631 if ($member[0] == '@') {
632 $member = $auth->cleanGroup(substr($member, 1));
633 if (in_array($member, $groups)) return true;
635 $member = $auth->cleanUser($member);
636 if ($member == $user) return true;
640 // still here? not a member!
645 * Convinience function for auth_aclcheck()
647 * This checks the permissions for the current user
649 * @author Andreas Gohr <andi@splitbrain.org>
651 * @param string $id page ID (needs to be resolved and cleaned)
652 * @return int permission level
654 function auth_quickaclcheck($id)
658 /* @var Input $INPUT */
660 # if no ACL is used always return upload rights
661 if (!$conf['useacl']) return AUTH_UPLOAD
;
662 return auth_aclcheck($id, $INPUT->server
->str('REMOTE_USER'), is_array($USERINFO) ?
$USERINFO['grps'] : []);
666 * Returns the maximum rights a user has for the given ID or its namespace
668 * @author Andreas Gohr <andi@splitbrain.org>
670 * @triggers AUTH_ACL_CHECK
671 * @param string $id page ID (needs to be resolved and cleaned)
672 * @param string $user Username
673 * @param array|null $groups Array of groups the user is in
674 * @return int permission level
676 function auth_aclcheck($id, $user, $groups)
684 return Event
::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
688 * default ACL check method
690 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
692 * @author Andreas Gohr <andi@splitbrain.org>
694 * @param array $data event data
695 * @return int permission level
697 function auth_aclcheck_cb($data)
700 $user =& $data['user'];
701 $groups =& $data['groups'];
705 /* @var AuthPlugin $auth */
708 // if no ACL is used always return upload rights
709 if (!$conf['useacl']) return AUTH_UPLOAD
;
710 if (!$auth instanceof AuthPlugin
) return AUTH_NONE
;
711 if (!is_array($AUTH_ACL)) return AUTH_NONE
;
713 //make sure groups is an array
714 if (!is_array($groups)) $groups = [];
716 //if user is superuser or in superusergroup return 255 (acl_admin)
717 if (auth_isadmin($user, $groups)) {
721 if (!$auth->isCaseSensitive()) {
722 $user = PhpString
::strtolower($user);
723 $groups = array_map([PhpString
::class, 'strtolower'], $groups);
725 $user = auth_nameencode($auth->cleanUser($user));
726 $groups = array_map([$auth, 'cleanGroup'], $groups);
728 //prepend groups with @ and nameencode
729 foreach ($groups as &$group) {
730 $group = '@' . auth_nameencode($group);
740 if ($user) $groups[] = $user;
742 //check exact match first
743 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
744 if (count($matches)) {
745 foreach ($matches as $match) {
746 $match = preg_replace('/#.*$/', '', $match); //ignore comments
747 $acl = preg_split('/[ \t]+/', $match);
748 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
749 $acl[1] = PhpString
::strtolower($acl[1]);
751 if (!in_array($acl[1], $groups)) {
754 if ($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
755 if ($acl[2] > $perm) {
760 //we had a match - return it
765 //still here? do the namespace checks
769 $path = '*'; //root document
773 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
774 if (count($matches)) {
775 foreach ($matches as $match) {
776 $match = preg_replace('/#.*$/', '', $match); //ignore comments
777 $acl = preg_split('/[ \t]+/', $match);
778 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
779 $acl[1] = PhpString
::strtolower($acl[1]);
781 if (!in_array($acl[1], $groups)) {
784 if ($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
785 if ($acl[2] > $perm) {
789 //we had a match - return it
794 //get next higher namespace
799 if ($path == ':*') $path = '*';
801 //we did this already
802 //looks like there is something wrong with the ACL
804 msg('No ACL setup yet! Denying access to everyone.');
807 } while (1); //this should never loop endless
812 * Encode ASCII special chars
814 * Some auth backends allow special chars in their user and groupnames
815 * The special chars are encoded with this function. Only ASCII chars
816 * are encoded UTF-8 multibyte are left as is (different from usual
819 * Decoding can be done with rawurldecode
821 * @author Andreas Gohr <gohr@cosmocode.de>
822 * @see rawurldecode()
824 * @param string $name
825 * @param bool $skip_group
828 function auth_nameencode($name, $skip_group = false)
830 global $cache_authname;
831 $cache =& $cache_authname;
832 $name = (string) $name;
834 // never encode wildcard FS#1955
835 if ($name == '%USER%') return $name;
836 if ($name == '%GROUP%') return $name;
838 if (!isset($cache[$name][$skip_group])) {
839 if ($skip_group && $name[0] == '@') {
840 $cache[$name][$skip_group] = '@' . preg_replace_callback(
841 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
842 'auth_nameencode_callback',
846 $cache[$name][$skip_group] = preg_replace_callback(
847 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
848 'auth_nameencode_callback',
854 return $cache[$name][$skip_group];
858 * callback encodes the matches
860 * @param array $matches first complete match, next matching subpatterms
863 function auth_nameencode_callback($matches)
865 return '%' . dechex(ord(substr($matches[1], -1)));
869 * Create a pronouncable password
871 * The $foruser variable might be used by plugins to run additional password
872 * policy checks, but is not used by the default implementation
874 * @param string $foruser username for which the password is generated
875 * @return string pronouncable password
878 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
879 * @triggers AUTH_PASSWORD_GENERATE
881 * @author Andreas Gohr <andi@splitbrain.org>
883 function auth_pwgen($foruser = '')
887 'foruser' => $foruser
890 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
891 if ($evt->advise_before(true)) {
892 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
893 $v = 'aeiou'; //vowels
895 $s = '!$%&?+*~#-_:.;,'; // specials
897 //use thre syllables...
898 for ($i = 0; $i < 3; $i++
) {
899 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
900 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
901 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
903 //... and add a nice number and special
904 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
906 $evt->advise_after();
908 return $data['password'];
912 * Sends a password to the given user
914 * @author Andreas Gohr <andi@splitbrain.org>
916 * @param string $user Login name of the user
917 * @param string $password The new password in clear text
918 * @return bool true on success
920 function auth_sendPassword($user, $password)
923 /* @var AuthPlugin $auth */
925 if (!$auth instanceof AuthPlugin
) return false;
927 $user = $auth->cleanUser($user);
928 $userinfo = $auth->getUserData($user, false);
930 if (!$userinfo['mail']) return false;
932 $text = rawLocale('password');
934 'FULLNAME' => $userinfo['name'],
936 'PASSWORD' => $password
939 $mail = new Mailer();
940 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
941 $mail->subject($lang['regpwmail']);
942 $mail->setBody($text, $trep);
943 return $mail->send();
947 * Register a new user
949 * This registers a new user - Data is read directly from $_POST
951 * @return bool true on success, false on any error
954 * @author Andreas Gohr <andi@splitbrain.org>
960 /* @var AuthPlugin $auth */
964 if (!$INPUT->post
->bool('save')) return false;
965 if (!actionOK('register')) return false;
968 $login = trim($auth->cleanUser($INPUT->post
->str('login')));
969 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post
->str('fullname')));
970 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post
->str('email')));
971 $pass = $INPUT->post
->str('pass');
972 $passchk = $INPUT->post
->str('passchk');
974 if (empty($login) ||
empty($fullname) ||
empty($email)) {
975 msg($lang['regmissing'], -1);
979 if ($conf['autopasswd']) {
980 $pass = auth_pwgen($login); // automatically generate password
981 } elseif (empty($pass) ||
empty($passchk)) {
982 msg($lang['regmissing'], -1); // complain about missing passwords
984 } elseif ($pass != $passchk) {
985 msg($lang['regbadpass'], -1); // complain about misspelled passwords
990 if (!mail_isvalid($email)) {
991 msg($lang['regbadmail'], -1);
995 //okay try to create the user
996 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
997 msg($lang['regfail'], -1);
1001 // send notification about the new user
1002 $subscription = new RegistrationSubscriptionSender();
1003 $subscription->sendRegister($login, $fullname, $email);
1006 if (!$conf['autopasswd']) {
1007 msg($lang['regsuccess2'], 1);
1011 // autogenerated password? then send password to user
1012 if (auth_sendPassword($login, $pass)) {
1013 msg($lang['regsuccess'], 1);
1016 msg($lang['regmailfail'], -1);
1022 * Update user profile
1026 * @author Christopher Smith <chris@jalakai.co.uk>
1028 function updateprofile()
1032 /* @var AuthPlugin $auth */
1034 /* @var Input $INPUT */
1037 if (!$INPUT->post
->bool('save')) return false;
1038 if (!checkSecurityToken()) return false;
1040 if (!actionOK('profile')) {
1041 msg($lang['profna'], -1);
1046 $changes['pass'] = $INPUT->post
->str('newpass');
1047 $changes['name'] = $INPUT->post
->str('fullname');
1048 $changes['mail'] = $INPUT->post
->str('email');
1050 // check misspelled passwords
1051 if ($changes['pass'] != $INPUT->post
->str('passchk')) {
1052 msg($lang['regbadpass'], -1);
1056 // clean fullname and email
1057 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1058 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1060 // no empty name and email (except the backend doesn't support them)
1062 (empty($changes['name']) && $auth->canDo('modName')) ||
1063 (empty($changes['mail']) && $auth->canDo('modMail'))
1065 msg($lang['profnoempty'], -1);
1068 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1069 msg($lang['regbadmail'], -1);
1073 $changes = array_filter($changes);
1075 // check for unavailable capabilities
1076 if (!$auth->canDo('modName')) unset($changes['name']);
1077 if (!$auth->canDo('modMail')) unset($changes['mail']);
1078 if (!$auth->canDo('modPass')) unset($changes['pass']);
1081 if ($changes === []) {
1082 msg($lang['profnochange'], -1);
1086 if ($conf['profileconfirm']) {
1087 if (!$auth->checkPass($INPUT->server
->str('REMOTE_USER'), $INPUT->post
->str('oldpass'))) {
1088 msg($lang['badpassconfirm'], -1);
1093 if (!$auth->triggerUserMod('modify', [$INPUT->server
->str('REMOTE_USER'), &$changes])) {
1094 msg($lang['proffail'], -1);
1098 if ($changes['pass']) {
1099 // update cookie and session with the changed data
1100 [/* user */, $sticky, /* pass */] = auth_getCookie();
1101 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1102 auth_setCookie($INPUT->server
->str('REMOTE_USER'), $pass, (bool) $sticky);
1104 // make sure the session is writable
1106 // invalidate session cache
1107 $_SESSION[DOKU_COOKIE
]['auth']['time'] = 0;
1108 session_write_close();
1115 * Delete the current logged-in user
1117 * @return bool true on success, false on any error
1119 function auth_deleteprofile()
1123 /* @var AuthPlugin $auth */
1125 /* @var Input $INPUT */
1128 if (!$INPUT->post
->bool('delete')) return false;
1129 if (!checkSecurityToken()) return false;
1131 // action prevented or auth module disallows
1132 if (!actionOK('profile_delete') ||
!$auth->canDo('delUser')) {
1133 msg($lang['profnodelete'], -1);
1137 if (!$INPUT->post
->bool('confirm_delete')) {
1138 msg($lang['profconfdeletemissing'], -1);
1142 if ($conf['profileconfirm']) {
1143 if (!$auth->checkPass($INPUT->server
->str('REMOTE_USER'), $INPUT->post
->str('oldpass'))) {
1144 msg($lang['badpassconfirm'], -1);
1150 $deleted[] = $INPUT->server
->str('REMOTE_USER');
1151 if ($auth->triggerUserMod('delete', [$deleted])) {
1152 // force and immediate logout including removing the sticky cookie
1161 * Send a new password
1163 * This function handles both phases of the password reset:
1165 * - handling the first request of password reset
1166 * - validating the password reset auth token
1168 * @return bool true on success, false on any error
1171 * @author Andreas Gohr <andi@splitbrain.org>
1172 * @author Benoit Chesneau <benoit@bchesneau.info>
1173 * @author Chris Smith <chris@jalakai.co.uk>
1175 function act_resendpwd()
1179 /* @var AuthPlugin $auth */
1181 /* @var Input $INPUT */
1184 if (!actionOK('resendpwd')) {
1185 msg($lang['resendna'], -1);
1189 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1192 // we're in token phase - get user info from token
1194 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1195 if (!file_exists($tfile)) {
1196 msg($lang['resendpwdbadauth'], -1);
1197 $INPUT->remove('pwauth');
1200 // token is only valid for 3 days
1201 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1202 msg($lang['resendpwdbadauth'], -1);
1203 $INPUT->remove('pwauth');
1208 $user = io_readfile($tfile);
1209 $userinfo = $auth->getUserData($user, false);
1210 if (!$userinfo['mail']) {
1211 msg($lang['resendpwdnouser'], -1);
1215 if (!$conf['autopasswd']) { // we let the user choose a password
1216 $pass = $INPUT->str('pass');
1218 // password given correctly?
1219 if (!$pass) return false;
1220 if ($pass != $INPUT->str('passchk')) {
1221 msg($lang['regbadpass'], -1);
1226 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1227 msg($lang['proffail'], -1);
1230 } else { // autogenerate the password and send by mail
1231 $pass = auth_pwgen($user);
1232 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1233 msg($lang['proffail'], -1);
1237 if (auth_sendPassword($user, $pass)) {
1238 msg($lang['resendpwdsuccess'], 1);
1240 msg($lang['regmailfail'], -1);
1247 // we're in request phase
1249 if (!$INPUT->post
->bool('save')) return false;
1251 if (!$INPUT->post
->str('login')) {
1252 msg($lang['resendpwdmissing'], -1);
1255 $user = trim($auth->cleanUser($INPUT->post
->str('login')));
1258 $userinfo = $auth->getUserData($user, false);
1259 if (!$userinfo['mail']) {
1260 msg($lang['resendpwdnouser'], -1);
1264 // generate auth token
1265 $token = md5(auth_randombytes(16)); // random secret
1266 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1267 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1269 io_saveFile($tfile, $user);
1271 $text = rawLocale('pwconfirm');
1272 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
1274 $mail = new Mailer();
1275 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1276 $mail->subject($lang['regpwmail']);
1277 $mail->setBody($text, $trep);
1278 if ($mail->send()) {
1279 msg($lang['resendpwdconfirm'], 1);
1281 msg($lang['regmailfail'], -1);
1289 * Encrypts a password using the given method and salt
1291 * If the selected method needs a salt and none was given, a random one
1294 * @author Andreas Gohr <andi@splitbrain.org>
1296 * @param string $clear The clear text password
1297 * @param string $method The hashing method
1298 * @param string $salt A salt, null for random
1299 * @return string The crypted password
1301 function auth_cryptPassword($clear, $method = '', $salt = null)
1304 if (empty($method)) $method = $conf['passcrypt'];
1306 $pass = new PassHash();
1307 $call = 'hash_' . $method;
1309 if (!method_exists($pass, $call)) {
1310 msg("Unsupported crypt method $method", -1);
1314 return $pass->$call($clear, $salt);
1318 * Verifies a cleartext password against a crypted hash
1320 * @param string $clear The clear text password
1321 * @param string $crypt The hash to compare with
1322 * @return bool true if both match
1325 * @author Andreas Gohr <andi@splitbrain.org>
1327 function auth_verifyPassword($clear, $crypt)
1329 $pass = new PassHash();
1330 return $pass->verify_hash($clear, $crypt);
1334 * Set the authentication cookie and add user identification data to the session
1336 * @param string $user username
1337 * @param string $pass encrypted password
1338 * @param bool $sticky whether or not the cookie will last beyond the session
1341 function auth_setCookie($user, $pass, $sticky)
1344 /* @var AuthPlugin $auth */
1348 if (!$auth instanceof AuthPlugin
) return false;
1349 $USERINFO = $auth->getUserData($user);
1352 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1353 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL
: $conf['cookiedir'];
1354 $time = $sticky ?
(time() +
60 * 60 * 24 * 365) : 0; //one year
1355 setcookie(DOKU_COOKIE
, $cookie, [
1357 'path' => $cookieDir,
1358 'secure' => ($conf['securecookie'] && is_ssl()),
1360 'samesite' => $conf['samesitecookie'] ?
: null, // null means browser default
1364 $_SESSION[DOKU_COOKIE
]['auth']['user'] = $user;
1365 $_SESSION[DOKU_COOKIE
]['auth']['pass'] = sha1($pass);
1366 $_SESSION[DOKU_COOKIE
]['auth']['buid'] = auth_browseruid();
1367 $_SESSION[DOKU_COOKIE
]['auth']['info'] = $USERINFO;
1368 $_SESSION[DOKU_COOKIE
]['auth']['time'] = time();
1374 * Returns the user, (encrypted) password and sticky bit from cookie
1378 function auth_getCookie()
1380 if (!isset($_COOKIE[DOKU_COOKIE
])) {
1381 return [null, null, null];
1383 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE
], 3, '');
1384 $sticky = (bool) $sticky;
1385 $pass = base64_decode($pass);
1386 $user = base64_decode($user);
1387 return [$user, $sticky, $pass];
1390 //Setup VIM: ex: et ts=2 :