3 * Authentication (and possibly Authorization in the future) system entry point
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Auth
;
27 use Psr\Log\LoggerAwareInterface
;
28 use Psr\Log\LoggerInterface
;
35 * This serves as the entry point to the authentication system.
37 * In the future, it may also serve as the entry point to the authorization
43 class AuthManager
implements LoggerAwareInterface
{
44 /** Log in with an existing (not necessarily local) user */
45 const ACTION_LOGIN
= 'login';
46 /** Continue a login process that was interrupted by the need for user input or communication
47 * with an external provider */
48 const ACTION_LOGIN_CONTINUE
= 'login-continue';
49 /** Create a new user */
50 const ACTION_CREATE
= 'create';
51 /** Continue a user creation process that was interrupted by the need for user input or
52 * communication with an external provider */
53 const ACTION_CREATE_CONTINUE
= 'create-continue';
54 /** Link an existing user to a third-party account */
55 const ACTION_LINK
= 'link';
56 /** Continue a user linking process that was interrupted by the need for user input or
57 * communication with an external provider */
58 const ACTION_LINK_CONTINUE
= 'link-continue';
59 /** Change a user's credentials */
60 const ACTION_CHANGE
= 'change';
61 /** Remove a user's credentials */
62 const ACTION_REMOVE
= 'remove';
63 /** Like ACTION_REMOVE but for linking providers only */
64 const ACTION_UNLINK
= 'unlink';
66 /** Security-sensitive operations are ok. */
68 /** Security-sensitive operations should re-authenticate. */
69 const SEC_REAUTH
= 'reauth';
70 /** Security-sensitive should not be performed. */
71 const SEC_FAIL
= 'fail';
73 /** Auto-creation is due to SessionManager */
74 const AUTOCREATE_SOURCE_SESSION
= \MediaWiki\Session\SessionManager
::class;
76 /** @var AuthManager|null */
77 private static $instance = null;
79 /** @var WebRequest */
85 /** @var LoggerInterface */
88 /** @var AuthenticationProvider[] */
89 private $allAuthenticationProviders = [];
91 /** @var PreAuthenticationProvider[] */
92 private $preAuthenticationProviders = null;
94 /** @var PrimaryAuthenticationProvider[] */
95 private $primaryAuthenticationProviders = null;
97 /** @var SecondaryAuthenticationProvider[] */
98 private $secondaryAuthenticationProviders = null;
100 /** @var CreatedAccountAuthenticationRequest[] */
101 private $createdAccountAuthenticationRequests = [];
104 * Get the global AuthManager
105 * @return AuthManager
107 public static function singleton() {
108 global $wgDisableAuthManager;
110 if ( $wgDisableAuthManager ) {
111 throw new \
BadMethodCallException( '$wgDisableAuthManager is set' );
114 if ( self
::$instance === null ) {
115 self
::$instance = new self(
116 \RequestContext
::getMain()->getRequest(),
117 \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' )
120 return self
::$instance;
124 * @param WebRequest $request
125 * @param Config $config
127 public function __construct( WebRequest
$request, Config
$config ) {
128 $this->request
= $request;
129 $this->config
= $config;
130 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' ) );
134 * @param LoggerInterface $logger
136 public function setLogger( LoggerInterface
$logger ) {
137 $this->logger
= $logger;
143 public function getRequest() {
144 return $this->request
;
148 * Force certain PrimaryAuthenticationProviders
149 * @deprecated For backwards compatibility only
150 * @param PrimaryAuthenticationProvider[] $providers
153 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
154 $this->logger
->warning( "Overriding AuthManager primary authn because $why" );
156 if ( $this->primaryAuthenticationProviders
!== null ) {
157 $this->logger
->warning(
158 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
161 $this->allAuthenticationProviders
= array_diff_key(
162 $this->allAuthenticationProviders
,
163 $this->primaryAuthenticationProviders
165 $session = $this->request
->getSession();
166 $session->remove( 'AuthManager::authnState' );
167 $session->remove( 'AuthManager::accountCreationState' );
168 $session->remove( 'AuthManager::accountLinkState' );
169 $this->createdAccountAuthenticationRequests
= [];
172 $this->primaryAuthenticationProviders
= [];
173 foreach ( $providers as $provider ) {
174 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
175 throw new \
RuntimeException(
176 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
177 get_class( $provider )
180 $provider->setLogger( $this->logger
);
181 $provider->setManager( $this );
182 $provider->setConfig( $this->config
);
183 $id = $provider->getUniqueId();
184 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
185 throw new \
RuntimeException(
186 "Duplicate specifications for id $id (classes " .
187 get_class( $provider ) . ' and ' .
188 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
191 $this->allAuthenticationProviders
[$id] = $provider;
192 $this->primaryAuthenticationProviders
[$id] = $provider;
197 * Call a legacy AuthPlugin method, if necessary
198 * @codeCoverageIgnore
199 * @deprecated For backwards compatibility only, should be avoided in new code
200 * @param string $method AuthPlugin method to call
201 * @param array $params Parameters to pass
202 * @param mixed $return Return value if AuthPlugin wasn't called
203 * @return mixed Return value from the AuthPlugin method, or $return
205 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
208 if ( $wgAuth && !$wgAuth instanceof AuthManagerAuthPlugin
) {
209 return call_user_func_array( [ $wgAuth, $method ], $params );
216 * @name Authentication
221 * Indicate whether user authentication is possible
223 * It may not be if the session is provided by something like OAuth
224 * for which each individual request includes authentication data.
228 public function canAuthenticateNow() {
229 return $this->request
->getSession()->canSetUser();
233 * Start an authentication flow
235 * In addition to the AuthenticationRequests returned by
236 * $this->getAuthenticationRequests(), a client might include a
237 * CreateFromLoginAuthenticationRequest from a previous login attempt to
240 * Instead of the AuthenticationRequests returned by
241 * $this->getAuthenticationRequests(), a client might pass a
242 * CreatedAccountAuthenticationRequest from an account creation that just
243 * succeeded to log in to the just-created account.
245 * @param AuthenticationRequest[] $reqs
246 * @param string $returnToUrl Url that REDIRECT responses should eventually
248 * @return AuthenticationResponse See self::continueAuthentication()
250 public function beginAuthentication( array $reqs, $returnToUrl ) {
251 $session = $this->request
->getSession();
252 if ( !$session->canSetUser() ) {
253 // Caller should have called canAuthenticateNow()
254 $session->remove( 'AuthManager::authnState' );
255 throw new \
LogicException( 'Authentication is not possible now' );
258 $guessUserName = null;
259 foreach ( $reqs as $req ) {
260 $req->returnToUrl
= $returnToUrl;
261 // @codeCoverageIgnoreStart
262 if ( $req->username
!== null && $req->username
!== '' ) {
263 if ( $guessUserName === null ) {
264 $guessUserName = $req->username
;
265 } elseif ( $guessUserName !== $req->username
) {
266 $guessUserName = null;
270 // @codeCoverageIgnoreEnd
273 // Check for special-case login of a just-created account
274 $req = AuthenticationRequest
::getRequestByClass(
275 $reqs, CreatedAccountAuthenticationRequest
::class
278 if ( !in_array( $req, $this->createdAccountAuthenticationRequests
, true ) ) {
279 throw new \
LogicException(
280 'CreatedAccountAuthenticationRequests are only valid on ' .
281 'the same AuthManager that created the account'
285 $user = User
::newFromName( $req->username
);
286 // @codeCoverageIgnoreStart
288 throw new \
UnexpectedValueException(
289 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
291 } elseif ( $user->getId() != $req->id
) {
292 throw new \
UnexpectedValueException(
293 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
296 // @codeCoverageIgnoreEnd
298 $this->logger
->info( 'Logging in {user} after account creation', [
299 'user' => $user->getName(),
301 $ret = AuthenticationResponse
::newPass( $user->getName() );
302 $this->setSessionDataForUser( $user );
303 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
304 $session->remove( 'AuthManager::authnState' );
305 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
309 $this->removeAuthenticationSessionData( null );
311 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
312 $status = $provider->testForAuthentication( $reqs );
313 if ( !$status->isGood() ) {
314 $this->logger
->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
315 $ret = AuthenticationResponse
::newFail(
316 Status
::wrap( $status )->getMessage()
318 $this->callMethodOnProviders( 7, 'postAuthentication',
319 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
321 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName ] );
328 'returnToUrl' => $returnToUrl,
329 'guessUserName' => $guessUserName,
331 'primaryResponse' => null,
334 'continueRequests' => [],
337 // Preserve state from a previous failed login
338 $req = AuthenticationRequest
::getRequestByClass(
339 $reqs, CreateFromLoginAuthenticationRequest
::class
342 $state['maybeLink'] = $req->maybeLink
;
345 $session = $this->request
->getSession();
346 $session->setSecret( 'AuthManager::authnState', $state );
349 return $this->continueAuthentication( $reqs );
353 * Continue an authentication flow
355 * Return values are interpreted as follows:
356 * - status FAIL: Authentication failed. If $response->createRequest is
357 * set, that may be passed to self::beginAuthentication() or to
358 * self::beginAccountCreation() to preserve state.
359 * - status REDIRECT: The client should be redirected to the contained URL,
360 * new AuthenticationRequests should be made (if any), then
361 * AuthManager::continueAuthentication() should be called.
362 * - status UI: The client should be presented with a user interface for
363 * the fields in the specified AuthenticationRequests, then new
364 * AuthenticationRequests should be made, then
365 * AuthManager::continueAuthentication() should be called.
366 * - status RESTART: The user logged in successfully with a third-party
367 * service, but the third-party credentials aren't attached to any local
368 * account. This could be treated as a UI or a FAIL.
369 * - status PASS: Authentication was successful.
371 * @param AuthenticationRequest[] $reqs
372 * @return AuthenticationResponse
374 public function continueAuthentication( array $reqs ) {
375 $session = $this->request
->getSession();
377 if ( !$session->canSetUser() ) {
378 // Caller should have called canAuthenticateNow()
379 // @codeCoverageIgnoreStart
380 throw new \
LogicException( 'Authentication is not possible now' );
381 // @codeCoverageIgnoreEnd
384 $state = $session->getSecret( 'AuthManager::authnState' );
385 if ( !is_array( $state ) ) {
386 return AuthenticationResponse
::newFail(
387 wfMessage( 'authmanager-authn-not-in-progress' )
390 $state['continueRequests'] = [];
392 $guessUserName = $state['guessUserName'];
394 foreach ( $reqs as $req ) {
395 $req->returnToUrl
= $state['returnToUrl'];
398 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
400 if ( $state['primary'] === null ) {
401 // We haven't picked a PrimaryAuthenticationProvider yet
402 // @codeCoverageIgnoreStart
403 $guessUserName = null;
404 foreach ( $reqs as $req ) {
405 if ( $req->username
!== null && $req->username
!== '' ) {
406 if ( $guessUserName === null ) {
407 $guessUserName = $req->username
;
408 } elseif ( $guessUserName !== $req->username
) {
409 $guessUserName = null;
414 $state['guessUserName'] = $guessUserName;
415 // @codeCoverageIgnoreEnd
416 $state['reqs'] = $reqs;
418 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
419 $res = $provider->beginPrimaryAuthentication( $reqs );
420 switch ( $res->status
) {
421 case AuthenticationResponse
::PASS
;
422 $state['primary'] = $id;
423 $state['primaryResponse'] = $res;
424 $this->logger
->debug( "Primary login with $id succeeded" );
426 case AuthenticationResponse
::FAIL
;
427 $this->logger
->debug( "Login failed in primary authentication by $id" );
428 if ( $res->createRequest ||
$state['maybeLink'] ) {
429 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
430 $res->createRequest
, $state['maybeLink']
433 $this->callMethodOnProviders( 7, 'postAuthentication',
434 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
436 $session->remove( 'AuthManager::authnState' );
437 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
439 case AuthenticationResponse
::ABSTAIN
;
442 case AuthenticationResponse
::REDIRECT
;
443 case AuthenticationResponse
::UI
;
444 $this->logger
->debug( "Primary login with $id returned $res->status" );
445 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
446 $state['primary'] = $id;
447 $state['continueRequests'] = $res->neededRequests
;
448 $session->setSecret( 'AuthManager::authnState', $state );
451 // @codeCoverageIgnoreStart
453 throw new \
DomainException(
454 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
456 // @codeCoverageIgnoreEnd
459 if ( $state['primary'] === null ) {
460 $this->logger
->debug( 'Login failed in primary authentication because no provider accepted' );
461 $ret = AuthenticationResponse
::newFail(
462 wfMessage( 'authmanager-authn-no-primary' )
464 $this->callMethodOnProviders( 7, 'postAuthentication',
465 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
467 $session->remove( 'AuthManager::authnState' );
470 } elseif ( $state['primaryResponse'] === null ) {
471 $provider = $this->getAuthenticationProvider( $state['primary'] );
472 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
473 // Configuration changed? Force them to start over.
474 // @codeCoverageIgnoreStart
475 $ret = AuthenticationResponse
::newFail(
476 wfMessage( 'authmanager-authn-not-in-progress' )
478 $this->callMethodOnProviders( 7, 'postAuthentication',
479 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
481 $session->remove( 'AuthManager::authnState' );
483 // @codeCoverageIgnoreEnd
485 $id = $provider->getUniqueId();
486 $res = $provider->continuePrimaryAuthentication( $reqs );
487 switch ( $res->status
) {
488 case AuthenticationResponse
::PASS
;
489 $state['primaryResponse'] = $res;
490 $this->logger
->debug( "Primary login with $id succeeded" );
492 case AuthenticationResponse
::FAIL
;
493 $this->logger
->debug( "Login failed in primary authentication by $id" );
494 if ( $res->createRequest ||
$state['maybeLink'] ) {
495 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
496 $res->createRequest
, $state['maybeLink']
499 $this->callMethodOnProviders( 7, 'postAuthentication',
500 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
502 $session->remove( 'AuthManager::authnState' );
503 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
505 case AuthenticationResponse
::REDIRECT
;
506 case AuthenticationResponse
::UI
;
507 $this->logger
->debug( "Primary login with $id returned $res->status" );
508 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
509 $state['continueRequests'] = $res->neededRequests
;
510 $session->setSecret( 'AuthManager::authnState', $state );
513 throw new \
DomainException(
514 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
519 $res = $state['primaryResponse'];
520 if ( $res->username
=== null ) {
521 $provider = $this->getAuthenticationProvider( $state['primary'] );
522 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
523 // Configuration changed? Force them to start over.
524 // @codeCoverageIgnoreStart
525 $ret = AuthenticationResponse
::newFail(
526 wfMessage( 'authmanager-authn-not-in-progress' )
528 $this->callMethodOnProviders( 7, 'postAuthentication',
529 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
531 $session->remove( 'AuthManager::authnState' );
533 // @codeCoverageIgnoreEnd
536 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
&&
538 // don't confuse the user with an incorrect message if linking is disabled
539 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider
::class )
541 $state['maybeLink'][$res->linkRequest
->getUniqueId()] = $res->linkRequest
;
542 $msg = 'authmanager-authn-no-local-user-link';
544 $msg = 'authmanager-authn-no-local-user';
546 $this->logger
->debug(
547 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
549 $ret = AuthenticationResponse
::newRestart( wfMessage( $msg ) );
550 $ret->neededRequests
= $this->getAuthenticationRequestsInternal(
553 $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders()
555 if ( $res->createRequest ||
$state['maybeLink'] ) {
556 $ret->createRequest
= new CreateFromLoginAuthenticationRequest(
557 $res->createRequest
, $state['maybeLink']
559 $ret->neededRequests
[] = $ret->createRequest
;
561 $this->fillRequests( $ret->neededRequests
, self
::ACTION_LOGIN
, null, true );
562 $session->setSecret( 'AuthManager::authnState', [
563 'reqs' => [], // Will be filled in later
565 'primaryResponse' => null,
567 'continueRequests' => $ret->neededRequests
,
572 // Step 2: Primary authentication succeeded, create the User object
573 // (and add the user locally if necessary)
575 $user = User
::newFromName( $res->username
, 'usable' );
577 throw new \
DomainException(
578 get_class( $provider ) . " returned an invalid username: {$res->username}"
581 if ( $user->getId() === 0 ) {
582 // User doesn't exist locally. Create it.
583 $this->logger
->info( 'Auto-creating {user} on login', [
584 'user' => $user->getName(),
586 $status = $this->autoCreateUser( $user, $state['primary'], false );
587 if ( !$status->isGood() ) {
588 $ret = AuthenticationResponse
::newFail(
589 Status
::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
591 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
592 $session->remove( 'AuthManager::authnState' );
593 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
598 // Step 3: Iterate over all the secondary authentication providers.
600 $beginReqs = $state['reqs'];
602 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
603 if ( !isset( $state['secondary'][$id] ) ) {
604 // This provider isn't started yet, so we pass it the set
605 // of reqs from beginAuthentication instead of whatever
606 // might have been used by a previous provider in line.
607 $func = 'beginSecondaryAuthentication';
608 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
609 } elseif ( !$state['secondary'][$id] ) {
610 $func = 'continueSecondaryAuthentication';
611 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
615 switch ( $res->status
) {
616 case AuthenticationResponse
::PASS
;
617 $this->logger
->debug( "Secondary login with $id succeeded" );
619 case AuthenticationResponse
::ABSTAIN
;
620 $state['secondary'][$id] = true;
622 case AuthenticationResponse
::FAIL
;
623 $this->logger
->debug( "Login failed in secondary authentication by $id" );
624 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
625 $session->remove( 'AuthManager::authnState' );
626 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName() ] );
628 case AuthenticationResponse
::REDIRECT
;
629 case AuthenticationResponse
::UI
;
630 $this->logger
->debug( "Secondary login with $id returned " . $res->status
);
631 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $user->getName() );
632 $state['secondary'][$id] = false;
633 $state['continueRequests'] = $res->neededRequests
;
634 $session->setSecret( 'AuthManager::authnState', $state );
637 // @codeCoverageIgnoreStart
639 throw new \
DomainException(
640 get_class( $provider ) . "::{$func}() returned $res->status"
642 // @codeCoverageIgnoreEnd
646 // Step 4: Authentication complete! Set the user in the session and
649 $this->logger
->info( 'Login for {user} succeeded', [
650 'user' => $user->getName(),
652 $req = AuthenticationRequest
::getRequestByClass(
653 $beginReqs, RememberMeAuthenticationRequest
::class
655 $this->setSessionDataForUser( $user, $req && $req->rememberMe
);
656 $ret = AuthenticationResponse
::newPass( $user->getName() );
657 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
658 $session->remove( 'AuthManager::authnState' );
659 $this->removeAuthenticationSessionData( null );
660 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
662 } catch ( \Exception
$ex ) {
663 $session->remove( 'AuthManager::authnState' );
669 * Whether security-sensitive operations should proceed.
671 * A "security-sensitive operation" is something like a password or email
672 * change, that would normally have a "reenter your password to confirm"
673 * box if we only supported password-based authentication.
675 * @param string $operation Operation being checked. This should be a
676 * message-key-like string such as 'change-password' or 'change-email'.
677 * @return string One of the SEC_* constants.
679 public function securitySensitiveOperationStatus( $operation ) {
680 $status = self
::SEC_OK
;
682 $this->logger
->debug( __METHOD__
. ": Checking $operation" );
684 $session = $this->request
->getSession();
685 $aId = $session->getUser()->getId();
687 // User isn't authenticated. DWIM?
688 $status = $this->canAuthenticateNow() ? self
::SEC_REAUTH
: self
::SEC_FAIL
;
689 $this->logger
->info( __METHOD__
. ": Not logged in! $operation is $status" );
693 if ( $session->canSetUser() ) {
694 $id = $session->get( 'AuthManager:lastAuthId' );
695 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
696 if ( $id !== $aId ||
$last === null ) {
697 $timeSinceLogin = PHP_INT_MAX
; // Forever ago
699 $timeSinceLogin = max( 0, time() - $last );
702 $thresholds = $this->config
->get( 'ReauthenticateTime' );
703 if ( isset( $thresholds[$operation] ) ) {
704 $threshold = $thresholds[$operation];
705 } elseif ( isset( $thresholds['default'] ) ) {
706 $threshold = $thresholds['default'];
708 throw new \
UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
711 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
712 $status = self
::SEC_REAUTH
;
715 $timeSinceLogin = -1;
717 $pass = $this->config
->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
718 if ( isset( $pass[$operation] ) ) {
719 $status = $pass[$operation] ? self
::SEC_OK
: self
::SEC_FAIL
;
720 } elseif ( isset( $pass['default'] ) ) {
721 $status = $pass['default'] ? self
::SEC_OK
: self
::SEC_FAIL
;
723 throw new \
UnexpectedValueException(
724 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
729 \Hooks
::run( 'SecuritySensitiveOperationStatus', [
730 &$status, $operation, $session, $timeSinceLogin
733 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
734 if ( !$this->canAuthenticateNow() && $status === self
::SEC_REAUTH
) {
735 $status = self
::SEC_FAIL
;
738 $this->logger
->info( __METHOD__
. ": $operation is $status" );
744 * Determine whether a username can authenticate
746 * @param string $username
749 public function userCanAuthenticate( $username ) {
750 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
751 if ( $provider->testUserCanAuthenticate( $username ) ) {
759 * Provide normalized versions of the username for security checks
761 * Since different providers can normalize the input in different ways,
762 * this returns an array of all the different ways the name might be
763 * normalized for authentication.
765 * The returned strings should not be revealed to the user, as that might
766 * leak private information (e.g. an email address might be normalized to a
769 * @param string $username
772 public function normalizeUsername( $username ) {
774 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
775 $normalized = $provider->providerNormalizeUsername( $username );
776 if ( $normalized !== null ) {
777 $ret[$normalized] = true;
780 return array_keys( $ret );
786 * @name Authentication data changing
791 * Revoke any authentication credentials for a user
793 * After this, the user should no longer be able to log in.
795 * @param string $username
797 public function revokeAccessForUser( $username ) {
798 $this->logger
->info( 'Revoking access for {user}', [
801 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
805 * Validate a change of authentication data (e.g. passwords)
806 * @param AuthenticationRequest $req
807 * @param bool $checkData If false, $req hasn't been loaded from the
808 * submission so checks on user-submitted fields should be skipped. $req->username is
809 * considered user-submitted for this purpose, even if it cannot be changed via
810 * $req->loadFromSubmission.
813 public function allowsAuthenticationDataChange( AuthenticationRequest
$req, $checkData = true ) {
815 $providers = $this->getPrimaryAuthenticationProviders() +
816 $this->getSecondaryAuthenticationProviders();
817 foreach ( $providers as $provider ) {
818 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
819 if ( !$status->isGood() ) {
820 return Status
::wrap( $status );
822 $any = $any ||
$status->value
!== 'ignored';
825 $status = Status
::newGood( 'ignored' );
826 $status->warning( 'authmanager-change-not-supported' );
829 return Status
::newGood();
833 * Change authentication data (e.g. passwords)
835 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
836 * result in a successful login in the future.
838 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
839 * no longer result in a successful login.
841 * @param AuthenticationRequest $req
843 public function changeAuthenticationData( AuthenticationRequest
$req ) {
844 $this->logger
->info( 'Changing authentication data for {user} class {what}', [
845 'user' => is_string( $req->username
) ?
$req->username
: '<no name>',
846 'what' => get_class( $req ),
849 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
851 // When the main account's authentication data is changed, invalidate
852 // all BotPasswords too.
853 \BotPassword
::invalidateAllPasswordsForUser( $req->username
);
859 * @name Account creation
864 * Determine whether accounts can be created
867 public function canCreateAccounts() {
868 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
869 switch ( $provider->accountCreationType() ) {
870 case PrimaryAuthenticationProvider
::TYPE_CREATE
:
871 case PrimaryAuthenticationProvider
::TYPE_LINK
:
879 * Determine whether a particular account can be created
880 * @param string $username
881 * @param int $flags Bitfield of User:READ_* constants
884 public function canCreateAccount( $username, $flags = User
::READ_NORMAL
) {
885 if ( !$this->canCreateAccounts() ) {
886 return Status
::newFatal( 'authmanager-create-disabled' );
889 if ( $this->userExists( $username, $flags ) ) {
890 return Status
::newFatal( 'userexists' );
893 $user = User
::newFromName( $username, 'creatable' );
894 if ( !is_object( $user ) ) {
895 return Status
::newFatal( 'noname' );
897 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
898 if ( $user->getId() !== 0 ) {
899 return Status
::newFatal( 'userexists' );
903 // Denied by providers?
904 $providers = $this->getPreAuthenticationProviders() +
905 $this->getPrimaryAuthenticationProviders() +
906 $this->getSecondaryAuthenticationProviders();
907 foreach ( $providers as $provider ) {
908 $status = $provider->testUserForCreation( $user, false );
909 if ( !$status->isGood() ) {
910 return Status
::wrap( $status );
914 return Status
::newGood();
918 * Basic permissions checks on whether a user can create accounts
919 * @param User $creator User doing the account creation
922 public function checkAccountCreatePermissions( User
$creator ) {
923 // Wiki is read-only?
924 if ( wfReadOnly() ) {
925 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
928 // This is awful, this permission check really shouldn't go through Title.
929 $permErrors = \SpecialPage
::getTitleFor( 'CreateAccount' )
930 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
932 $status = Status
::newGood();
933 foreach ( $permErrors as $args ) {
934 call_user_func_array( [ $status, 'fatal' ], $args );
939 $block = $creator->isBlockedFromCreateAccount();
943 $block->mReason ?
: wfMessage( 'blockednoreason' )->text(),
947 if ( $block->getType() === \Block
::TYPE_RANGE
) {
948 $errorMessage = 'cantcreateaccount-range-text';
949 $errorParams[] = $this->getRequest()->getIP();
951 $errorMessage = 'cantcreateaccount-text';
954 return Status
::newFatal( wfMessage( $errorMessage, $errorParams ) );
957 $ip = $this->getRequest()->getIP();
958 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
959 return Status
::newFatal( 'sorbs_create_account_reason' );
962 return Status
::newGood();
966 * Start an account creation flow
968 * In addition to the AuthenticationRequests returned by
969 * $this->getAuthenticationRequests(), a client might include a
970 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
972 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
974 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
975 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
976 * username set, that username must be used for all other requests.
978 * @param User $creator User doing the account creation
979 * @param AuthenticationRequest[] $reqs
980 * @param string $returnToUrl Url that REDIRECT responses should eventually
982 * @return AuthenticationResponse
984 public function beginAccountCreation( User
$creator, array $reqs, $returnToUrl ) {
985 $session = $this->request
->getSession();
986 if ( !$this->canCreateAccounts() ) {
987 // Caller should have called canCreateAccounts()
988 $session->remove( 'AuthManager::accountCreationState' );
989 throw new \
LogicException( 'Account creation is not possible' );
993 $username = AuthenticationRequest
::getUsernameFromRequests( $reqs );
994 } catch ( \UnexpectedValueException
$ex ) {
997 if ( $username === null ) {
998 $this->logger
->debug( __METHOD__
. ': No username provided' );
999 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1002 // Permissions check
1003 $status = $this->checkAccountCreatePermissions( $creator );
1004 if ( !$status->isGood() ) {
1005 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1006 'user' => $username,
1007 'creator' => $creator->getName(),
1008 'reason' => $status->getWikiText( null, null, 'en' )
1010 return AuthenticationResponse
::newFail( $status->getMessage() );
1013 $status = $this->canCreateAccount( $username, User
::READ_LOCKING
);
1014 if ( !$status->isGood() ) {
1015 $this->logger
->debug( __METHOD__
. ': {user} cannot be created: {reason}', [
1016 'user' => $username,
1017 'creator' => $creator->getName(),
1018 'reason' => $status->getWikiText( null, null, 'en' )
1020 return AuthenticationResponse
::newFail( $status->getMessage() );
1023 $user = User
::newFromName( $username, 'creatable' );
1024 foreach ( $reqs as $req ) {
1025 $req->username
= $username;
1026 $req->returnToUrl
= $returnToUrl;
1027 if ( $req instanceof UserDataAuthenticationRequest
) {
1028 $status = $req->populateUser( $user );
1029 if ( !$status->isGood() ) {
1030 $status = Status
::wrap( $status );
1031 $session->remove( 'AuthManager::accountCreationState' );
1032 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1033 'user' => $user->getName(),
1034 'creator' => $creator->getName(),
1035 'reason' => $status->getWikiText( null, null, 'en' ),
1037 return AuthenticationResponse
::newFail( $status->getMessage() );
1042 $this->removeAuthenticationSessionData( null );
1045 'username' => $username,
1047 'creatorid' => $creator->getId(),
1048 'creatorname' => $creator->getName(),
1050 'returnToUrl' => $returnToUrl,
1052 'primaryResponse' => null,
1054 'continueRequests' => [],
1056 'ranPreTests' => false,
1059 // Special case: converting a login to an account creation
1060 $req = AuthenticationRequest
::getRequestByClass(
1061 $reqs, CreateFromLoginAuthenticationRequest
::class
1064 $state['maybeLink'] = $req->maybeLink
;
1066 if ( $req->createRequest
) {
1067 $reqs[] = $req->createRequest
;
1068 $state['reqs'][] = $req->createRequest
;
1072 $session->setSecret( 'AuthManager::accountCreationState', $state );
1073 $session->persist();
1075 return $this->continueAccountCreation( $reqs );
1079 * Continue an account creation flow
1080 * @param AuthenticationRequest[] $reqs
1081 * @return AuthenticationResponse
1083 public function continueAccountCreation( array $reqs ) {
1084 $session = $this->request
->getSession();
1086 if ( !$this->canCreateAccounts() ) {
1087 // Caller should have called canCreateAccounts()
1088 $session->remove( 'AuthManager::accountCreationState' );
1089 throw new \
LogicException( 'Account creation is not possible' );
1092 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1093 if ( !is_array( $state ) ) {
1094 return AuthenticationResponse
::newFail(
1095 wfMessage( 'authmanager-create-not-in-progress' )
1098 $state['continueRequests'] = [];
1100 // Step 0: Prepare and validate the input
1102 $user = User
::newFromName( $state['username'], 'creatable' );
1103 if ( !is_object( $user ) ) {
1104 $session->remove( 'AuthManager::accountCreationState' );
1105 $this->logger
->debug( __METHOD__
. ': Invalid username', [
1106 'user' => $state['username'],
1108 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1111 if ( $state['creatorid'] ) {
1112 $creator = User
::newFromId( $state['creatorid'] );
1114 $creator = new User
;
1115 $creator->setName( $state['creatorname'] );
1118 // Avoid account creation races on double submissions
1119 $cache = \ObjectCache
::getLocalClusterInstance();
1120 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1122 // Don't clear AuthManager::accountCreationState for this code
1123 // path because the process that won the race owns it.
1124 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1125 'user' => $user->getName(),
1126 'creator' => $creator->getName(),
1128 return AuthenticationResponse
::newFail( wfMessage( 'usernameinprogress' ) );
1131 // Permissions check
1132 $status = $this->checkAccountCreatePermissions( $creator );
1133 if ( !$status->isGood() ) {
1134 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1135 'user' => $user->getName(),
1136 'creator' => $creator->getName(),
1137 'reason' => $status->getWikiText( null, null, 'en' )
1139 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1140 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1141 $session->remove( 'AuthManager::accountCreationState' );
1145 // Load from master for existence check
1146 $user->load( User
::READ_LOCKING
);
1148 if ( $state['userid'] === 0 ) {
1149 if ( $user->getId() != 0 ) {
1150 $this->logger
->debug( __METHOD__
. ': User exists locally', [
1151 'user' => $user->getName(),
1152 'creator' => $creator->getName(),
1154 $ret = AuthenticationResponse
::newFail( wfMessage( 'userexists' ) );
1155 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1156 $session->remove( 'AuthManager::accountCreationState' );
1160 if ( $user->getId() == 0 ) {
1161 $this->logger
->debug( __METHOD__
. ': User does not exist locally when it should', [
1162 'user' => $user->getName(),
1163 'creator' => $creator->getName(),
1164 'expected_id' => $state['userid'],
1166 throw new \
UnexpectedValueException(
1167 "User \"{$state['username']}\" should exist now, but doesn't!"
1170 if ( $user->getId() != $state['userid'] ) {
1171 $this->logger
->debug( __METHOD__
. ': User ID/name mismatch', [
1172 'user' => $user->getName(),
1173 'creator' => $creator->getName(),
1174 'expected_id' => $state['userid'],
1175 'actual_id' => $user->getId(),
1177 throw new \
UnexpectedValueException(
1178 "User \"{$state['username']}\" exists, but " .
1179 "ID {$user->getId()} != {$state['userid']}!"
1183 foreach ( $state['reqs'] as $req ) {
1184 if ( $req instanceof UserDataAuthenticationRequest
) {
1185 $status = $req->populateUser( $user );
1186 if ( !$status->isGood() ) {
1187 // This should never happen...
1188 $status = Status
::wrap( $status );
1189 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1190 'user' => $user->getName(),
1191 'creator' => $creator->getName(),
1192 'reason' => $status->getWikiText( null, null, 'en' ),
1194 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1195 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1196 $session->remove( 'AuthManager::accountCreationState' );
1202 foreach ( $reqs as $req ) {
1203 $req->returnToUrl
= $state['returnToUrl'];
1204 $req->username
= $state['username'];
1207 // Run pre-creation tests, if we haven't already
1208 if ( !$state['ranPreTests'] ) {
1209 $providers = $this->getPreAuthenticationProviders() +
1210 $this->getPrimaryAuthenticationProviders() +
1211 $this->getSecondaryAuthenticationProviders();
1212 foreach ( $providers as $id => $provider ) {
1213 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1214 if ( !$status->isGood() ) {
1215 $this->logger
->debug( __METHOD__
. ": Fail in pre-authentication by $id", [
1216 'user' => $user->getName(),
1217 'creator' => $creator->getName(),
1219 $ret = AuthenticationResponse
::newFail(
1220 Status
::wrap( $status )->getMessage()
1222 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1223 $session->remove( 'AuthManager::accountCreationState' );
1228 $state['ranPreTests'] = true;
1231 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1233 if ( $state['primary'] === null ) {
1234 // We haven't picked a PrimaryAuthenticationProvider yet
1235 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1236 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_NONE
) {
1239 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1240 switch ( $res->status
) {
1241 case AuthenticationResponse
::PASS
;
1242 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1243 'user' => $user->getName(),
1244 'creator' => $creator->getName(),
1246 $state['primary'] = $id;
1247 $state['primaryResponse'] = $res;
1249 case AuthenticationResponse
::FAIL
;
1250 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1251 'user' => $user->getName(),
1252 'creator' => $creator->getName(),
1254 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1255 $session->remove( 'AuthManager::accountCreationState' );
1257 case AuthenticationResponse
::ABSTAIN
;
1260 case AuthenticationResponse
::REDIRECT
;
1261 case AuthenticationResponse
::UI
;
1262 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1263 'user' => $user->getName(),
1264 'creator' => $creator->getName(),
1266 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1267 $state['primary'] = $id;
1268 $state['continueRequests'] = $res->neededRequests
;
1269 $session->setSecret( 'AuthManager::accountCreationState', $state );
1272 // @codeCoverageIgnoreStart
1274 throw new \
DomainException(
1275 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1277 // @codeCoverageIgnoreEnd
1280 if ( $state['primary'] === null ) {
1281 $this->logger
->debug( __METHOD__
. ': Primary creation failed because no provider accepted', [
1282 'user' => $user->getName(),
1283 'creator' => $creator->getName(),
1285 $ret = AuthenticationResponse
::newFail(
1286 wfMessage( 'authmanager-create-no-primary' )
1288 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1289 $session->remove( 'AuthManager::accountCreationState' );
1292 } elseif ( $state['primaryResponse'] === null ) {
1293 $provider = $this->getAuthenticationProvider( $state['primary'] );
1294 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1295 // Configuration changed? Force them to start over.
1296 // @codeCoverageIgnoreStart
1297 $ret = AuthenticationResponse
::newFail(
1298 wfMessage( 'authmanager-create-not-in-progress' )
1300 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1301 $session->remove( 'AuthManager::accountCreationState' );
1303 // @codeCoverageIgnoreEnd
1305 $id = $provider->getUniqueId();
1306 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1307 switch ( $res->status
) {
1308 case AuthenticationResponse
::PASS
;
1309 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1310 'user' => $user->getName(),
1311 'creator' => $creator->getName(),
1313 $state['primaryResponse'] = $res;
1315 case AuthenticationResponse
::FAIL
;
1316 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1317 'user' => $user->getName(),
1318 'creator' => $creator->getName(),
1320 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1321 $session->remove( 'AuthManager::accountCreationState' );
1323 case AuthenticationResponse
::REDIRECT
;
1324 case AuthenticationResponse
::UI
;
1325 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1326 'user' => $user->getName(),
1327 'creator' => $creator->getName(),
1329 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1330 $state['continueRequests'] = $res->neededRequests
;
1331 $session->setSecret( 'AuthManager::accountCreationState', $state );
1334 throw new \
DomainException(
1335 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1340 // Step 2: Primary authentication succeeded, create the User object
1341 // and add the user locally.
1343 if ( $state['userid'] === 0 ) {
1344 $this->logger
->info( 'Creating user {user} during account creation', [
1345 'user' => $user->getName(),
1346 'creator' => $creator->getName(),
1348 $status = $user->addToDatabase();
1349 if ( !$status->isOk() ) {
1350 // @codeCoverageIgnoreStart
1351 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1352 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1353 $session->remove( 'AuthManager::accountCreationState' );
1355 // @codeCoverageIgnoreEnd
1357 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1358 \Hooks
::run( 'LocalUserCreated', [ $user, false ] );
1359 $user->saveSettings();
1360 $state['userid'] = $user->getId();
1362 // Update user count
1363 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1365 // Watch user's userpage and talk page
1366 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1368 // Inform the provider
1369 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1372 if ( $this->config
->get( 'NewUserLog' ) ) {
1373 $isAnon = $creator->isAnon();
1374 $logEntry = new \
ManualLogEntry(
1376 $logSubtype ?
: ( $isAnon ?
'create' : 'create2' )
1378 $logEntry->setPerformer( $isAnon ?
$user : $creator );
1379 $logEntry->setTarget( $user->getUserPage() );
1380 $req = AuthenticationRequest
::getRequestByClass(
1381 $state['reqs'], CreationReasonAuthenticationRequest
::class
1383 $logEntry->setComment( $req ?
$req->reason
: '' );
1384 $logEntry->setParameters( [
1385 '4::userid' => $user->getId(),
1387 $logid = $logEntry->insert();
1388 $logEntry->publish( $logid );
1392 // Step 3: Iterate over all the secondary authentication providers.
1394 $beginReqs = $state['reqs'];
1396 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1397 if ( !isset( $state['secondary'][$id] ) ) {
1398 // This provider isn't started yet, so we pass it the set
1399 // of reqs from beginAuthentication instead of whatever
1400 // might have been used by a previous provider in line.
1401 $func = 'beginSecondaryAccountCreation';
1402 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1403 } elseif ( !$state['secondary'][$id] ) {
1404 $func = 'continueSecondaryAccountCreation';
1405 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1409 switch ( $res->status
) {
1410 case AuthenticationResponse
::PASS
;
1411 $this->logger
->debug( __METHOD__
. ": Secondary creation passed by $id", [
1412 'user' => $user->getName(),
1413 'creator' => $creator->getName(),
1416 case AuthenticationResponse
::ABSTAIN
;
1417 $state['secondary'][$id] = true;
1419 case AuthenticationResponse
::REDIRECT
;
1420 case AuthenticationResponse
::UI
;
1421 $this->logger
->debug( __METHOD__
. ": Secondary creation $res->status by $id", [
1422 'user' => $user->getName(),
1423 'creator' => $creator->getName(),
1425 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1426 $state['secondary'][$id] = false;
1427 $state['continueRequests'] = $res->neededRequests
;
1428 $session->setSecret( 'AuthManager::accountCreationState', $state );
1430 case AuthenticationResponse
::FAIL
;
1431 throw new \
DomainException(
1432 get_class( $provider ) . "::{$func}() returned $res->status." .
1433 ' Secondary providers are not allowed to fail account creation, that' .
1434 ' should have been done via testForAccountCreation().'
1436 // @codeCoverageIgnoreStart
1438 throw new \
DomainException(
1439 get_class( $provider ) . "::{$func}() returned $res->status"
1441 // @codeCoverageIgnoreEnd
1445 $id = $user->getId();
1446 $name = $user->getName();
1447 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1448 $ret = AuthenticationResponse
::newPass( $name );
1449 $ret->loginRequest
= $req;
1450 $this->createdAccountAuthenticationRequests
[] = $req;
1452 $this->logger
->info( __METHOD__
. ': Account creation succeeded for {user}', [
1453 'user' => $user->getName(),
1454 'creator' => $creator->getName(),
1457 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1458 $session->remove( 'AuthManager::accountCreationState' );
1459 $this->removeAuthenticationSessionData( null );
1461 } catch ( \Exception
$ex ) {
1462 $session->remove( 'AuthManager::accountCreationState' );
1468 * Auto-create an account, and log into that account
1469 * @param User $user User to auto-create
1470 * @param string $source What caused the auto-creation? This must be the ID
1471 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1472 * @param bool $login Whether to also log the user in
1473 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1475 public function autoCreateUser( User
$user, $source, $login = true ) {
1476 if ( $source !== self
::AUTOCREATE_SOURCE_SESSION
&&
1477 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1479 throw new \
InvalidArgumentException( "Unknown auto-creation source: $source" );
1482 $username = $user->getName();
1484 // Try the local user from the slave DB
1485 $localId = User
::idFromName( $username );
1486 $flags = User
::READ_NORMAL
;
1488 // Fetch the user ID from the master, so that we don't try to create the user
1489 // when they already exist, due to replication lag
1490 // @codeCoverageIgnoreStart
1491 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
1492 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1493 $flags = User
::READ_LATEST
;
1495 // @codeCoverageIgnoreEnd
1498 $this->logger
->debug( __METHOD__
. ': {username} already exists locally', [
1499 'username' => $username,
1501 $user->setId( $localId );
1502 $user->loadFromId( $flags );
1504 $this->setSessionDataForUser( $user );
1506 $status = Status
::newGood();
1507 $status->warning( 'userexists' );
1511 // Wiki is read-only?
1512 if ( wfReadOnly() ) {
1513 $this->logger
->debug( __METHOD__
. ': denied by wfReadOnly(): {reason}', [
1514 'username' => $username,
1515 'reason' => wfReadOnlyReason(),
1518 $user->loadFromId();
1519 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1522 // Check the session, if we tried to create this user already there's
1523 // no point in retrying.
1524 $session = $this->request
->getSession();
1525 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1526 $this->logger
->debug( __METHOD__
. ': blacklisted in session {sessionid}', [
1527 'username' => $username,
1528 'sessionid' => $session->getId(),
1531 $user->loadFromId();
1532 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1533 if ( $reason instanceof StatusValue
) {
1534 return Status
::wrap( $reason );
1536 return Status
::newFatal( $reason );
1540 // Is the username creatable?
1541 if ( !User
::isCreatableName( $username ) ) {
1542 $this->logger
->debug( __METHOD__
. ': name "{username}" is not creatable', [
1543 'username' => $username,
1545 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname', 600 );
1547 $user->loadFromId();
1548 return Status
::newFatal( 'noname' );
1551 // Is the IP user able to create accounts?
1553 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1554 $this->logger
->debug( __METHOD__
. ': IP lacks the ability to create or autocreate accounts', [
1555 'username' => $username,
1556 'ip' => $anon->getName(),
1558 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm', 600 );
1559 $session->persist();
1561 $user->loadFromId();
1562 return Status
::newFatal( 'authmanager-autocreate-noperm' );
1565 // Avoid account creation races on double submissions
1566 $cache = \ObjectCache
::getLocalClusterInstance();
1567 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1569 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1570 'user' => $username,
1573 $user->loadFromId();
1574 return Status
::newFatal( 'usernameinprogress' );
1577 // Denied by providers?
1578 $providers = $this->getPreAuthenticationProviders() +
1579 $this->getPrimaryAuthenticationProviders() +
1580 $this->getSecondaryAuthenticationProviders();
1581 foreach ( $providers as $provider ) {
1582 $status = $provider->testUserForCreation( $user, $source );
1583 if ( !$status->isGood() ) {
1584 $ret = Status
::wrap( $status );
1585 $this->logger
->debug( __METHOD__
. ': Provider denied creation of {username}: {reason}', [
1586 'username' => $username,
1587 'reason' => $ret->getWikiText( null, null, 'en' ),
1589 $session->set( 'AuthManager::AutoCreateBlacklist', $status, 600 );
1591 $user->loadFromId();
1596 // Ignore warnings about master connections/writes...hard to avoid here
1597 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
1599 $backoffKey = wfMemcKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1600 if ( $cache->get( $backoffKey ) ) {
1601 $this->logger
->debug( __METHOD__
. ': {username} denied by prior creation attempt failures', [
1602 'username' => $username,
1605 $user->loadFromId();
1606 return Status
::newFatal( 'authmanager-autocreate-exception' );
1609 // Checks passed, create the user...
1610 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
1611 $this->logger
->info( __METHOD__
. ': creating new user ({username}) - from: {from}', [
1612 'username' => $username,
1617 $status = $user->addToDatabase();
1618 if ( !$status->isOk() ) {
1619 // double-check for a race condition (T70012)
1620 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1622 $this->logger
->info( __METHOD__
. ': {username} already exists locally (race)', [
1623 'username' => $username,
1625 $user->setId( $localId );
1626 $user->loadFromId( User
::READ_LATEST
);
1628 $this->setSessionDataForUser( $user );
1630 $status = Status
::newGood();
1631 $status->warning( 'userexists' );
1633 $this->logger
->error( __METHOD__
. ': {username} failed with message {message}', [
1634 'username' => $username,
1635 'message' => $status->getWikiText( null, null, 'en' )
1638 $user->loadFromId();
1642 } catch ( \Exception
$ex ) {
1643 $this->logger
->error( __METHOD__
. ': {username} failed with exception {exception}', [
1644 'username' => $username,
1647 // Do not keep throwing errors for a while
1648 $cache->set( $backoffKey, 1, 600 );
1649 // Bubble up error; which should normally trigger DB rollbacks
1653 $this->setDefaultUserOptions( $user, true );
1655 // Inform the providers
1656 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1658 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1659 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
1660 $user->saveSettings();
1662 // Update user count
1663 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1665 // Watch user's userpage and talk page
1666 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1669 if ( $this->config
->get( 'NewUserLog' ) ) {
1670 $logEntry = new \
ManualLogEntry( 'newusers', 'autocreate' );
1671 $logEntry->setPerformer( $user );
1672 $logEntry->setTarget( $user->getUserPage() );
1673 $logEntry->setComment( '' );
1674 $logEntry->setParameters( [
1675 '4::userid' => $user->getId(),
1677 $logid = $logEntry->insert();
1681 $this->setSessionDataForUser( $user );
1684 return Status
::newGood();
1690 * @name Account linking
1695 * Determine whether accounts can be linked
1698 public function canLinkAccounts() {
1699 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1700 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
) {
1708 * Start an account linking flow
1710 * @param User $user User being linked
1711 * @param AuthenticationRequest[] $reqs
1712 * @param string $returnToUrl Url that REDIRECT responses should eventually
1714 * @return AuthenticationResponse
1716 public function beginAccountLink( User
$user, array $reqs, $returnToUrl ) {
1717 $session = $this->request
->getSession();
1718 $session->remove( 'AuthManager::accountLinkState' );
1720 if ( !$this->canLinkAccounts() ) {
1721 // Caller should have called canLinkAccounts()
1722 throw new \
LogicException( 'Account linking is not possible' );
1725 if ( $user->getId() === 0 ) {
1726 if ( !User
::isUsableName( $user->getName() ) ) {
1727 $msg = wfMessage( 'noname' );
1729 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1731 return AuthenticationResponse
::newFail( $msg );
1733 foreach ( $reqs as $req ) {
1734 $req->username
= $user->getName();
1735 $req->returnToUrl
= $returnToUrl;
1738 $this->removeAuthenticationSessionData( null );
1740 $providers = $this->getPreAuthenticationProviders();
1741 foreach ( $providers as $id => $provider ) {
1742 $status = $provider->testForAccountLink( $user );
1743 if ( !$status->isGood() ) {
1744 $this->logger
->debug( __METHOD__
. ": Account linking pre-check failed by $id", [
1745 'user' => $user->getName(),
1747 $ret = AuthenticationResponse
::newFail(
1748 Status
::wrap( $status )->getMessage()
1750 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1756 'username' => $user->getName(),
1757 'userid' => $user->getId(),
1758 'returnToUrl' => $returnToUrl,
1760 'continueRequests' => [],
1763 $providers = $this->getPrimaryAuthenticationProviders();
1764 foreach ( $providers as $id => $provider ) {
1765 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider
::TYPE_LINK
) {
1769 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1770 switch ( $res->status
) {
1771 case AuthenticationResponse
::PASS
;
1772 $this->logger
->info( "Account linked to {user} by $id", [
1773 'user' => $user->getName(),
1775 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1778 case AuthenticationResponse
::FAIL
;
1779 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1780 'user' => $user->getName(),
1782 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1785 case AuthenticationResponse
::ABSTAIN
;
1789 case AuthenticationResponse
::REDIRECT
;
1790 case AuthenticationResponse
::UI
;
1791 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1792 'user' => $user->getName(),
1794 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1795 $state['primary'] = $id;
1796 $state['continueRequests'] = $res->neededRequests
;
1797 $session->setSecret( 'AuthManager::accountLinkState', $state );
1798 $session->persist();
1801 // @codeCoverageIgnoreStart
1803 throw new \
DomainException(
1804 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1806 // @codeCoverageIgnoreEnd
1810 $this->logger
->debug( __METHOD__
. ': Account linking failed because no provider accepted', [
1811 'user' => $user->getName(),
1813 $ret = AuthenticationResponse
::newFail(
1814 wfMessage( 'authmanager-link-no-primary' )
1816 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1821 * Continue an account linking flow
1822 * @param AuthenticationRequest[] $reqs
1823 * @return AuthenticationResponse
1825 public function continueAccountLink( array $reqs ) {
1826 $session = $this->request
->getSession();
1828 if ( !$this->canLinkAccounts() ) {
1829 // Caller should have called canLinkAccounts()
1830 $session->remove( 'AuthManager::accountLinkState' );
1831 throw new \
LogicException( 'Account linking is not possible' );
1834 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1835 if ( !is_array( $state ) ) {
1836 return AuthenticationResponse
::newFail(
1837 wfMessage( 'authmanager-link-not-in-progress' )
1840 $state['continueRequests'] = [];
1842 // Step 0: Prepare and validate the input
1844 $user = User
::newFromName( $state['username'], 'usable' );
1845 if ( !is_object( $user ) ) {
1846 $session->remove( 'AuthManager::accountLinkState' );
1847 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1849 if ( $user->getId() != $state['userid'] ) {
1850 throw new \
UnexpectedValueException(
1851 "User \"{$state['username']}\" is valid, but " .
1852 "ID {$user->getId()} != {$state['userid']}!"
1856 foreach ( $reqs as $req ) {
1857 $req->username
= $state['username'];
1858 $req->returnToUrl
= $state['returnToUrl'];
1861 // Step 1: Call the primary again until it succeeds
1863 $provider = $this->getAuthenticationProvider( $state['primary'] );
1864 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1865 // Configuration changed? Force them to start over.
1866 // @codeCoverageIgnoreStart
1867 $ret = AuthenticationResponse
::newFail(
1868 wfMessage( 'authmanager-link-not-in-progress' )
1870 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1871 $session->remove( 'AuthManager::accountLinkState' );
1873 // @codeCoverageIgnoreEnd
1875 $id = $provider->getUniqueId();
1876 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1877 switch ( $res->status
) {
1878 case AuthenticationResponse
::PASS
;
1879 $this->logger
->info( "Account linked to {user} by $id", [
1880 'user' => $user->getName(),
1882 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1883 $session->remove( 'AuthManager::accountLinkState' );
1885 case AuthenticationResponse
::FAIL
;
1886 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1887 'user' => $user->getName(),
1889 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1890 $session->remove( 'AuthManager::accountLinkState' );
1892 case AuthenticationResponse
::REDIRECT
;
1893 case AuthenticationResponse
::UI
;
1894 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1895 'user' => $user->getName(),
1897 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1898 $state['continueRequests'] = $res->neededRequests
;
1899 $session->setSecret( 'AuthManager::accountLinkState', $state );
1902 throw new \
DomainException(
1903 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1906 } catch ( \Exception
$ex ) {
1907 $session->remove( 'AuthManager::accountLinkState' );
1915 * @name Information methods
1920 * Return the applicable list of AuthenticationRequests
1922 * Possible values for $action:
1923 * - ACTION_LOGIN: Valid for passing to beginAuthentication
1924 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
1925 * - ACTION_CREATE: Valid for passing to beginAccountCreation
1926 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
1927 * - ACTION_LINK: Valid for passing to beginAccountLink
1928 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
1929 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
1930 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
1931 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
1933 * @param string $action One of the AuthManager::ACTION_* constants
1934 * @param User|null $user User being acted on, instead of the current user.
1935 * @return AuthenticationRequest[]
1937 public function getAuthenticationRequests( $action, User
$user = null ) {
1939 $providerAction = $action;
1941 // Figure out which providers to query
1942 switch ( $action ) {
1943 case self
::ACTION_LOGIN
:
1944 case self
::ACTION_CREATE
:
1945 $providers = $this->getPreAuthenticationProviders() +
1946 $this->getPrimaryAuthenticationProviders() +
1947 $this->getSecondaryAuthenticationProviders();
1950 case self
::ACTION_LOGIN_CONTINUE
:
1951 $state = $this->request
->getSession()->getSecret( 'AuthManager::authnState' );
1952 return is_array( $state ) ?
$state['continueRequests'] : [];
1954 case self
::ACTION_CREATE_CONTINUE
:
1955 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountCreationState' );
1956 return is_array( $state ) ?
$state['continueRequests'] : [];
1958 case self
::ACTION_LINK
:
1959 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
1960 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
1964 case self
::ACTION_UNLINK
:
1965 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
1966 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
1969 // To providers, unlink and remove are identical.
1970 $providerAction = self
::ACTION_REMOVE
;
1973 case self
::ACTION_LINK_CONTINUE
:
1974 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountLinkState' );
1975 return is_array( $state ) ?
$state['continueRequests'] : [];
1977 case self
::ACTION_CHANGE
:
1978 case self
::ACTION_REMOVE
:
1979 $providers = $this->getPrimaryAuthenticationProviders() +
1980 $this->getSecondaryAuthenticationProviders();
1983 // @codeCoverageIgnoreStart
1985 throw new \
DomainException( __METHOD__
. ": Invalid action \"$action\"" );
1987 // @codeCoverageIgnoreEnd
1989 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
1993 * Internal request lookup for self::getAuthenticationRequests
1995 * @param string $providerAction Action to pass to providers
1996 * @param array $options Options to pass to providers
1997 * @param AuthenticationProvider[] $providers
1998 * @param User|null $user
1999 * @return AuthenticationRequest[]
2001 private function getAuthenticationRequestsInternal(
2002 $providerAction, array $options, array $providers, User
$user = null
2004 $user = $user ?
: \RequestContext
::getMain()->getUser();
2005 $options['username'] = $user->isAnon() ?
null : $user->getName();
2007 // Query them and merge results
2009 $allPrimaryRequired = null;
2010 foreach ( $providers as $provider ) {
2011 $isPrimary = $provider instanceof PrimaryAuthenticationProvider
;
2013 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2014 $id = $req->getUniqueId();
2016 // If it's from a Primary, mark it as "primary-required" but
2017 // track it for later.
2019 if ( $req->required
) {
2020 $thisRequired[$id] = true;
2021 $req->required
= AuthenticationRequest
::PRIMARY_REQUIRED
;
2025 if ( !isset( $reqs[$id] ) ||
$req->required
=== AuthenticationRequest
::REQUIRED
) {
2030 // Track which requests are required by all primaries
2032 $allPrimaryRequired = $allPrimaryRequired === null
2034 : array_intersect_key( $allPrimaryRequired, $thisRequired );
2037 // Any requests that were required by all primaries are required.
2038 foreach ( (array)$allPrimaryRequired as $id => $dummy ) {
2039 $reqs[$id]->required
= AuthenticationRequest
::REQUIRED
;
2042 // AuthManager has its own req for some actions
2043 switch ( $providerAction ) {
2044 case self
::ACTION_LOGIN
:
2045 $reqs[] = new RememberMeAuthenticationRequest
;
2048 case self
::ACTION_CREATE
:
2049 $reqs[] = new UsernameAuthenticationRequest
;
2050 $reqs[] = new UserDataAuthenticationRequest
;
2051 if ( $options['username'] !== null ) {
2052 $reqs[] = new CreationReasonAuthenticationRequest
;
2053 $options['username'] = null; // Don't fill in the username below
2058 // Fill in reqs data
2059 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2061 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2062 if ( $providerAction === self
::ACTION_CHANGE ||
$providerAction === self
::ACTION_REMOVE
) {
2063 $reqs = array_filter( $reqs, function ( $req ) {
2064 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2068 return array_values( $reqs );
2072 * Set values in an array of requests
2073 * @param AuthenticationRequest[] &$reqs
2074 * @param string $action
2075 * @param string|null $username
2076 * @param boolean $forceAction
2078 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2079 foreach ( $reqs as $req ) {
2080 if ( !$req->action ||
$forceAction ) {
2081 $req->action
= $action;
2083 if ( $req->username
=== null ) {
2084 $req->username
= $username;
2090 * Determine whether a username exists
2091 * @param string $username
2092 * @param int $flags Bitfield of User:READ_* constants
2095 public function userExists( $username, $flags = User
::READ_NORMAL
) {
2096 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2097 if ( $provider->testUserExists( $username, $flags ) ) {
2106 * Determine whether a user property should be allowed to be changed.
2108 * Supported properties are:
2113 * @param string $property
2116 public function allowsPropertyChange( $property ) {
2117 $providers = $this->getPrimaryAuthenticationProviders() +
2118 $this->getSecondaryAuthenticationProviders();
2119 foreach ( $providers as $provider ) {
2120 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2128 * Get a provider by ID
2129 * @note This is public so extensions can check whether their own provider
2130 * is installed and so they can read its configuration if necessary.
2131 * Other uses are not recommended.
2133 * @return AuthenticationProvider|null
2135 public function getAuthenticationProvider( $id ) {
2137 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2138 return $this->allAuthenticationProviders
[$id];
2141 // Slow version: instantiate each kind and check
2142 $providers = $this->getPrimaryAuthenticationProviders();
2143 if ( isset( $providers[$id] ) ) {
2144 return $providers[$id];
2146 $providers = $this->getSecondaryAuthenticationProviders();
2147 if ( isset( $providers[$id] ) ) {
2148 return $providers[$id];
2150 $providers = $this->getPreAuthenticationProviders();
2151 if ( isset( $providers[$id] ) ) {
2152 return $providers[$id];
2161 * @name Internal methods
2166 * Store authentication in the current session
2167 * @protected For use by AuthenticationProviders
2168 * @param string $key
2169 * @param mixed $data Must be serializable
2171 public function setAuthenticationSessionData( $key, $data ) {
2172 $session = $this->request
->getSession();
2173 $arr = $session->getSecret( 'authData' );
2174 if ( !is_array( $arr ) ) {
2178 $session->setSecret( 'authData', $arr );
2182 * Fetch authentication data from the current session
2183 * @protected For use by AuthenticationProviders
2184 * @param string $key
2185 * @param mixed $default
2188 public function getAuthenticationSessionData( $key, $default = null ) {
2189 $arr = $this->request
->getSession()->getSecret( 'authData' );
2190 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2198 * Remove authentication data
2199 * @protected For use by AuthenticationProviders
2200 * @param string|null $key If null, all data is removed
2202 public function removeAuthenticationSessionData( $key ) {
2203 $session = $this->request
->getSession();
2204 if ( $key === null ) {
2205 $session->remove( 'authData' );
2207 $arr = $session->getSecret( 'authData' );
2208 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2209 unset( $arr[$key] );
2210 $session->setSecret( 'authData', $arr );
2216 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2217 * @param string $class
2218 * @param array[] $specs
2219 * @return AuthenticationProvider[]
2221 protected function providerArrayFromSpecs( $class, array $specs ) {
2223 foreach ( $specs as &$spec ) {
2224 $spec = [ 'sort2' => $i++
] +
$spec +
[ 'sort' => 0 ];
2227 usort( $specs, function ( $a, $b ) {
2228 return ( (int)$a['sort'] ) - ( (int)$b['sort'] )
2229 ?
: $a['sort2'] - $b['sort2'];
2233 foreach ( $specs as $spec ) {
2234 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
2235 if ( !$provider instanceof $class ) {
2236 throw new \
RuntimeException(
2237 "Expected instance of $class, got " . get_class( $provider )
2240 $provider->setLogger( $this->logger
);
2241 $provider->setManager( $this );
2242 $provider->setConfig( $this->config
);
2243 $id = $provider->getUniqueId();
2244 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2245 throw new \
RuntimeException(
2246 "Duplicate specifications for id $id (classes " .
2247 get_class( $provider ) . ' and ' .
2248 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
2251 $this->allAuthenticationProviders
[$id] = $provider;
2252 $ret[$id] = $provider;
2258 * Get the configuration
2261 private function getConfiguration() {
2262 return $this->config
->get( 'AuthManagerConfig' ) ?
: $this->config
->get( 'AuthManagerAutoConfig' );
2266 * Get the list of PreAuthenticationProviders
2267 * @return PreAuthenticationProvider[]
2269 protected function getPreAuthenticationProviders() {
2270 if ( $this->preAuthenticationProviders
=== null ) {
2271 $conf = $this->getConfiguration();
2272 $this->preAuthenticationProviders
= $this->providerArrayFromSpecs(
2273 PreAuthenticationProvider
::class, $conf['preauth']
2276 return $this->preAuthenticationProviders
;
2280 * Get the list of PrimaryAuthenticationProviders
2281 * @return PrimaryAuthenticationProvider[]
2283 protected function getPrimaryAuthenticationProviders() {
2284 if ( $this->primaryAuthenticationProviders
=== null ) {
2285 $conf = $this->getConfiguration();
2286 $this->primaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2287 PrimaryAuthenticationProvider
::class, $conf['primaryauth']
2290 return $this->primaryAuthenticationProviders
;
2294 * Get the list of SecondaryAuthenticationProviders
2295 * @return SecondaryAuthenticationProvider[]
2297 protected function getSecondaryAuthenticationProviders() {
2298 if ( $this->secondaryAuthenticationProviders
=== null ) {
2299 $conf = $this->getConfiguration();
2300 $this->secondaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2301 SecondaryAuthenticationProvider
::class, $conf['secondaryauth']
2304 return $this->secondaryAuthenticationProviders
;
2309 * @param bool|null $remember
2311 private function setSessionDataForUser( $user, $remember = null ) {
2312 $session = $this->request
->getSession();
2313 $delay = $session->delaySave();
2315 $session->resetId();
2316 $session->resetAllTokens();
2317 if ( $session->canSetUser() ) {
2318 $session->setUser( $user );
2320 if ( $remember !== null ) {
2321 $session->setRememberUser( $remember );
2323 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2324 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2325 $session->persist();
2327 \ScopedCallback
::consume( $delay );
2329 \Hooks
::run( 'UserLoggedIn', [ $user ] );
2334 * @param bool $useContextLang Use 'uselang' to set the user's language
2336 private function setDefaultUserOptions( User
$user, $useContextLang ) {
2341 $lang = $useContextLang ? \RequestContext
::getMain()->getLanguage() : $wgContLang;
2342 $user->setOption( 'language', $lang->getPreferredVariant() );
2344 if ( $wgContLang->hasVariants() ) {
2345 $user->setOption( 'variant', $wgContLang->getPreferredVariant() );
2350 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2351 * @param string $method
2352 * @param array $args
2354 private function callMethodOnProviders( $which, $method, array $args ) {
2357 $providers +
= $this->getPreAuthenticationProviders();
2360 $providers +
= $this->getPrimaryAuthenticationProviders();
2363 $providers +
= $this->getSecondaryAuthenticationProviders();
2365 foreach ( $providers as $provider ) {
2366 call_user_func_array( [ $provider, $method ], $args );
2371 * Reset the internal caching for unit testing
2373 public static function resetCache() {
2374 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2375 // @codeCoverageIgnoreStart
2376 throw new \
MWException( __METHOD__
. ' may only be called from unit tests!' );
2377 // @codeCoverageIgnoreEnd
2380 self
::$instance = null;
2388 * For really cool vim folding this needs to be at the end:
2389 * vim: foldmarker=@{,@} foldmethod=marker