3 namespace wcf\system\session
;
5 use ParagonIE\ConstantTime\Hex
;
6 use wcf\data\session\Session
as LegacySession
;
7 use wcf\data\session\SessionEditor
;
8 use wcf\data\user\User
;
9 use wcf\data\user\UserEditor
;
10 use wcf\system\application\ApplicationHandler
;
11 use wcf\system\cache\builder\SpiderCacheBuilder
;
12 use wcf\system\cache\builder\UserGroupOptionCacheBuilder
;
13 use wcf\system\cache\builder\UserGroupPermissionCacheBuilder
;
14 use wcf\system\database\DatabaseException
;
15 use wcf\system\database\util\PreparedStatementConditionBuilder
;
16 use wcf\system\event\EventHandler
;
17 use wcf\system\exception\PermissionDeniedException
;
18 use wcf\system\page\PageLocationManager
;
19 use wcf\system\request\RouteHandler
;
20 use wcf\system\SingletonFactory
;
21 use wcf\system\user\storage\UserStorageHandler
;
23 use wcf\system\WCFACP
;
24 use wcf\util\CryptoUtil
;
25 use wcf\util\HeaderUtil
;
26 use wcf\util\UserUtil
;
31 * @author Tim Duesterhus, Alexander Ebert
32 * @copyright 2001-2020 WoltLab GmbH
33 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
34 * @package WoltLabSuite\Core\System\Session
36 * @property-read string $sessionID unique textual identifier of the session
37 * @property-read int|null $userID id of the user the session belongs to or `null` if the session belongs to a guest
38 * @property-read int|null $pageID id of the latest page visited
39 * @property-read int|null $pageObjectID id of the object the latest page visited belongs to
40 * @property-read int|null $parentPageID id of the parent page of latest page visited
41 * @property-read int|null $parentPageObjectID id of the object the parent page of latest page visited belongs to
42 * @property-read int $spiderID id of the spider the session belongs to
44 final class SessionHandler
extends SingletonFactory
47 * prevents update on shutdown
50 protected $doNotUpdate = false;
53 * disables page tracking
56 protected $disableTracking = false;
59 * group data and permissions
65 * true if within ACP or WCFSetup
68 protected $isACP = false;
71 * language id for active user
74 protected $languageID = 0;
77 * language ids for active user
80 protected $languageIDs;
90 protected $legacySession;
108 protected $variables = [];
111 * indicates if session variables changed and must be saved upon shutdown
114 protected $variablesChanged = false;
117 * true if this is a new session
120 protected $firstVisit = false;
123 * list of names of permissions only available for users
126 protected $usersOnlyPermissions = [];
133 private const GUEST_SESSION_LIFETIME
= 2 * 3600;
135 private const USER_SESSION_LIFETIME
= 60 * 86400;
137 private const USER_SESSION_LIMIT
= 30;
139 private const CHANGE_USER_AFTER_MULTIFACTOR_KEY
= self
::class . "\0__changeUserAfterMultifactor__";
141 private const PENDING_USER_LIFETIME
= 15 * 60;
143 private const REAUTHENTICATION_KEY
= self
::class . "\0__reauthentication__";
145 private const REAUTHENTICATION_HARD_LIMIT
= 12 * 3600;
147 private const REAUTHENTICATION_SOFT_LIMIT
= 2 * 3600;
149 private const REAUTHENTICATION_SOFT_LIMIT_ACP
= 2 * 3600;
151 private const REAUTHENTICATION_GRACE_PERIOD
= 15 * 60;
154 * Provides access to session data.
159 public function __get($key)
163 return $this->sessionID
;
165 return $this->user
->userID
;
167 return $this->getSpiderID(UserUtil
::getUserAgent());
171 case 'parentPageObjectID':
172 return $this->legacySession
->{$key};
174 /** @deprecated 5.4 - The below values are deprecated. */
176 return UserUtil
::getIpAddress();
178 return UserUtil
::getUserAgent();
180 return UserUtil
::getRequestURI();
181 case 'requestMethod':
182 return !empty($_SERVER['REQUEST_METHOD']) ? \
substr($_SERVER['REQUEST_METHOD'], 0, 7) : '';
183 case 'lastActivityTime':
194 protected function init()
196 $this->isACP
= (\
class_exists(WCFACP
::class, false) ||
!PACKAGE_ID
);
197 $this->usersOnlyPermissions
= UserGroupOptionCacheBuilder
::getInstance()->getData([], 'usersOnlyOptions');
201 * @deprecated 5.4 - This method is a noop. The cookie suffix is determined automatically.
203 public function setCookieSuffix()
208 * @deprecated 5.4 - This method is a noop. Cookie handling works automatically.
210 public function setHasValidCookie($hasValidCookie)
215 * Parses the session cookie value, returning an array with the stored fields.
217 * The return array is guaranteed to have a `sessionId` key.
219 private function parseCookie(string $value): array
221 $length = \
mb_strlen($value, '8bit');
223 throw new \
InvalidArgumentException(\
sprintf(
224 'Expected at least 1 Byte, %d given.',
229 $version = \
unpack('Cversion', $value)['version'];
230 if (!\
in_array($version, [1], true)) {
231 throw new \
InvalidArgumentException(\
sprintf(
232 'Unknown version %d',
237 if ($version === 1) {
238 if ($length !== 22) {
239 throw new \
InvalidArgumentException(\
sprintf(
240 'Expected exactly 22 Bytes, %d given.',
244 $data = \
unpack('Cversion/A20sessionId/Ctimestep', $value);
245 $data['sessionId'] = Hex
::encode($data['sessionId']);
250 throw new \
LogicException('Unreachable');
254 * Extracts the data from the session cookie.
256 * @see SessionHandler::parseCookie()
259 private function getParsedCookieData(): ?
array
261 $cookieName = COOKIE_PREFIX
. "user_session";
263 if (!empty($_COOKIE[$cookieName])) {
266 'sessionId' => $_COOKIE[$cookieName],
270 $cookieData = CryptoUtil
::getValueFromSignedString($_COOKIE[$cookieName]);
272 // Check whether the sessionId was correctly signed.
278 return $this->parseCookie($cookieData);
279 } catch (\InvalidArgumentException
$e) {
288 * Returns the session ID stored in the session cookie or `null`.
290 private function getSessionIdFromCookie(): ?
string
292 $cookieData = $this->getParsedCookieData();
295 return $cookieData['sessionId'];
302 * Returns the current time step. The time step changes
305 private function getCookieTimestep(): int
307 $window = (24 * 3600);
309 \assert
((self
::USER_SESSION_LIFETIME
/ $window) < 0xFF);
311 return \floor
(TIME_NOW
/ $window) & 0xFF;
315 * Returns the signed session data for use in a cookie.
317 private function getCookieValue(): string
320 return $this->sessionID
;
323 return CryptoUtil
::createSignedString(\
pack(
326 Hex
::decode($this->sessionID
),
327 $this->getCookieTimestep()
332 * Returns true if client provided a valid session cookie.
337 public function hasValidCookie(): bool
339 return $this->getSessionIdFromCookie() === $this->sessionID
;
343 * @deprecated 5.4 - Sessions are managed automatically. Use loadFromCookie().
345 public function load($sessionEditorClassName, $sessionID)
348 if (!empty($sessionID)) {
349 $hasSession = $this->getExistingSession($sessionID);
358 * Loads the session matching the session cookie.
360 public function loadFromCookie()
362 $sessionID = $this->getSessionIdFromCookie();
366 $hasSession = $this->getExistingSession($sessionID);
370 $this->maybeRefreshCookie();
377 * Refreshes the session cookie, extending the expiry.
379 private function maybeRefreshCookie(): void
381 // Guests use short-lived sessions with an actual session cookie.
382 if (!$this->user
->userID
) {
386 $cookieData = $this->getParsedCookieData();
388 // No refresh is needed if the timestep matches up.
389 if (isset($cookieData['timestep']) && $cookieData['timestep'] === $this->getCookieTimestep()) {
393 // Refresh the cookie.
394 HeaderUtil
::setCookie(
396 $this->getCookieValue(),
397 TIME_NOW +
(self
::USER_SESSION_LIFETIME
* 2)
402 * Initializes session system.
404 public function initSession()
406 $this->defineConstants();
408 // assign language and style id
409 $this->languageID
= $this->getVar('languageID') ?
: $this->user
->languageID
;
410 $this->styleID
= $this->getVar('styleID') ?
: $this->user
->styleID
;
412 // https://github.com/WoltLab/WCF/issues/2568
413 if ($this->getVar('__wcfIsFirstVisit') === true) {
414 $this->firstVisit
= true;
415 $this->unregister('__wcfIsFirstVisit');
420 * Disables update on shutdown.
422 public function disableUpdate()
424 $this->doNotUpdate
= true;
428 * Disables page tracking.
430 public function disableTracking()
432 $this->disableTracking
= true;
436 * Defines global wcf constants related to session.
438 protected function defineConstants()
441 if (!\
defined('SECURITY_TOKEN')) {
442 \
define('SECURITY_TOKEN', $this->getSecurityToken());
444 if (!\
defined('SECURITY_TOKEN_INPUT_TAG')) {
446 'SECURITY_TOKEN_INPUT_TAG',
447 '<input type="hidden" name="t" value="' . $this->getSecurityToken() . '">'
453 * Initializes security token.
455 protected function initSecurityToken()
458 if (!empty($_COOKIE['XSRF-TOKEN'])) {
459 // We intentionally do not extract the signed value and instead just verify the correctness.
461 // The reason is that common JavaScript frameworks can use the contents of the `XSRF-TOKEN` cookie as-is,
462 // without performing any processing on it, improving interoperability. Leveraging this JavaScript framework
463 // feature requires the author of the controller to check the value within the `X-XSRF-TOKEN` request header
464 // instead of the WoltLab Suite specific `t` parameter, though.
466 // The only reason we sign the cookie is that an XSS vulnerability or a rogue application on a subdomain
467 // is not able to create a valid `XSRF-TOKEN`, e.g. by setting the `XSRF-TOKEN` cookie to the static
468 // value `1234`, possibly allowing later exploitation.
469 if (!PACKAGE_ID || CryptoUtil
::validateSignedString($_COOKIE['XSRF-TOKEN'])) {
470 $xsrfToken = $_COOKIE['XSRF-TOKEN'];
476 $xsrfToken = CryptoUtil
::createSignedString(\random_bytes
(16));
478 $xsrfToken = Hex
::encode(\random_bytes
(16));
481 // We construct the cookie manually instead of using HeaderUtil::setCookie(), because:
482 // 1) We don't want the prefix. The `XSRF-TOKEN` cookie name is a standard name across applications
483 // and it is supported by default in common JavaScript frameworks.
484 // 2) We want to set the SameSite=strict parameter.
485 // 3) We don't want the HttpOnly parameter.
486 $sameSite = $cookieDomain = '';
488 if (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
489 // We need to specify the cookieDomain in a multi domain set-up, because
490 // otherwise no cookies are sent to subdomains.
491 $cookieDomain = HeaderUtil
::getCookieDomain();
492 $cookieDomain = ($cookieDomain !== null ?
'; domain=' . $cookieDomain : '');
494 // SameSite=strict is not supported in a multi domain set-up, because
495 // it breaks cross-application requests.
496 $sameSite = '; SameSite=strict';
500 'set-cookie: XSRF-TOKEN=' . \rawurlencode
($xsrfToken) . '; path=/' . $cookieDomain . (RouteHandler
::secureConnection() ?
'; secure' : '') . $sameSite,
505 $this->xsrfToken
= $xsrfToken;
509 * Returns security token.
513 public function getSecurityToken()
515 if ($this->xsrfToken
=== null) {
516 $this->initSecurityToken();
519 return $this->xsrfToken
;
523 * Validates the given security token, returns false if
524 * given token is invalid.
526 * @param string $token
529 public function checkSecurityToken($token)
531 // The output of CryptoUtil::createSignedString() is not url-safe. For compatibility
532 // reasons the SECURITY_TOKEN in URLs might not be encoded, turning the '+' into a space.
533 // Convert it back before comparing.
534 $token = \
str_replace(' ', '+', $token);
536 return \
hash_equals($this->getSecurityToken(), $token);
540 * Registers a session variable.
543 * @param mixed $value
545 public function register($key, $value)
547 $scope = $this->isACP ?
'acp' : 'frontend';
549 $this->variables
[$scope][$key] = $value;
550 $this->variablesChanged
= true;
554 * Unsets a session variable.
558 public function unregister($key)
560 $scope = $this->isACP ?
'acp' : 'frontend';
562 unset($this->variables
[$scope][$key]);
563 $this->variablesChanged
= true;
567 * Returns the value of a session variable or `null` if the session
568 * variable does not exist.
573 public function getVar($key)
575 $scope = $this->isACP ?
'acp' : 'frontend';
577 if (isset($this->variables
[$scope][$key])) {
578 return $this->variables
[$scope][$key];
583 * Returns the user object of this session.
587 public function getUser()
593 * Tries to read existing session identified by the given session id. Returns whether
594 * a session could be found.
596 protected function getExistingSession(string $sessionID): bool
599 FROM wcf" . WCF_N
. "_user_session
600 WHERE sessionID = ?";
601 $statement = WCF
::getDB()->prepareStatement($sql);
602 $statement->execute([
605 $row = $statement->fetchSingleRow();
611 // Check whether the session technically already expired.
612 $lifetime = ($row['userID'] ? self
::USER_SESSION_LIFETIME
: self
::GUEST_SESSION_LIFETIME
);
613 if ($row['lastActivityTime'] < (TIME_NOW
- $lifetime)) {
617 $variables = @\
unserialize($row['sessionVariables']);
618 // Check whether the session variables became corrupted.
619 if (!\
is_array($variables)) {
623 $this->sessionID
= $sessionID;
624 $this->user
= new User($row['userID']);
625 $this->variables
= $variables;
627 $sql = "UPDATE wcf" . WCF_N
. "_user_session
631 WHERE sessionID = ?";
632 $statement = WCF
::getDB()->prepareStatement($sql);
633 $statement->execute([
634 UserUtil
::getIpAddress(),
635 UserUtil
::getUserAgent(),
640 // Fetch legacy session.
641 $condition = new PreparedStatementConditionBuilder();
643 if ($row['userID']) {
644 // The `userID IS NOT NULL` condition technically is redundant, but is added for
645 // clarity and consistency with the guest case below.
646 $condition->add('userID IS NOT NULL');
647 $condition->add('userID = ?', [$row['userID']]);
649 $condition->add('userID IS NULL');
650 $condition->add('(sessionID = ? OR spiderID = ?)', [
652 $this->getSpiderID(UserUtil
::getUserAgent()),
657 FROM wcf" . WCF_N
. "_session
659 $statement = WCF
::getDB()->prepareStatement($sql);
660 $statement->execute($condition->getParameters());
661 $this->legacySession
= $statement->fetchSingleObject(LegacySession
::class);
663 if (!$this->legacySession
) {
664 $this->legacySession
= $this->createLegacySession();
671 * Creates a new session.
673 protected function create()
675 $this->sessionID
= Hex
::encode(\random_bytes
(20));
682 // Create new session.
683 $sql = "INSERT INTO wcf" . WCF_N
. "_user_session
684 (sessionID, ipAddress, userAgent, creationTime, lastActivityTime, sessionVariables)
685 VALUES (?, ?, ?, ?, ?, ?)";
686 $statement = WCF
::getDB()->prepareStatement($sql);
687 $statement->execute([
689 UserUtil
::getIpAddress(),
690 UserUtil
::getUserAgent(),
693 \
serialize($variables),
696 $this->variables
= $variables;
697 $this->user
= new User(null);
698 $this->firstVisit
= true;
700 HeaderUtil
::setCookie(
702 $this->getCookieValue()
705 // Maintain legacy session table for users online list.
706 $this->legacySession
= null;
708 // Try to find an existing spider session. Order by lastActivityTime to maintain a
709 // stable selection in case duplicates exist for some reason.
710 $spiderID = $this->getSpiderID(UserUtil
::getUserAgent());
713 FROM wcf" . WCF_N
. "_session
716 ORDER BY lastActivityTime DESC";
717 $statement = WCF
::getDB()->prepareStatement($sql);
718 $statement->execute([$spiderID]);
719 $this->legacySession
= $statement->fetchSingleObject(LegacySession
::class);
722 if (!$this->legacySession
) {
723 $this->legacySession
= $this->createLegacySession();
727 private function createLegacySession(): LegacySession
730 if (!$this->user
->userID
) {
731 $spiderID = $this->getSpiderID(UserUtil
::getUserAgent());
736 'sessionID' => $this->sessionID
,
737 'userID' => $this->user
->userID
,
738 'ipAddress' => UserUtil
::getIpAddress(),
739 'userAgent' => UserUtil
::getUserAgent(),
740 'lastActivityTime' => TIME_NOW
,
741 'requestURI' => UserUtil
::getRequestURI(),
742 'requestMethod' => !empty($_SERVER['REQUEST_METHOD']) ? \
substr($_SERVER['REQUEST_METHOD'], 0, 7) : '',
743 'spiderID' => $spiderID,
746 return SessionEditor
::create($sessionData);
750 * Returns the value of the permission with the given name.
752 * @param string $permission
753 * @return mixed permission value
755 public function getPermission($permission)
757 // check if a users only permission is checked for a guest and return
758 // false if that is the case
759 if (!$this->user
->userID
&& \
in_array($permission, $this->usersOnlyPermissions
)) {
763 $this->loadGroupData();
765 if (!isset($this->groupData
[$permission])) {
769 return $this->groupData
[$permission];
773 * Returns true if a permission was set to 'Never'. This is required to preserve
774 * compatibility, while preventing ACLs from overruling a 'Never' setting.
776 * @param string $permission
779 public function getNeverPermission($permission)
781 $this->loadGroupData();
783 return isset($this->groupData
['__never'][$permission]);
787 * Checks if the active user has the given permissions and throws a
788 * PermissionDeniedException if that isn't the case.
790 * @param string[] $permissions list of permissions where each one must pass
791 * @throws PermissionDeniedException
793 public function checkPermissions(array $permissions)
795 foreach ($permissions as $permission) {
796 if (!$this->getPermission($permission)) {
797 throw new PermissionDeniedException();
803 * Loads group data from cache.
805 protected function loadGroupData()
807 if ($this->groupData
!== null) {
811 // work-around for setup process (package wcf does not exist yet)
813 $sql = "SELECT groupID
814 FROM wcf" . WCF_N
. "_user_to_group
816 $statement = WCF
::getDB()->prepareStatement($sql);
817 $statement->execute([$this->user
->userID
]);
818 $groupIDs = $statement->fetchAll(\PDO
::FETCH_COLUMN
);
820 $groupIDs = $this->user
->getGroupIDs();
823 // get group data from cache
824 $this->groupData
= UserGroupPermissionCacheBuilder
::getInstance()->getData($groupIDs);
825 if (isset($this->groupData
['groupIDs']) && $this->groupData
['groupIDs'] != $groupIDs) {
826 $this->groupData
= [];
831 * Returns language ids for active user.
835 public function getLanguageIDs()
837 $this->loadLanguageIDs();
839 return $this->languageIDs
;
843 * Loads language ids for active user.
845 protected function loadLanguageIDs()
847 if ($this->languageIDs
!== null) {
851 $this->languageIDs
= [];
853 if (!$this->user
->userID
) {
857 // work-around for setup process (package wcf does not exist yet)
859 $sql = "SELECT languageID
860 FROM wcf" . WCF_N
. "_user_to_language
862 $statement = WCF
::getDB()->prepareStatement($sql);
863 $statement->execute([$this->user
->userID
]);
864 $this->languageIDs
= $statement->fetchAll(\PDO
::FETCH_COLUMN
);
866 $this->languageIDs
= $this->user
->getLanguageIDs();
871 * If multi-factor authentication is enabled for the given user then
872 * - the userID will be stored in the session variables, and
873 * - `true` is returned.
875 * - `changeUser()` will be called, and
876 * - `false` is returned.
878 * If `true` is returned you should perform a redirect to `MultifactorAuthenticationForm`.
882 public function changeUserAfterMultifactorAuthentication(User
$user): bool
884 if ($user->multifactorActive
) {
885 $this->register(self
::CHANGE_USER_AFTER_MULTIFACTOR_KEY
, [
886 'userId' => $user->userID
,
887 'expires' => TIME_NOW + self
::PENDING_USER_LIFETIME
,
889 $this->setLanguageID($user->languageID
);
893 $this->changeUser($user);
900 * Applies the pending user change, calling `changeUser()` for the user returned
901 * by `getPendingUserChange()`.
903 * As a safety check you must provide the `$expectedUser` as a parameter, it must match the
904 * data stored within the session.
906 * @throws \RuntimeException If the `$expectedUser` does not match.
907 * @throws \BadMethodCallException If `getPendingUserChange()` returns `null`.
908 * @see SessionHandler::getPendingUserChange()
911 public function applyPendingUserChange(User
$expectedUser): void
913 $user = $this->getPendingUserChange();
914 $this->clearPendingUserChange();
916 if ($user->userID
!== $expectedUser->userID
) {
917 throw new \
RuntimeException('Mismatching expectedUser.');
921 throw new \
BadMethodCallException('No pending user change.');
924 $this->changeUser($user);
928 * Returns the pending user change initiated by `changeUserAfterMultifactorAuthentication()`.
930 * @see SessionHandler::changeUserAfterMultifactorAuthentication()
933 public function getPendingUserChange(): ?User
935 $data = $this->getVar(self
::CHANGE_USER_AFTER_MULTIFACTOR_KEY
);
940 $userId = $data['userId'];
941 $expires = $data['expires'];
943 if ($expires < TIME_NOW
) {
947 $user = new User($userId);
949 if (!$user->userID
) {
957 * Clears a pending user change, reverses the effects of `changeUserAfterMultifactorAuthentication()`.
959 * @see SessionHandler::changeUserAfterMultifactorAuthentication()
962 public function clearPendingUserChange(): void
964 $this->unregister(self
::CHANGE_USER_AFTER_MULTIFACTOR_KEY
);
968 * Stores a new user object in this session, e.g. a user was guest because not
969 * logged in, after the login his old session is used to store his full data.
972 * @param bool $hideSession if true, database won't be updated
974 public function changeUser(User
$user, $hideSession = false)
976 $eventParameters = ['user' => $user, 'hideSession' => $hideSession];
978 EventHandler
::getInstance()->fireAction($this, 'beforeChangeUser', $eventParameters);
980 $user = $eventParameters['user'];
981 $hideSession = $eventParameters['hideSession'];
983 // skip changeUserVirtual, if session will not be persistent anyway
985 $this->changeUserVirtual($user);
988 // update user reference
992 $this->groupData
= null;
993 $this->languageIDs
= null;
994 $this->languageID
= $this->user
->languageID
;
995 $this->styleID
= $this->user
->styleID
;
998 WCF
::setLanguage($this->languageID ?
: 0);
1000 // in some cases the language id can be stuck in the session variables
1001 $this->unregister('languageID');
1003 EventHandler
::getInstance()->fireAction($this, 'afterChangeUser');
1007 * Changes the user stored in the session.
1010 * @throws DatabaseException
1012 protected function changeUserVirtual(User
$user)
1014 // We must delete the old session to not carry over any state across different users.
1017 // If the target user is a registered user ...
1018 if ($user->userID
) {
1019 // ... we create a new session with a new session ID ...
1022 // ... delete the newly created legacy session ...
1023 $sql = "DELETE FROM wcf" . WCF_N
. "_session
1024 WHERE sessionID = ?";
1025 $statement = WCF
::getDB()->prepareStatement($sql);
1026 $statement->execute([$this->sessionID
]);
1028 // ... perform the login ...
1029 $sql = "UPDATE wcf" . WCF_N
. "_user_session
1031 WHERE sessionID = ?";
1032 $statement = WCF
::getDB()->prepareStatement($sql);
1033 $statement->execute([
1038 // ... delete any user sessions exceeding the limit ...
1039 $sql = "SELECT all_sessions.sessionID
1040 FROM wcf" . WCF_N
. "_user_session all_sessions
1043 FROM wcf" . WCF_N
. "_user_session
1045 ORDER BY lastActivityTime DESC
1046 LIMIT " . self
::USER_SESSION_LIMIT
. "
1048 ON newest_sessions.sessionID = all_sessions.sessionID
1049 WHERE all_sessions.userID = ?
1050 AND newest_sessions.sessionID IS NULL";
1051 $statement = WCF
::getDB()->prepareStatement($sql);
1052 $statement->execute([
1056 foreach ($statement->fetchAll(\PDO
::FETCH_COLUMN
) as $sessionID) {
1057 $this->deleteUserSession($sessionID);
1060 // ... and reload the session with the updated information.
1061 $hasSession = $this->getExistingSession($this->sessionID
);
1064 throw new \
LogicException('Unreachable');
1070 * Checks whether the user needs to authenticate themselves once again
1071 * to access a security critical area.
1073 * If `true` is returned you should perform a redirect to `ReAuthenticationForm`,
1074 * otherwise the user is sufficiently authenticated and may proceed.
1076 * @throws \BadMethodCallException If the current user is a guest.
1079 public function needsReauthentication(): bool
1081 if (!$this->getUser()->userID
) {
1082 throw new \
BadMethodCallException('The current user is a guest.');
1085 // Reauthentication for third party authentication is not supported.
1086 if ($this->getUser()->authData
) {
1090 $data = $this->getVar(self
::REAUTHENTICATION_KEY
);
1092 // Request a new authentication if no stored information is available.
1097 $lastAuthentication = $data['lastAuthentication'];
1098 $lastCheck = $data['lastCheck'];
1100 // Request a new authentication if the hard limit since the last authentication
1102 if ($lastAuthentication < (TIME_NOW
- self
::REAUTHENTICATION_HARD_LIMIT
)) {
1106 $softLimit = self
::REAUTHENTICATION_SOFT_LIMIT
;
1108 $softLimit = self
::REAUTHENTICATION_SOFT_LIMIT_ACP
;
1110 // If both the debug mode and the developer tools are enabled the
1111 // reauthentication soft limit within the ACP matches the hard limit.
1113 // This allows for a continous access to the ACP and specifically the
1114 // developer tools within a single workday without needing to re-login
1115 // just because one spent 15 minutes within the IDE.
1116 if (ENABLE_DEBUG_MODE
&& ENABLE_DEVELOPER_TOOLS
) {
1117 $softLimit = self
::REAUTHENTICATION_HARD_LIMIT
;
1121 // Request a new authentication if the soft limit since the last authentication
1123 if ($lastAuthentication < (TIME_NOW
- $softLimit)) {
1124 // ... and the grace period since the last check is also exceeded.
1125 if ($lastCheck < (TIME_NOW
- self
::REAUTHENTICATION_GRACE_PERIOD
)) {
1130 // If we reach this point we determined that a new authentication is not necessary.
1132 ($lastAuthentication >= TIME_NOW
- $softLimit)
1133 ||
($lastAuthentication >= TIME_NOW
- self
::REAUTHENTICATION_HARD_LIMIT
1134 && $lastCheck >= TIME_NOW
- self
::REAUTHENTICATION_GRACE_PERIOD
)
1137 // Update the lastCheck timestamp to make sure that the grace period works properly.
1139 // The grace period allows the user to complete their action if the soft limit
1140 // expires between loading a form and actually submitting that form, provided that
1141 // the user does not take longer than the grace period to fill in the form.
1142 $data['lastCheck'] = TIME_NOW
;
1143 $this->register(self
::REAUTHENTICATION_KEY
, $data);
1149 * Registers that the user performed reauthentication successfully.
1151 * This method should be considered to be semi-public and is intended to be used
1152 * by `ReAuthenticationForm` only.
1154 * @throws \BadMethodCallException If the current user is a guest.
1155 * @see SessionHandler::needsReauthentication()
1158 public function registerReauthentication(): void
1160 if (!$this->getUser()->userID
) {
1161 throw new \
BadMethodCallException('The current user is a guest.');
1164 $this->register(self
::REAUTHENTICATION_KEY
, [
1165 'lastAuthentication' => TIME_NOW
,
1166 'lastCheck' => TIME_NOW
,
1171 * Clears that the user performed reauthentication successfully.
1173 * After this method is called `needsReauthentication()` will return true until
1174 * `registerReauthentication()` is called again.
1176 * @throws \BadMethodCallException If the current user is a guest.
1177 * @see SessionHandler::needsReauthentication()
1178 * @see SessionHandler::registerReauthentication()
1181 public function clearReauthentication(): void
1183 if (!$this->getUser()->userID
) {
1184 throw new \
BadMethodCallException('The current user is a guest.');
1187 $this->unregister(self
::REAUTHENTICATION_KEY
);
1191 * Updates user session on shutdown.
1193 public function update()
1195 if ($this->doNotUpdate
) {
1199 if ($this->variablesChanged
) {
1200 $sql = "UPDATE wcf" . WCF_N
. "_user_session
1201 SET sessionVariables = ?
1202 WHERE sessionID = ?";
1203 $statement = WCF
::getDB()->prepareStatement($sql);
1204 $statement->execute([
1205 \
serialize($this->variables
),
1209 // Reset the flag, because the variables are no longer dirty.
1210 $this->variablesChanged
= false;
1214 'ipAddress' => UserUtil
::getIpAddress(),
1215 'userAgent' => $this->userAgent
,
1216 'requestURI' => $this->requestURI
,
1217 'requestMethod' => $this->requestMethod
,
1218 'lastActivityTime' => TIME_NOW
,
1219 'userID' => $this->user
->userID
,
1220 'sessionID' => $this->sessionID
,
1222 if (!\
class_exists('wcf\system\CLIWCF', false) && !$this->disableTracking
) {
1223 $pageLocations = PageLocationManager
::getInstance()->getLocations();
1224 if (isset($pageLocations[0])) {
1225 $data['pageID'] = $pageLocations[0]['pageID'];
1226 $data['pageObjectID'] = ($pageLocations[0]['pageObjectID'] ?
: null);
1227 $data['parentPageID'] = null;
1228 $data['parentPageObjectID'] = null;
1230 for ($i = 1, $length = \
count($pageLocations); $i < $length; $i++
) {
1231 if (!empty($pageLocations[$i]['useAsParentLocation'])) {
1232 $data['parentPageID'] = $pageLocations[$i]['pageID'];
1233 $data['parentPageObjectID'] = ($pageLocations[$i]['pageObjectID'] ?
: null);
1240 if ($this->legacySession
) {
1241 $sessionEditor = new SessionEditor($this->legacySession
);
1242 $sessionEditor->update($data);
1247 * @deprecated 5.4 - This method is a noop. The lastActivityTime is always updated immediately after loading.
1249 public function keepAlive()
1254 * Deletes this session and its related data.
1256 public function delete()
1259 if ($this->user
->userID
) {
1260 self
::resetSessions([$this->user
->userID
]);
1262 // update last activity time
1263 $editor = new UserEditor($this->user
);
1264 $editor->update(['lastActivityTime' => TIME_NOW
]);
1267 $this->deleteUserSession($this->sessionID
);
1271 * Prunes expired sessions.
1273 public function prune()
1275 $sql = "DELETE FROM wcf" . WCF_N
. "_user_session
1276 WHERE (lastActivityTime < ? AND userID IS NULL)
1277 OR (lastActivityTime < ? AND userID IS NOT NULL)";
1278 $statement = WCF
::getDB()->prepareStatement($sql);
1279 $statement->execute([
1280 TIME_NOW
- self
::GUEST_SESSION_LIFETIME
,
1281 TIME_NOW
- self
::USER_SESSION_LIFETIME
,
1284 // Legacy sessions live 120 minutes, they will be re-created on demand.
1285 $sql = "DELETE FROM wcf" . WCF_N
. "_session
1286 WHERE lastActivityTime < ?";
1287 $statement = WCF
::getDB()->prepareStatement($sql);
1288 $statement->execute([
1289 TIME_NOW
- (3600 * 2),
1294 * Deletes this session if:
1295 * - it is newly created in this request, and
1296 * - it belongs to a guest.
1298 * This method is useful if you have controllers that are likely to be
1299 * accessed by a user agent that is not going to re-use sessions (e.g.
1300 * curl in a cronjob). It immediately remove the session that was created
1301 * just for that request and that is not going to be used ever again.
1305 public function deleteIfNew()
1307 if ($this->isFirstVisit() && !$this->getUser()->userID
) {
1313 * Returns currently active language id.
1317 public function getLanguageID()
1319 return $this->languageID
;
1323 * Sets the currently active language id.
1325 * @param int $languageID
1327 public function setLanguageID($languageID)
1329 $this->languageID
= $languageID;
1330 $this->register('languageID', $this->languageID
);
1334 * Returns currently active style id.
1338 public function getStyleID()
1340 return $this->styleID
;
1344 * Sets the currently active style id.
1346 * @param int $styleID
1348 public function setStyleID($styleID)
1350 $this->styleID
= $styleID;
1351 $this->register('styleID', $this->styleID
);
1355 * Resets session-specific storage data.
1357 * @param int[] $userIDs
1359 public static function resetSessions(array $userIDs = [])
1361 if (!empty($userIDs)) {
1362 UserStorageHandler
::getInstance()->reset($userIDs, 'groupIDs');
1363 UserStorageHandler
::getInstance()->reset($userIDs, 'languageIDs');
1365 UserStorageHandler
::getInstance()->resetAll('groupIDs');
1366 UserStorageHandler
::getInstance()->resetAll('languageIDs');
1371 * Returns the spider id for given user agent.
1373 protected function getSpiderID(string $userAgent): ?
int
1375 $spiderList = SpiderCacheBuilder
::getInstance()->getData();
1376 $userAgent = \
strtolower($userAgent);
1378 foreach ($spiderList as $spider) {
1379 if (\
strpos($userAgent, $spider->spiderIdentifier
) !== false) {
1380 return \
intval($spider->spiderID
);
1388 * Returns true if this is a new session.
1392 public function isFirstVisit()
1394 return $this->firstVisit
;
1398 * Returns all sessions for a specific user.
1401 * @throws \InvalidArgumentException if the given user is a guest.
1404 public function getUserSessions(User
$user): array
1406 if (!$user->userID
) {
1407 throw new \
InvalidArgumentException("The given user is a guest.");
1411 FROM wcf" . WCF_N
. "_user_session
1413 $statement = WCF
::getDB()->prepareStatement($sql);
1414 $statement->execute([$user->userID
]);
1417 while ($row = $statement->fetchArray()) {
1418 $sessions[] = new Session($row);
1425 * Deletes the sessions for a specific user, except the session with the given session id.
1427 * If the given session id is `null` or unknown, all sessions of the user will be deleted.
1429 * @throws \InvalidArgumentException if the given user is a guest.
1432 public function deleteUserSessionsExcept(User
$user, ?
string $sessionID = null): void
1434 if (!$user->userID
) {
1435 throw new \
InvalidArgumentException("The given user is a guest.");
1438 $conditionBuilder = new PreparedStatementConditionBuilder();
1439 $conditionBuilder->add('userID = ?', [$user->userID
]);
1441 if ($sessionID !== null) {
1442 $conditionBuilder->add('sessionID <> ?', [$sessionID]);
1445 $sql = "DELETE FROM wcf" . WCF_N
. "_user_session
1446 " . $conditionBuilder;
1447 $statement = WCF
::getDB()->prepareStatement($sql);
1448 $statement->execute($conditionBuilder->getParameters());
1450 // Delete legacy session.
1451 $sql = "DELETE FROM wcf" . WCF_N
. "_session
1452 " . $conditionBuilder;
1453 $statement = WCF
::getDB()->prepareStatement($sql);
1454 $statement->execute($conditionBuilder->getParameters());
1458 * Deletes a session with the given session ID.
1462 public function deleteUserSession(string $sessionID): void
1464 $sql = "DELETE FROM wcf" . WCF_N
. "_user_session
1465 WHERE sessionID = ?";
1466 $statement = WCF
::getDB()->prepareStatement($sql);
1467 $statement->execute([$sessionID]);
1469 // Delete legacy session.
1470 $sql = "DELETE FROM wcf" . WCF_N
. "_session
1471 WHERE sessionID = ?";
1472 $statement = WCF
::getDB()->prepareStatement($sql);
1473 $statement->execute([$sessionID]);