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 if ( self
::$instance === null ) {
109 self
::$instance = new self(
110 \RequestContext
::getMain()->getRequest(),
111 \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' )
114 return self
::$instance;
118 * @param WebRequest $request
119 * @param Config $config
121 public function __construct( WebRequest
$request, Config
$config ) {
122 $this->request
= $request;
123 $this->config
= $config;
124 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' ) );
128 * @param LoggerInterface $logger
130 public function setLogger( LoggerInterface
$logger ) {
131 $this->logger
= $logger;
137 public function getRequest() {
138 return $this->request
;
142 * Force certain PrimaryAuthenticationProviders
143 * @deprecated For backwards compatibility only
144 * @param PrimaryAuthenticationProvider[] $providers
147 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
148 $this->logger
->warning( "Overriding AuthManager primary authn because $why" );
150 if ( $this->primaryAuthenticationProviders
!== null ) {
151 $this->logger
->warning(
152 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
155 $this->allAuthenticationProviders
= array_diff_key(
156 $this->allAuthenticationProviders
,
157 $this->primaryAuthenticationProviders
159 $session = $this->request
->getSession();
160 $session->remove( 'AuthManager::authnState' );
161 $session->remove( 'AuthManager::accountCreationState' );
162 $session->remove( 'AuthManager::accountLinkState' );
163 $this->createdAccountAuthenticationRequests
= [];
166 $this->primaryAuthenticationProviders
= [];
167 foreach ( $providers as $provider ) {
168 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
169 throw new \
RuntimeException(
170 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
171 get_class( $provider )
174 $provider->setLogger( $this->logger
);
175 $provider->setManager( $this );
176 $provider->setConfig( $this->config
);
177 $id = $provider->getUniqueId();
178 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
179 throw new \
RuntimeException(
180 "Duplicate specifications for id $id (classes " .
181 get_class( $provider ) . ' and ' .
182 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
185 $this->allAuthenticationProviders
[$id] = $provider;
186 $this->primaryAuthenticationProviders
[$id] = $provider;
191 * Call a legacy AuthPlugin method, if necessary
192 * @codeCoverageIgnore
193 * @deprecated For backwards compatibility only, should be avoided in new code
194 * @param string $method AuthPlugin method to call
195 * @param array $params Parameters to pass
196 * @param mixed $return Return value if AuthPlugin wasn't called
197 * @return mixed Return value from the AuthPlugin method, or $return
199 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
202 if ( $wgAuth && !$wgAuth instanceof AuthManagerAuthPlugin
) {
203 return call_user_func_array( [ $wgAuth, $method ], $params );
210 * @name Authentication
215 * Indicate whether user authentication is possible
217 * It may not be if the session is provided by something like OAuth
218 * for which each individual request includes authentication data.
222 public function canAuthenticateNow() {
223 return $this->request
->getSession()->canSetUser();
227 * Start an authentication flow
229 * In addition to the AuthenticationRequests returned by
230 * $this->getAuthenticationRequests(), a client might include a
231 * CreateFromLoginAuthenticationRequest from a previous login attempt to
234 * Instead of the AuthenticationRequests returned by
235 * $this->getAuthenticationRequests(), a client might pass a
236 * CreatedAccountAuthenticationRequest from an account creation that just
237 * succeeded to log in to the just-created account.
239 * @param AuthenticationRequest[] $reqs
240 * @param string $returnToUrl Url that REDIRECT responses should eventually
242 * @return AuthenticationResponse See self::continueAuthentication()
244 public function beginAuthentication( array $reqs, $returnToUrl ) {
245 $session = $this->request
->getSession();
246 if ( !$session->canSetUser() ) {
247 // Caller should have called canAuthenticateNow()
248 $session->remove( 'AuthManager::authnState' );
249 throw new \
LogicException( 'Authentication is not possible now' );
252 $guessUserName = null;
253 foreach ( $reqs as $req ) {
254 $req->returnToUrl
= $returnToUrl;
255 // @codeCoverageIgnoreStart
256 if ( $req->username
!== null && $req->username
!== '' ) {
257 if ( $guessUserName === null ) {
258 $guessUserName = $req->username
;
259 } elseif ( $guessUserName !== $req->username
) {
260 $guessUserName = null;
264 // @codeCoverageIgnoreEnd
267 // Check for special-case login of a just-created account
268 $req = AuthenticationRequest
::getRequestByClass(
269 $reqs, CreatedAccountAuthenticationRequest
::class
272 if ( !in_array( $req, $this->createdAccountAuthenticationRequests
, true ) ) {
273 throw new \
LogicException(
274 'CreatedAccountAuthenticationRequests are only valid on ' .
275 'the same AuthManager that created the account'
279 $user = User
::newFromName( $req->username
);
280 // @codeCoverageIgnoreStart
282 throw new \
UnexpectedValueException(
283 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
285 } elseif ( $user->getId() != $req->id
) {
286 throw new \
UnexpectedValueException(
287 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
290 // @codeCoverageIgnoreEnd
292 $this->logger
->info( 'Logging in {user} after account creation', [
293 'user' => $user->getName(),
295 $ret = AuthenticationResponse
::newPass( $user->getName() );
296 $this->setSessionDataForUser( $user );
297 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
298 $session->remove( 'AuthManager::authnState' );
299 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
303 $this->removeAuthenticationSessionData( null );
305 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
306 $status = $provider->testForAuthentication( $reqs );
307 if ( !$status->isGood() ) {
308 $this->logger
->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
309 $ret = AuthenticationResponse
::newFail(
310 Status
::wrap( $status )->getMessage()
312 $this->callMethodOnProviders( 7, 'postAuthentication',
313 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
315 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName ] );
322 'returnToUrl' => $returnToUrl,
323 'guessUserName' => $guessUserName,
325 'primaryResponse' => null,
328 'continueRequests' => [],
331 // Preserve state from a previous failed login
332 $req = AuthenticationRequest
::getRequestByClass(
333 $reqs, CreateFromLoginAuthenticationRequest
::class
336 $state['maybeLink'] = $req->maybeLink
;
339 $session = $this->request
->getSession();
340 $session->setSecret( 'AuthManager::authnState', $state );
343 return $this->continueAuthentication( $reqs );
347 * Continue an authentication flow
349 * Return values are interpreted as follows:
350 * - status FAIL: Authentication failed. If $response->createRequest is
351 * set, that may be passed to self::beginAuthentication() or to
352 * self::beginAccountCreation() to preserve state.
353 * - status REDIRECT: The client should be redirected to the contained URL,
354 * new AuthenticationRequests should be made (if any), then
355 * AuthManager::continueAuthentication() should be called.
356 * - status UI: The client should be presented with a user interface for
357 * the fields in the specified AuthenticationRequests, then new
358 * AuthenticationRequests should be made, then
359 * AuthManager::continueAuthentication() should be called.
360 * - status RESTART: The user logged in successfully with a third-party
361 * service, but the third-party credentials aren't attached to any local
362 * account. This could be treated as a UI or a FAIL.
363 * - status PASS: Authentication was successful.
365 * @param AuthenticationRequest[] $reqs
366 * @return AuthenticationResponse
368 public function continueAuthentication( array $reqs ) {
369 $session = $this->request
->getSession();
371 if ( !$session->canSetUser() ) {
372 // Caller should have called canAuthenticateNow()
373 // @codeCoverageIgnoreStart
374 throw new \
LogicException( 'Authentication is not possible now' );
375 // @codeCoverageIgnoreEnd
378 $state = $session->getSecret( 'AuthManager::authnState' );
379 if ( !is_array( $state ) ) {
380 return AuthenticationResponse
::newFail(
381 wfMessage( 'authmanager-authn-not-in-progress' )
384 $state['continueRequests'] = [];
386 $guessUserName = $state['guessUserName'];
388 foreach ( $reqs as $req ) {
389 $req->returnToUrl
= $state['returnToUrl'];
392 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
394 if ( $state['primary'] === null ) {
395 // We haven't picked a PrimaryAuthenticationProvider yet
396 // @codeCoverageIgnoreStart
397 $guessUserName = null;
398 foreach ( $reqs as $req ) {
399 if ( $req->username
!== null && $req->username
!== '' ) {
400 if ( $guessUserName === null ) {
401 $guessUserName = $req->username
;
402 } elseif ( $guessUserName !== $req->username
) {
403 $guessUserName = null;
408 $state['guessUserName'] = $guessUserName;
409 // @codeCoverageIgnoreEnd
410 $state['reqs'] = $reqs;
412 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
413 $res = $provider->beginPrimaryAuthentication( $reqs );
414 switch ( $res->status
) {
415 case AuthenticationResponse
::PASS
;
416 $state['primary'] = $id;
417 $state['primaryResponse'] = $res;
418 $this->logger
->debug( "Primary login with $id succeeded" );
420 case AuthenticationResponse
::FAIL
;
421 $this->logger
->debug( "Login failed in primary authentication by $id" );
422 if ( $res->createRequest ||
$state['maybeLink'] ) {
423 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
424 $res->createRequest
, $state['maybeLink']
427 $this->callMethodOnProviders( 7, 'postAuthentication',
428 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
430 $session->remove( 'AuthManager::authnState' );
431 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
433 case AuthenticationResponse
::ABSTAIN
;
436 case AuthenticationResponse
::REDIRECT
;
437 case AuthenticationResponse
::UI
;
438 $this->logger
->debug( "Primary login with $id returned $res->status" );
439 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
440 $state['primary'] = $id;
441 $state['continueRequests'] = $res->neededRequests
;
442 $session->setSecret( 'AuthManager::authnState', $state );
445 // @codeCoverageIgnoreStart
447 throw new \
DomainException(
448 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
450 // @codeCoverageIgnoreEnd
453 if ( $state['primary'] === null ) {
454 $this->logger
->debug( 'Login failed in primary authentication because no provider accepted' );
455 $ret = AuthenticationResponse
::newFail(
456 wfMessage( 'authmanager-authn-no-primary' )
458 $this->callMethodOnProviders( 7, 'postAuthentication',
459 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
461 $session->remove( 'AuthManager::authnState' );
464 } elseif ( $state['primaryResponse'] === null ) {
465 $provider = $this->getAuthenticationProvider( $state['primary'] );
466 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
467 // Configuration changed? Force them to start over.
468 // @codeCoverageIgnoreStart
469 $ret = AuthenticationResponse
::newFail(
470 wfMessage( 'authmanager-authn-not-in-progress' )
472 $this->callMethodOnProviders( 7, 'postAuthentication',
473 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
475 $session->remove( 'AuthManager::authnState' );
477 // @codeCoverageIgnoreEnd
479 $id = $provider->getUniqueId();
480 $res = $provider->continuePrimaryAuthentication( $reqs );
481 switch ( $res->status
) {
482 case AuthenticationResponse
::PASS
;
483 $state['primaryResponse'] = $res;
484 $this->logger
->debug( "Primary login with $id succeeded" );
486 case AuthenticationResponse
::FAIL
;
487 $this->logger
->debug( "Login failed in primary authentication by $id" );
488 if ( $res->createRequest ||
$state['maybeLink'] ) {
489 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
490 $res->createRequest
, $state['maybeLink']
493 $this->callMethodOnProviders( 7, 'postAuthentication',
494 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
496 $session->remove( 'AuthManager::authnState' );
497 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
499 case AuthenticationResponse
::REDIRECT
;
500 case AuthenticationResponse
::UI
;
501 $this->logger
->debug( "Primary login with $id returned $res->status" );
502 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
503 $state['continueRequests'] = $res->neededRequests
;
504 $session->setSecret( 'AuthManager::authnState', $state );
507 throw new \
DomainException(
508 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
513 $res = $state['primaryResponse'];
514 if ( $res->username
=== null ) {
515 $provider = $this->getAuthenticationProvider( $state['primary'] );
516 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
517 // Configuration changed? Force them to start over.
518 // @codeCoverageIgnoreStart
519 $ret = AuthenticationResponse
::newFail(
520 wfMessage( 'authmanager-authn-not-in-progress' )
522 $this->callMethodOnProviders( 7, 'postAuthentication',
523 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
525 $session->remove( 'AuthManager::authnState' );
527 // @codeCoverageIgnoreEnd
530 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
&&
532 // don't confuse the user with an incorrect message if linking is disabled
533 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider
::class )
535 $state['maybeLink'][$res->linkRequest
->getUniqueId()] = $res->linkRequest
;
536 $msg = 'authmanager-authn-no-local-user-link';
538 $msg = 'authmanager-authn-no-local-user';
540 $this->logger
->debug(
541 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
543 $ret = AuthenticationResponse
::newRestart( wfMessage( $msg ) );
544 $ret->neededRequests
= $this->getAuthenticationRequestsInternal(
547 $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders()
549 if ( $res->createRequest ||
$state['maybeLink'] ) {
550 $ret->createRequest
= new CreateFromLoginAuthenticationRequest(
551 $res->createRequest
, $state['maybeLink']
553 $ret->neededRequests
[] = $ret->createRequest
;
555 $this->fillRequests( $ret->neededRequests
, self
::ACTION_LOGIN
, null, true );
556 $session->setSecret( 'AuthManager::authnState', [
557 'reqs' => [], // Will be filled in later
559 'primaryResponse' => null,
561 'continueRequests' => $ret->neededRequests
,
566 // Step 2: Primary authentication succeeded, create the User object
567 // (and add the user locally if necessary)
569 $user = User
::newFromName( $res->username
, 'usable' );
571 throw new \
DomainException(
572 get_class( $provider ) . " returned an invalid username: {$res->username}"
575 if ( $user->getId() === 0 ) {
576 // User doesn't exist locally. Create it.
577 $this->logger
->info( 'Auto-creating {user} on login', [
578 'user' => $user->getName(),
580 $status = $this->autoCreateUser( $user, $state['primary'], false );
581 if ( !$status->isGood() ) {
582 $ret = AuthenticationResponse
::newFail(
583 Status
::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
585 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
586 $session->remove( 'AuthManager::authnState' );
587 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
592 // Step 3: Iterate over all the secondary authentication providers.
594 $beginReqs = $state['reqs'];
596 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
597 if ( !isset( $state['secondary'][$id] ) ) {
598 // This provider isn't started yet, so we pass it the set
599 // of reqs from beginAuthentication instead of whatever
600 // might have been used by a previous provider in line.
601 $func = 'beginSecondaryAuthentication';
602 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
603 } elseif ( !$state['secondary'][$id] ) {
604 $func = 'continueSecondaryAuthentication';
605 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
609 switch ( $res->status
) {
610 case AuthenticationResponse
::PASS
;
611 $this->logger
->debug( "Secondary login with $id succeeded" );
613 case AuthenticationResponse
::ABSTAIN
;
614 $state['secondary'][$id] = true;
616 case AuthenticationResponse
::FAIL
;
617 $this->logger
->debug( "Login failed in secondary authentication by $id" );
618 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
619 $session->remove( 'AuthManager::authnState' );
620 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName() ] );
622 case AuthenticationResponse
::REDIRECT
;
623 case AuthenticationResponse
::UI
;
624 $this->logger
->debug( "Secondary login with $id returned " . $res->status
);
625 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $user->getName() );
626 $state['secondary'][$id] = false;
627 $state['continueRequests'] = $res->neededRequests
;
628 $session->setSecret( 'AuthManager::authnState', $state );
631 // @codeCoverageIgnoreStart
633 throw new \
DomainException(
634 get_class( $provider ) . "::{$func}() returned $res->status"
636 // @codeCoverageIgnoreEnd
640 // Step 4: Authentication complete! Set the user in the session and
643 $this->logger
->info( 'Login for {user} succeeded', [
644 'user' => $user->getName(),
646 $req = AuthenticationRequest
::getRequestByClass(
647 $beginReqs, RememberMeAuthenticationRequest
::class
649 $this->setSessionDataForUser( $user, $req && $req->rememberMe
);
650 $ret = AuthenticationResponse
::newPass( $user->getName() );
651 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
652 $session->remove( 'AuthManager::authnState' );
653 $this->removeAuthenticationSessionData( null );
654 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
656 } catch ( \Exception
$ex ) {
657 $session->remove( 'AuthManager::authnState' );
663 * Whether security-sensitive operations should proceed.
665 * A "security-sensitive operation" is something like a password or email
666 * change, that would normally have a "reenter your password to confirm"
667 * box if we only supported password-based authentication.
669 * @param string $operation Operation being checked. This should be a
670 * message-key-like string such as 'change-password' or 'change-email'.
671 * @return string One of the SEC_* constants.
673 public function securitySensitiveOperationStatus( $operation ) {
674 $status = self
::SEC_OK
;
676 $this->logger
->debug( __METHOD__
. ": Checking $operation" );
678 $session = $this->request
->getSession();
679 $aId = $session->getUser()->getId();
681 // User isn't authenticated. DWIM?
682 $status = $this->canAuthenticateNow() ? self
::SEC_REAUTH
: self
::SEC_FAIL
;
683 $this->logger
->info( __METHOD__
. ": Not logged in! $operation is $status" );
687 if ( $session->canSetUser() ) {
688 $id = $session->get( 'AuthManager:lastAuthId' );
689 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
690 if ( $id !== $aId ||
$last === null ) {
691 $timeSinceLogin = PHP_INT_MAX
; // Forever ago
693 $timeSinceLogin = max( 0, time() - $last );
696 $thresholds = $this->config
->get( 'ReauthenticateTime' );
697 if ( isset( $thresholds[$operation] ) ) {
698 $threshold = $thresholds[$operation];
699 } elseif ( isset( $thresholds['default'] ) ) {
700 $threshold = $thresholds['default'];
702 throw new \
UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
705 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
706 $status = self
::SEC_REAUTH
;
709 $timeSinceLogin = -1;
711 $pass = $this->config
->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
712 if ( isset( $pass[$operation] ) ) {
713 $status = $pass[$operation] ? self
::SEC_OK
: self
::SEC_FAIL
;
714 } elseif ( isset( $pass['default'] ) ) {
715 $status = $pass['default'] ? self
::SEC_OK
: self
::SEC_FAIL
;
717 throw new \
UnexpectedValueException(
718 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
723 \Hooks
::run( 'SecuritySensitiveOperationStatus', [
724 &$status, $operation, $session, $timeSinceLogin
727 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
728 if ( !$this->canAuthenticateNow() && $status === self
::SEC_REAUTH
) {
729 $status = self
::SEC_FAIL
;
732 $this->logger
->info( __METHOD__
. ": $operation is $status" );
738 * Determine whether a username can authenticate
740 * @param string $username
743 public function userCanAuthenticate( $username ) {
744 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
745 if ( $provider->testUserCanAuthenticate( $username ) ) {
753 * Provide normalized versions of the username for security checks
755 * Since different providers can normalize the input in different ways,
756 * this returns an array of all the different ways the name might be
757 * normalized for authentication.
759 * The returned strings should not be revealed to the user, as that might
760 * leak private information (e.g. an email address might be normalized to a
763 * @param string $username
766 public function normalizeUsername( $username ) {
768 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
769 $normalized = $provider->providerNormalizeUsername( $username );
770 if ( $normalized !== null ) {
771 $ret[$normalized] = true;
774 return array_keys( $ret );
780 * @name Authentication data changing
785 * Revoke any authentication credentials for a user
787 * After this, the user should no longer be able to log in.
789 * @param string $username
791 public function revokeAccessForUser( $username ) {
792 $this->logger
->info( 'Revoking access for {user}', [
795 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
799 * Validate a change of authentication data (e.g. passwords)
800 * @param AuthenticationRequest $req
801 * @param bool $checkData If false, $req hasn't been loaded from the
802 * submission so checks on user-submitted fields should be skipped. $req->username is
803 * considered user-submitted for this purpose, even if it cannot be changed via
804 * $req->loadFromSubmission.
807 public function allowsAuthenticationDataChange( AuthenticationRequest
$req, $checkData = true ) {
809 $providers = $this->getPrimaryAuthenticationProviders() +
810 $this->getSecondaryAuthenticationProviders();
811 foreach ( $providers as $provider ) {
812 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
813 if ( !$status->isGood() ) {
814 return Status
::wrap( $status );
816 $any = $any ||
$status->value
!== 'ignored';
819 $status = Status
::newGood( 'ignored' );
820 $status->warning( 'authmanager-change-not-supported' );
823 return Status
::newGood();
827 * Change authentication data (e.g. passwords)
829 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
830 * result in a successful login in the future.
832 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
833 * no longer result in a successful login.
835 * @param AuthenticationRequest $req
837 public function changeAuthenticationData( AuthenticationRequest
$req ) {
838 $this->logger
->info( 'Changing authentication data for {user} class {what}', [
839 'user' => is_string( $req->username
) ?
$req->username
: '<no name>',
840 'what' => get_class( $req ),
843 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
845 // When the main account's authentication data is changed, invalidate
846 // all BotPasswords too.
847 \BotPassword
::invalidateAllPasswordsForUser( $req->username
);
853 * @name Account creation
858 * Determine whether accounts can be created
861 public function canCreateAccounts() {
862 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
863 switch ( $provider->accountCreationType() ) {
864 case PrimaryAuthenticationProvider
::TYPE_CREATE
:
865 case PrimaryAuthenticationProvider
::TYPE_LINK
:
873 * Determine whether a particular account can be created
874 * @param string $username
875 * @param array $options
876 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
877 * - creating: (bool) For internal use only. Never specify this.
880 public function canCreateAccount( $username, $options = [] ) {
882 if ( is_int( $options ) ) {
883 $options = [ 'flags' => $options ];
886 'flags' => User
::READ_NORMAL
,
889 $flags = $options['flags'];
891 if ( !$this->canCreateAccounts() ) {
892 return Status
::newFatal( 'authmanager-create-disabled' );
895 if ( $this->userExists( $username, $flags ) ) {
896 return Status
::newFatal( 'userexists' );
899 $user = User
::newFromName( $username, 'creatable' );
900 if ( !is_object( $user ) ) {
901 return Status
::newFatal( 'noname' );
903 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
904 if ( $user->getId() !== 0 ) {
905 return Status
::newFatal( 'userexists' );
909 // Denied by providers?
910 $providers = $this->getPreAuthenticationProviders() +
911 $this->getPrimaryAuthenticationProviders() +
912 $this->getSecondaryAuthenticationProviders();
913 foreach ( $providers as $provider ) {
914 $status = $provider->testUserForCreation( $user, false, $options );
915 if ( !$status->isGood() ) {
916 return Status
::wrap( $status );
920 return Status
::newGood();
924 * Basic permissions checks on whether a user can create accounts
925 * @param User $creator User doing the account creation
928 public function checkAccountCreatePermissions( User
$creator ) {
929 // Wiki is read-only?
930 if ( wfReadOnly() ) {
931 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
934 // This is awful, this permission check really shouldn't go through Title.
935 $permErrors = \SpecialPage
::getTitleFor( 'CreateAccount' )
936 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
938 $status = Status
::newGood();
939 foreach ( $permErrors as $args ) {
940 call_user_func_array( [ $status, 'fatal' ], $args );
945 $block = $creator->isBlockedFromCreateAccount();
949 $block->mReason ?
: wfMessage( 'blockednoreason' )->text(),
953 if ( $block->getType() === \Block
::TYPE_RANGE
) {
954 $errorMessage = 'cantcreateaccount-range-text';
955 $errorParams[] = $this->getRequest()->getIP();
957 $errorMessage = 'cantcreateaccount-text';
960 return Status
::newFatal( wfMessage( $errorMessage, $errorParams ) );
963 $ip = $this->getRequest()->getIP();
964 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
965 return Status
::newFatal( 'sorbs_create_account_reason' );
968 return Status
::newGood();
972 * Start an account creation flow
974 * In addition to the AuthenticationRequests returned by
975 * $this->getAuthenticationRequests(), a client might include a
976 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
978 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
980 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
981 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
982 * username set, that username must be used for all other requests.
984 * @param User $creator User doing the account creation
985 * @param AuthenticationRequest[] $reqs
986 * @param string $returnToUrl Url that REDIRECT responses should eventually
988 * @return AuthenticationResponse
990 public function beginAccountCreation( User
$creator, array $reqs, $returnToUrl ) {
991 $session = $this->request
->getSession();
992 if ( !$this->canCreateAccounts() ) {
993 // Caller should have called canCreateAccounts()
994 $session->remove( 'AuthManager::accountCreationState' );
995 throw new \
LogicException( 'Account creation is not possible' );
999 $username = AuthenticationRequest
::getUsernameFromRequests( $reqs );
1000 } catch ( \UnexpectedValueException
$ex ) {
1003 if ( $username === null ) {
1004 $this->logger
->debug( __METHOD__
. ': No username provided' );
1005 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1008 // Permissions check
1009 $status = $this->checkAccountCreatePermissions( $creator );
1010 if ( !$status->isGood() ) {
1011 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1012 'user' => $username,
1013 'creator' => $creator->getName(),
1014 'reason' => $status->getWikiText( null, null, 'en' )
1016 return AuthenticationResponse
::newFail( $status->getMessage() );
1019 $status = $this->canCreateAccount(
1020 $username, [ 'flags' => User
::READ_LOCKING
, 'creating' => true ]
1022 if ( !$status->isGood() ) {
1023 $this->logger
->debug( __METHOD__
. ': {user} cannot be created: {reason}', [
1024 'user' => $username,
1025 'creator' => $creator->getName(),
1026 'reason' => $status->getWikiText( null, null, 'en' )
1028 return AuthenticationResponse
::newFail( $status->getMessage() );
1031 $user = User
::newFromName( $username, 'creatable' );
1032 foreach ( $reqs as $req ) {
1033 $req->username
= $username;
1034 $req->returnToUrl
= $returnToUrl;
1035 if ( $req instanceof UserDataAuthenticationRequest
) {
1036 $status = $req->populateUser( $user );
1037 if ( !$status->isGood() ) {
1038 $status = Status
::wrap( $status );
1039 $session->remove( 'AuthManager::accountCreationState' );
1040 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1041 'user' => $user->getName(),
1042 'creator' => $creator->getName(),
1043 'reason' => $status->getWikiText( null, null, 'en' ),
1045 return AuthenticationResponse
::newFail( $status->getMessage() );
1050 $this->removeAuthenticationSessionData( null );
1053 'username' => $username,
1055 'creatorid' => $creator->getId(),
1056 'creatorname' => $creator->getName(),
1058 'returnToUrl' => $returnToUrl,
1060 'primaryResponse' => null,
1062 'continueRequests' => [],
1064 'ranPreTests' => false,
1067 // Special case: converting a login to an account creation
1068 $req = AuthenticationRequest
::getRequestByClass(
1069 $reqs, CreateFromLoginAuthenticationRequest
::class
1072 $state['maybeLink'] = $req->maybeLink
;
1074 if ( $req->createRequest
) {
1075 $reqs[] = $req->createRequest
;
1076 $state['reqs'][] = $req->createRequest
;
1080 $session->setSecret( 'AuthManager::accountCreationState', $state );
1081 $session->persist();
1083 return $this->continueAccountCreation( $reqs );
1087 * Continue an account creation flow
1088 * @param AuthenticationRequest[] $reqs
1089 * @return AuthenticationResponse
1091 public function continueAccountCreation( array $reqs ) {
1092 $session = $this->request
->getSession();
1094 if ( !$this->canCreateAccounts() ) {
1095 // Caller should have called canCreateAccounts()
1096 $session->remove( 'AuthManager::accountCreationState' );
1097 throw new \
LogicException( 'Account creation is not possible' );
1100 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1101 if ( !is_array( $state ) ) {
1102 return AuthenticationResponse
::newFail(
1103 wfMessage( 'authmanager-create-not-in-progress' )
1106 $state['continueRequests'] = [];
1108 // Step 0: Prepare and validate the input
1110 $user = User
::newFromName( $state['username'], 'creatable' );
1111 if ( !is_object( $user ) ) {
1112 $session->remove( 'AuthManager::accountCreationState' );
1113 $this->logger
->debug( __METHOD__
. ': Invalid username', [
1114 'user' => $state['username'],
1116 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1119 if ( $state['creatorid'] ) {
1120 $creator = User
::newFromId( $state['creatorid'] );
1122 $creator = new User
;
1123 $creator->setName( $state['creatorname'] );
1126 // Avoid account creation races on double submissions
1127 $cache = \ObjectCache
::getLocalClusterInstance();
1128 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1130 // Don't clear AuthManager::accountCreationState for this code
1131 // path because the process that won the race owns it.
1132 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1133 'user' => $user->getName(),
1134 'creator' => $creator->getName(),
1136 return AuthenticationResponse
::newFail( wfMessage( 'usernameinprogress' ) );
1139 // Permissions check
1140 $status = $this->checkAccountCreatePermissions( $creator );
1141 if ( !$status->isGood() ) {
1142 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1143 'user' => $user->getName(),
1144 'creator' => $creator->getName(),
1145 'reason' => $status->getWikiText( null, null, 'en' )
1147 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1148 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1149 $session->remove( 'AuthManager::accountCreationState' );
1153 // Load from master for existence check
1154 $user->load( User
::READ_LOCKING
);
1156 if ( $state['userid'] === 0 ) {
1157 if ( $user->getId() != 0 ) {
1158 $this->logger
->debug( __METHOD__
. ': User exists locally', [
1159 'user' => $user->getName(),
1160 'creator' => $creator->getName(),
1162 $ret = AuthenticationResponse
::newFail( wfMessage( 'userexists' ) );
1163 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1164 $session->remove( 'AuthManager::accountCreationState' );
1168 if ( $user->getId() == 0 ) {
1169 $this->logger
->debug( __METHOD__
. ': User does not exist locally when it should', [
1170 'user' => $user->getName(),
1171 'creator' => $creator->getName(),
1172 'expected_id' => $state['userid'],
1174 throw new \
UnexpectedValueException(
1175 "User \"{$state['username']}\" should exist now, but doesn't!"
1178 if ( $user->getId() != $state['userid'] ) {
1179 $this->logger
->debug( __METHOD__
. ': User ID/name mismatch', [
1180 'user' => $user->getName(),
1181 'creator' => $creator->getName(),
1182 'expected_id' => $state['userid'],
1183 'actual_id' => $user->getId(),
1185 throw new \
UnexpectedValueException(
1186 "User \"{$state['username']}\" exists, but " .
1187 "ID {$user->getId()} != {$state['userid']}!"
1191 foreach ( $state['reqs'] as $req ) {
1192 if ( $req instanceof UserDataAuthenticationRequest
) {
1193 $status = $req->populateUser( $user );
1194 if ( !$status->isGood() ) {
1195 // This should never happen...
1196 $status = Status
::wrap( $status );
1197 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1198 'user' => $user->getName(),
1199 'creator' => $creator->getName(),
1200 'reason' => $status->getWikiText( null, null, 'en' ),
1202 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1203 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1204 $session->remove( 'AuthManager::accountCreationState' );
1210 foreach ( $reqs as $req ) {
1211 $req->returnToUrl
= $state['returnToUrl'];
1212 $req->username
= $state['username'];
1215 // Run pre-creation tests, if we haven't already
1216 if ( !$state['ranPreTests'] ) {
1217 $providers = $this->getPreAuthenticationProviders() +
1218 $this->getPrimaryAuthenticationProviders() +
1219 $this->getSecondaryAuthenticationProviders();
1220 foreach ( $providers as $id => $provider ) {
1221 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1222 if ( !$status->isGood() ) {
1223 $this->logger
->debug( __METHOD__
. ": Fail in pre-authentication by $id", [
1224 'user' => $user->getName(),
1225 'creator' => $creator->getName(),
1227 $ret = AuthenticationResponse
::newFail(
1228 Status
::wrap( $status )->getMessage()
1230 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1231 $session->remove( 'AuthManager::accountCreationState' );
1236 $state['ranPreTests'] = true;
1239 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1241 if ( $state['primary'] === null ) {
1242 // We haven't picked a PrimaryAuthenticationProvider yet
1243 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1244 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_NONE
) {
1247 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1248 switch ( $res->status
) {
1249 case AuthenticationResponse
::PASS
;
1250 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1251 'user' => $user->getName(),
1252 'creator' => $creator->getName(),
1254 $state['primary'] = $id;
1255 $state['primaryResponse'] = $res;
1257 case AuthenticationResponse
::FAIL
;
1258 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1259 'user' => $user->getName(),
1260 'creator' => $creator->getName(),
1262 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1263 $session->remove( 'AuthManager::accountCreationState' );
1265 case AuthenticationResponse
::ABSTAIN
;
1268 case AuthenticationResponse
::REDIRECT
;
1269 case AuthenticationResponse
::UI
;
1270 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1271 'user' => $user->getName(),
1272 'creator' => $creator->getName(),
1274 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1275 $state['primary'] = $id;
1276 $state['continueRequests'] = $res->neededRequests
;
1277 $session->setSecret( 'AuthManager::accountCreationState', $state );
1280 // @codeCoverageIgnoreStart
1282 throw new \
DomainException(
1283 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1285 // @codeCoverageIgnoreEnd
1288 if ( $state['primary'] === null ) {
1289 $this->logger
->debug( __METHOD__
. ': Primary creation failed because no provider accepted', [
1290 'user' => $user->getName(),
1291 'creator' => $creator->getName(),
1293 $ret = AuthenticationResponse
::newFail(
1294 wfMessage( 'authmanager-create-no-primary' )
1296 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1297 $session->remove( 'AuthManager::accountCreationState' );
1300 } elseif ( $state['primaryResponse'] === null ) {
1301 $provider = $this->getAuthenticationProvider( $state['primary'] );
1302 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1303 // Configuration changed? Force them to start over.
1304 // @codeCoverageIgnoreStart
1305 $ret = AuthenticationResponse
::newFail(
1306 wfMessage( 'authmanager-create-not-in-progress' )
1308 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1309 $session->remove( 'AuthManager::accountCreationState' );
1311 // @codeCoverageIgnoreEnd
1313 $id = $provider->getUniqueId();
1314 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1315 switch ( $res->status
) {
1316 case AuthenticationResponse
::PASS
;
1317 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1318 'user' => $user->getName(),
1319 'creator' => $creator->getName(),
1321 $state['primaryResponse'] = $res;
1323 case AuthenticationResponse
::FAIL
;
1324 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1325 'user' => $user->getName(),
1326 'creator' => $creator->getName(),
1328 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1329 $session->remove( 'AuthManager::accountCreationState' );
1331 case AuthenticationResponse
::REDIRECT
;
1332 case AuthenticationResponse
::UI
;
1333 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1334 'user' => $user->getName(),
1335 'creator' => $creator->getName(),
1337 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1338 $state['continueRequests'] = $res->neededRequests
;
1339 $session->setSecret( 'AuthManager::accountCreationState', $state );
1342 throw new \
DomainException(
1343 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1348 // Step 2: Primary authentication succeeded, create the User object
1349 // and add the user locally.
1351 if ( $state['userid'] === 0 ) {
1352 $this->logger
->info( 'Creating user {user} during account creation', [
1353 'user' => $user->getName(),
1354 'creator' => $creator->getName(),
1356 $status = $user->addToDatabase();
1357 if ( !$status->isOk() ) {
1358 // @codeCoverageIgnoreStart
1359 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1360 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1361 $session->remove( 'AuthManager::accountCreationState' );
1363 // @codeCoverageIgnoreEnd
1365 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1366 \Hooks
::run( 'LocalUserCreated', [ $user, false ] );
1367 $user->saveSettings();
1368 $state['userid'] = $user->getId();
1370 // Update user count
1371 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1373 // Watch user's userpage and talk page
1374 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1376 // Inform the provider
1377 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1380 if ( $this->config
->get( 'NewUserLog' ) ) {
1381 $isAnon = $creator->isAnon();
1382 $logEntry = new \
ManualLogEntry(
1384 $logSubtype ?
: ( $isAnon ?
'create' : 'create2' )
1386 $logEntry->setPerformer( $isAnon ?
$user : $creator );
1387 $logEntry->setTarget( $user->getUserPage() );
1388 $req = AuthenticationRequest
::getRequestByClass(
1389 $state['reqs'], CreationReasonAuthenticationRequest
::class
1391 $logEntry->setComment( $req ?
$req->reason
: '' );
1392 $logEntry->setParameters( [
1393 '4::userid' => $user->getId(),
1395 $logid = $logEntry->insert();
1396 $logEntry->publish( $logid );
1400 // Step 3: Iterate over all the secondary authentication providers.
1402 $beginReqs = $state['reqs'];
1404 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1405 if ( !isset( $state['secondary'][$id] ) ) {
1406 // This provider isn't started yet, so we pass it the set
1407 // of reqs from beginAuthentication instead of whatever
1408 // might have been used by a previous provider in line.
1409 $func = 'beginSecondaryAccountCreation';
1410 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1411 } elseif ( !$state['secondary'][$id] ) {
1412 $func = 'continueSecondaryAccountCreation';
1413 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1417 switch ( $res->status
) {
1418 case AuthenticationResponse
::PASS
;
1419 $this->logger
->debug( __METHOD__
. ": Secondary creation passed by $id", [
1420 'user' => $user->getName(),
1421 'creator' => $creator->getName(),
1424 case AuthenticationResponse
::ABSTAIN
;
1425 $state['secondary'][$id] = true;
1427 case AuthenticationResponse
::REDIRECT
;
1428 case AuthenticationResponse
::UI
;
1429 $this->logger
->debug( __METHOD__
. ": Secondary creation $res->status by $id", [
1430 'user' => $user->getName(),
1431 'creator' => $creator->getName(),
1433 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1434 $state['secondary'][$id] = false;
1435 $state['continueRequests'] = $res->neededRequests
;
1436 $session->setSecret( 'AuthManager::accountCreationState', $state );
1438 case AuthenticationResponse
::FAIL
;
1439 throw new \
DomainException(
1440 get_class( $provider ) . "::{$func}() returned $res->status." .
1441 ' Secondary providers are not allowed to fail account creation, that' .
1442 ' should have been done via testForAccountCreation().'
1444 // @codeCoverageIgnoreStart
1446 throw new \
DomainException(
1447 get_class( $provider ) . "::{$func}() returned $res->status"
1449 // @codeCoverageIgnoreEnd
1453 $id = $user->getId();
1454 $name = $user->getName();
1455 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1456 $ret = AuthenticationResponse
::newPass( $name );
1457 $ret->loginRequest
= $req;
1458 $this->createdAccountAuthenticationRequests
[] = $req;
1460 $this->logger
->info( __METHOD__
. ': Account creation succeeded for {user}', [
1461 'user' => $user->getName(),
1462 'creator' => $creator->getName(),
1465 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1466 $session->remove( 'AuthManager::accountCreationState' );
1467 $this->removeAuthenticationSessionData( null );
1469 } catch ( \Exception
$ex ) {
1470 $session->remove( 'AuthManager::accountCreationState' );
1476 * Auto-create an account, and log into that account
1477 * @param User $user User to auto-create
1478 * @param string $source What caused the auto-creation? This must be the ID
1479 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1480 * @param bool $login Whether to also log the user in
1481 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1483 public function autoCreateUser( User
$user, $source, $login = true ) {
1484 if ( $source !== self
::AUTOCREATE_SOURCE_SESSION
&&
1485 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1487 throw new \
InvalidArgumentException( "Unknown auto-creation source: $source" );
1490 $username = $user->getName();
1492 // Try the local user from the slave DB
1493 $localId = User
::idFromName( $username );
1494 $flags = User
::READ_NORMAL
;
1496 // Fetch the user ID from the master, so that we don't try to create the user
1497 // when they already exist, due to replication lag
1498 // @codeCoverageIgnoreStart
1499 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
1500 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1501 $flags = User
::READ_LATEST
;
1503 // @codeCoverageIgnoreEnd
1506 $this->logger
->debug( __METHOD__
. ': {username} already exists locally', [
1507 'username' => $username,
1509 $user->setId( $localId );
1510 $user->loadFromId( $flags );
1512 $this->setSessionDataForUser( $user );
1514 $status = Status
::newGood();
1515 $status->warning( 'userexists' );
1519 // Wiki is read-only?
1520 if ( wfReadOnly() ) {
1521 $this->logger
->debug( __METHOD__
. ': denied by wfReadOnly(): {reason}', [
1522 'username' => $username,
1523 'reason' => wfReadOnlyReason(),
1526 $user->loadFromId();
1527 return Status
::newFatal( 'readonlytext', wfReadOnlyReason() );
1530 // Check the session, if we tried to create this user already there's
1531 // no point in retrying.
1532 $session = $this->request
->getSession();
1533 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1534 $this->logger
->debug( __METHOD__
. ': blacklisted in session {sessionid}', [
1535 'username' => $username,
1536 'sessionid' => $session->getId(),
1539 $user->loadFromId();
1540 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1541 if ( $reason instanceof StatusValue
) {
1542 return Status
::wrap( $reason );
1544 return Status
::newFatal( $reason );
1548 // Is the username creatable?
1549 if ( !User
::isCreatableName( $username ) ) {
1550 $this->logger
->debug( __METHOD__
. ': name "{username}" is not creatable', [
1551 'username' => $username,
1553 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname', 600 );
1555 $user->loadFromId();
1556 return Status
::newFatal( 'noname' );
1559 // Is the IP user able to create accounts?
1561 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1562 $this->logger
->debug( __METHOD__
. ': IP lacks the ability to create or autocreate accounts', [
1563 'username' => $username,
1564 'ip' => $anon->getName(),
1566 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm', 600 );
1567 $session->persist();
1569 $user->loadFromId();
1570 return Status
::newFatal( 'authmanager-autocreate-noperm' );
1573 // Avoid account creation races on double submissions
1574 $cache = \ObjectCache
::getLocalClusterInstance();
1575 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1577 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1578 'user' => $username,
1581 $user->loadFromId();
1582 return Status
::newFatal( 'usernameinprogress' );
1585 // Denied by providers?
1587 'flags' => User
::READ_LATEST
,
1590 $providers = $this->getPreAuthenticationProviders() +
1591 $this->getPrimaryAuthenticationProviders() +
1592 $this->getSecondaryAuthenticationProviders();
1593 foreach ( $providers as $provider ) {
1594 $status = $provider->testUserForCreation( $user, $source, $options );
1595 if ( !$status->isGood() ) {
1596 $ret = Status
::wrap( $status );
1597 $this->logger
->debug( __METHOD__
. ': Provider denied creation of {username}: {reason}', [
1598 'username' => $username,
1599 'reason' => $ret->getWikiText( null, null, 'en' ),
1601 $session->set( 'AuthManager::AutoCreateBlacklist', $status, 600 );
1603 $user->loadFromId();
1608 $backoffKey = wfMemcKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1609 if ( $cache->get( $backoffKey ) ) {
1610 $this->logger
->debug( __METHOD__
. ': {username} denied by prior creation attempt failures', [
1611 'username' => $username,
1614 $user->loadFromId();
1615 return Status
::newFatal( 'authmanager-autocreate-exception' );
1618 // Checks passed, create the user...
1619 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
1620 $this->logger
->info( __METHOD__
. ': creating new user ({username}) - from: {from}', [
1621 'username' => $username,
1625 // Ignore warnings about master connections/writes...hard to avoid here
1626 $trxProfiler = \Profiler
::instance()->getTransactionProfiler();
1627 $trxProfiler->setSilenced( true );
1629 $status = $user->addToDatabase();
1630 if ( !$status->isOk() ) {
1631 // double-check for a race condition (T70012)
1632 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1634 $this->logger
->info( __METHOD__
. ': {username} already exists locally (race)', [
1635 'username' => $username,
1637 $user->setId( $localId );
1638 $user->loadFromId( User
::READ_LATEST
);
1640 $this->setSessionDataForUser( $user );
1642 $status = Status
::newGood();
1643 $status->warning( 'userexists' );
1645 $this->logger
->error( __METHOD__
. ': {username} failed with message {message}', [
1646 'username' => $username,
1647 'message' => $status->getWikiText( null, null, 'en' )
1650 $user->loadFromId();
1654 } catch ( \Exception
$ex ) {
1655 $trxProfiler->setSilenced( false );
1656 $this->logger
->error( __METHOD__
. ': {username} failed with exception {exception}', [
1657 'username' => $username,
1660 // Do not keep throwing errors for a while
1661 $cache->set( $backoffKey, 1, 600 );
1662 // Bubble up error; which should normally trigger DB rollbacks
1666 $this->setDefaultUserOptions( $user, false );
1668 // Inform the providers
1669 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1671 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1672 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
1673 $user->saveSettings();
1675 // Update user count
1676 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1677 // Watch user's userpage and talk page
1678 \DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1679 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1683 if ( $this->config
->get( 'NewUserLog' ) ) {
1684 $logEntry = new \
ManualLogEntry( 'newusers', 'autocreate' );
1685 $logEntry->setPerformer( $user );
1686 $logEntry->setTarget( $user->getUserPage() );
1687 $logEntry->setComment( '' );
1688 $logEntry->setParameters( [
1689 '4::userid' => $user->getId(),
1691 $logEntry->insert();
1694 $trxProfiler->setSilenced( false );
1697 $this->setSessionDataForUser( $user );
1700 return Status
::newGood();
1706 * @name Account linking
1711 * Determine whether accounts can be linked
1714 public function canLinkAccounts() {
1715 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1716 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
) {
1724 * Start an account linking flow
1726 * @param User $user User being linked
1727 * @param AuthenticationRequest[] $reqs
1728 * @param string $returnToUrl Url that REDIRECT responses should eventually
1730 * @return AuthenticationResponse
1732 public function beginAccountLink( User
$user, array $reqs, $returnToUrl ) {
1733 $session = $this->request
->getSession();
1734 $session->remove( 'AuthManager::accountLinkState' );
1736 if ( !$this->canLinkAccounts() ) {
1737 // Caller should have called canLinkAccounts()
1738 throw new \
LogicException( 'Account linking is not possible' );
1741 if ( $user->getId() === 0 ) {
1742 if ( !User
::isUsableName( $user->getName() ) ) {
1743 $msg = wfMessage( 'noname' );
1745 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1747 return AuthenticationResponse
::newFail( $msg );
1749 foreach ( $reqs as $req ) {
1750 $req->username
= $user->getName();
1751 $req->returnToUrl
= $returnToUrl;
1754 $this->removeAuthenticationSessionData( null );
1756 $providers = $this->getPreAuthenticationProviders();
1757 foreach ( $providers as $id => $provider ) {
1758 $status = $provider->testForAccountLink( $user );
1759 if ( !$status->isGood() ) {
1760 $this->logger
->debug( __METHOD__
. ": Account linking pre-check failed by $id", [
1761 'user' => $user->getName(),
1763 $ret = AuthenticationResponse
::newFail(
1764 Status
::wrap( $status )->getMessage()
1766 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1772 'username' => $user->getName(),
1773 'userid' => $user->getId(),
1774 'returnToUrl' => $returnToUrl,
1776 'continueRequests' => [],
1779 $providers = $this->getPrimaryAuthenticationProviders();
1780 foreach ( $providers as $id => $provider ) {
1781 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider
::TYPE_LINK
) {
1785 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1786 switch ( $res->status
) {
1787 case AuthenticationResponse
::PASS
;
1788 $this->logger
->info( "Account linked to {user} by $id", [
1789 'user' => $user->getName(),
1791 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1794 case AuthenticationResponse
::FAIL
;
1795 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1796 'user' => $user->getName(),
1798 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1801 case AuthenticationResponse
::ABSTAIN
;
1805 case AuthenticationResponse
::REDIRECT
;
1806 case AuthenticationResponse
::UI
;
1807 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1808 'user' => $user->getName(),
1810 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1811 $state['primary'] = $id;
1812 $state['continueRequests'] = $res->neededRequests
;
1813 $session->setSecret( 'AuthManager::accountLinkState', $state );
1814 $session->persist();
1817 // @codeCoverageIgnoreStart
1819 throw new \
DomainException(
1820 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1822 // @codeCoverageIgnoreEnd
1826 $this->logger
->debug( __METHOD__
. ': Account linking failed because no provider accepted', [
1827 'user' => $user->getName(),
1829 $ret = AuthenticationResponse
::newFail(
1830 wfMessage( 'authmanager-link-no-primary' )
1832 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1837 * Continue an account linking flow
1838 * @param AuthenticationRequest[] $reqs
1839 * @return AuthenticationResponse
1841 public function continueAccountLink( array $reqs ) {
1842 $session = $this->request
->getSession();
1844 if ( !$this->canLinkAccounts() ) {
1845 // Caller should have called canLinkAccounts()
1846 $session->remove( 'AuthManager::accountLinkState' );
1847 throw new \
LogicException( 'Account linking is not possible' );
1850 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1851 if ( !is_array( $state ) ) {
1852 return AuthenticationResponse
::newFail(
1853 wfMessage( 'authmanager-link-not-in-progress' )
1856 $state['continueRequests'] = [];
1858 // Step 0: Prepare and validate the input
1860 $user = User
::newFromName( $state['username'], 'usable' );
1861 if ( !is_object( $user ) ) {
1862 $session->remove( 'AuthManager::accountLinkState' );
1863 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1865 if ( $user->getId() != $state['userid'] ) {
1866 throw new \
UnexpectedValueException(
1867 "User \"{$state['username']}\" is valid, but " .
1868 "ID {$user->getId()} != {$state['userid']}!"
1872 foreach ( $reqs as $req ) {
1873 $req->username
= $state['username'];
1874 $req->returnToUrl
= $state['returnToUrl'];
1877 // Step 1: Call the primary again until it succeeds
1879 $provider = $this->getAuthenticationProvider( $state['primary'] );
1880 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1881 // Configuration changed? Force them to start over.
1882 // @codeCoverageIgnoreStart
1883 $ret = AuthenticationResponse
::newFail(
1884 wfMessage( 'authmanager-link-not-in-progress' )
1886 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1887 $session->remove( 'AuthManager::accountLinkState' );
1889 // @codeCoverageIgnoreEnd
1891 $id = $provider->getUniqueId();
1892 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1893 switch ( $res->status
) {
1894 case AuthenticationResponse
::PASS
;
1895 $this->logger
->info( "Account linked to {user} by $id", [
1896 'user' => $user->getName(),
1898 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1899 $session->remove( 'AuthManager::accountLinkState' );
1901 case AuthenticationResponse
::FAIL
;
1902 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1903 'user' => $user->getName(),
1905 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1906 $session->remove( 'AuthManager::accountLinkState' );
1908 case AuthenticationResponse
::REDIRECT
;
1909 case AuthenticationResponse
::UI
;
1910 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1911 'user' => $user->getName(),
1913 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1914 $state['continueRequests'] = $res->neededRequests
;
1915 $session->setSecret( 'AuthManager::accountLinkState', $state );
1918 throw new \
DomainException(
1919 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1922 } catch ( \Exception
$ex ) {
1923 $session->remove( 'AuthManager::accountLinkState' );
1931 * @name Information methods
1936 * Return the applicable list of AuthenticationRequests
1938 * Possible values for $action:
1939 * - ACTION_LOGIN: Valid for passing to beginAuthentication
1940 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
1941 * - ACTION_CREATE: Valid for passing to beginAccountCreation
1942 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
1943 * - ACTION_LINK: Valid for passing to beginAccountLink
1944 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
1945 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
1946 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
1947 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
1949 * @param string $action One of the AuthManager::ACTION_* constants
1950 * @param User|null $user User being acted on, instead of the current user.
1951 * @return AuthenticationRequest[]
1953 public function getAuthenticationRequests( $action, User
$user = null ) {
1955 $providerAction = $action;
1957 // Figure out which providers to query
1958 switch ( $action ) {
1959 case self
::ACTION_LOGIN
:
1960 case self
::ACTION_CREATE
:
1961 $providers = $this->getPreAuthenticationProviders() +
1962 $this->getPrimaryAuthenticationProviders() +
1963 $this->getSecondaryAuthenticationProviders();
1966 case self
::ACTION_LOGIN_CONTINUE
:
1967 $state = $this->request
->getSession()->getSecret( 'AuthManager::authnState' );
1968 return is_array( $state ) ?
$state['continueRequests'] : [];
1970 case self
::ACTION_CREATE_CONTINUE
:
1971 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountCreationState' );
1972 return is_array( $state ) ?
$state['continueRequests'] : [];
1974 case self
::ACTION_LINK
:
1975 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
1976 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
1980 case self
::ACTION_UNLINK
:
1981 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
1982 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
1985 // To providers, unlink and remove are identical.
1986 $providerAction = self
::ACTION_REMOVE
;
1989 case self
::ACTION_LINK_CONTINUE
:
1990 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountLinkState' );
1991 return is_array( $state ) ?
$state['continueRequests'] : [];
1993 case self
::ACTION_CHANGE
:
1994 case self
::ACTION_REMOVE
:
1995 $providers = $this->getPrimaryAuthenticationProviders() +
1996 $this->getSecondaryAuthenticationProviders();
1999 // @codeCoverageIgnoreStart
2001 throw new \
DomainException( __METHOD__
. ": Invalid action \"$action\"" );
2003 // @codeCoverageIgnoreEnd
2005 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2009 * Internal request lookup for self::getAuthenticationRequests
2011 * @param string $providerAction Action to pass to providers
2012 * @param array $options Options to pass to providers
2013 * @param AuthenticationProvider[] $providers
2014 * @param User|null $user
2015 * @return AuthenticationRequest[]
2017 private function getAuthenticationRequestsInternal(
2018 $providerAction, array $options, array $providers, User
$user = null
2020 $user = $user ?
: \RequestContext
::getMain()->getUser();
2021 $options['username'] = $user->isAnon() ?
null : $user->getName();
2023 // Query them and merge results
2025 foreach ( $providers as $provider ) {
2026 $isPrimary = $provider instanceof PrimaryAuthenticationProvider
;
2027 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2028 $id = $req->getUniqueId();
2030 // If a required request if from a Primary, mark it as "primary-required" instead
2032 if ( $req->required
) {
2033 $req->required
= AuthenticationRequest
::PRIMARY_REQUIRED
;
2038 !isset( $reqs[$id] )
2039 ||
$req->required
=== AuthenticationRequest
::REQUIRED
2040 ||
$reqs[$id] === AuthenticationRequest
::OPTIONAL
2047 // AuthManager has its own req for some actions
2048 switch ( $providerAction ) {
2049 case self
::ACTION_LOGIN
:
2050 $reqs[] = new RememberMeAuthenticationRequest
;
2053 case self
::ACTION_CREATE
:
2054 $reqs[] = new UsernameAuthenticationRequest
;
2055 $reqs[] = new UserDataAuthenticationRequest
;
2056 if ( $options['username'] !== null ) {
2057 $reqs[] = new CreationReasonAuthenticationRequest
;
2058 $options['username'] = null; // Don't fill in the username below
2063 // Fill in reqs data
2064 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2066 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2067 if ( $providerAction === self
::ACTION_CHANGE ||
$providerAction === self
::ACTION_REMOVE
) {
2068 $reqs = array_filter( $reqs, function ( $req ) {
2069 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2073 return array_values( $reqs );
2077 * Set values in an array of requests
2078 * @param AuthenticationRequest[] &$reqs
2079 * @param string $action
2080 * @param string|null $username
2081 * @param boolean $forceAction
2083 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2084 foreach ( $reqs as $req ) {
2085 if ( !$req->action ||
$forceAction ) {
2086 $req->action
= $action;
2088 if ( $req->username
=== null ) {
2089 $req->username
= $username;
2095 * Determine whether a username exists
2096 * @param string $username
2097 * @param int $flags Bitfield of User:READ_* constants
2100 public function userExists( $username, $flags = User
::READ_NORMAL
) {
2101 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2102 if ( $provider->testUserExists( $username, $flags ) ) {
2111 * Determine whether a user property should be allowed to be changed.
2113 * Supported properties are:
2118 * @param string $property
2121 public function allowsPropertyChange( $property ) {
2122 $providers = $this->getPrimaryAuthenticationProviders() +
2123 $this->getSecondaryAuthenticationProviders();
2124 foreach ( $providers as $provider ) {
2125 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2133 * Get a provider by ID
2134 * @note This is public so extensions can check whether their own provider
2135 * is installed and so they can read its configuration if necessary.
2136 * Other uses are not recommended.
2138 * @return AuthenticationProvider|null
2140 public function getAuthenticationProvider( $id ) {
2142 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2143 return $this->allAuthenticationProviders
[$id];
2146 // Slow version: instantiate each kind and check
2147 $providers = $this->getPrimaryAuthenticationProviders();
2148 if ( isset( $providers[$id] ) ) {
2149 return $providers[$id];
2151 $providers = $this->getSecondaryAuthenticationProviders();
2152 if ( isset( $providers[$id] ) ) {
2153 return $providers[$id];
2155 $providers = $this->getPreAuthenticationProviders();
2156 if ( isset( $providers[$id] ) ) {
2157 return $providers[$id];
2166 * @name Internal methods
2171 * Store authentication in the current session
2172 * @protected For use by AuthenticationProviders
2173 * @param string $key
2174 * @param mixed $data Must be serializable
2176 public function setAuthenticationSessionData( $key, $data ) {
2177 $session = $this->request
->getSession();
2178 $arr = $session->getSecret( 'authData' );
2179 if ( !is_array( $arr ) ) {
2183 $session->setSecret( 'authData', $arr );
2187 * Fetch authentication data from the current session
2188 * @protected For use by AuthenticationProviders
2189 * @param string $key
2190 * @param mixed $default
2193 public function getAuthenticationSessionData( $key, $default = null ) {
2194 $arr = $this->request
->getSession()->getSecret( 'authData' );
2195 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2203 * Remove authentication data
2204 * @protected For use by AuthenticationProviders
2205 * @param string|null $key If null, all data is removed
2207 public function removeAuthenticationSessionData( $key ) {
2208 $session = $this->request
->getSession();
2209 if ( $key === null ) {
2210 $session->remove( 'authData' );
2212 $arr = $session->getSecret( 'authData' );
2213 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2214 unset( $arr[$key] );
2215 $session->setSecret( 'authData', $arr );
2221 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2222 * @param string $class
2223 * @param array[] $specs
2224 * @return AuthenticationProvider[]
2226 protected function providerArrayFromSpecs( $class, array $specs ) {
2228 foreach ( $specs as &$spec ) {
2229 $spec = [ 'sort2' => $i++
] +
$spec +
[ 'sort' => 0 ];
2232 usort( $specs, function ( $a, $b ) {
2233 return ( (int)$a['sort'] ) - ( (int)$b['sort'] )
2234 ?
: $a['sort2'] - $b['sort2'];
2238 foreach ( $specs as $spec ) {
2239 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
2240 if ( !$provider instanceof $class ) {
2241 throw new \
RuntimeException(
2242 "Expected instance of $class, got " . get_class( $provider )
2245 $provider->setLogger( $this->logger
);
2246 $provider->setManager( $this );
2247 $provider->setConfig( $this->config
);
2248 $id = $provider->getUniqueId();
2249 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2250 throw new \
RuntimeException(
2251 "Duplicate specifications for id $id (classes " .
2252 get_class( $provider ) . ' and ' .
2253 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
2256 $this->allAuthenticationProviders
[$id] = $provider;
2257 $ret[$id] = $provider;
2263 * Get the configuration
2266 private function getConfiguration() {
2267 return $this->config
->get( 'AuthManagerConfig' ) ?
: $this->config
->get( 'AuthManagerAutoConfig' );
2271 * Get the list of PreAuthenticationProviders
2272 * @return PreAuthenticationProvider[]
2274 protected function getPreAuthenticationProviders() {
2275 if ( $this->preAuthenticationProviders
=== null ) {
2276 $conf = $this->getConfiguration();
2277 $this->preAuthenticationProviders
= $this->providerArrayFromSpecs(
2278 PreAuthenticationProvider
::class, $conf['preauth']
2281 return $this->preAuthenticationProviders
;
2285 * Get the list of PrimaryAuthenticationProviders
2286 * @return PrimaryAuthenticationProvider[]
2288 protected function getPrimaryAuthenticationProviders() {
2289 if ( $this->primaryAuthenticationProviders
=== null ) {
2290 $conf = $this->getConfiguration();
2291 $this->primaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2292 PrimaryAuthenticationProvider
::class, $conf['primaryauth']
2295 return $this->primaryAuthenticationProviders
;
2299 * Get the list of SecondaryAuthenticationProviders
2300 * @return SecondaryAuthenticationProvider[]
2302 protected function getSecondaryAuthenticationProviders() {
2303 if ( $this->secondaryAuthenticationProviders
=== null ) {
2304 $conf = $this->getConfiguration();
2305 $this->secondaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2306 SecondaryAuthenticationProvider
::class, $conf['secondaryauth']
2309 return $this->secondaryAuthenticationProviders
;
2314 * @param bool|null $remember
2316 private function setSessionDataForUser( $user, $remember = null ) {
2317 $session = $this->request
->getSession();
2318 $delay = $session->delaySave();
2320 $session->resetId();
2321 $session->resetAllTokens();
2322 if ( $session->canSetUser() ) {
2323 $session->setUser( $user );
2325 if ( $remember !== null ) {
2326 $session->setRememberUser( $remember );
2328 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2329 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2330 $session->persist();
2332 \ScopedCallback
::consume( $delay );
2334 \Hooks
::run( 'UserLoggedIn', [ $user ] );
2339 * @param bool $useContextLang Use 'uselang' to set the user's language
2341 private function setDefaultUserOptions( User
$user, $useContextLang ) {
2346 $lang = $useContextLang ? \RequestContext
::getMain()->getLanguage() : $wgContLang;
2347 $user->setOption( 'language', $lang->getPreferredVariant() );
2349 if ( $wgContLang->hasVariants() ) {
2350 $user->setOption( 'variant', $wgContLang->getPreferredVariant() );
2355 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2356 * @param string $method
2357 * @param array $args
2359 private function callMethodOnProviders( $which, $method, array $args ) {
2362 $providers +
= $this->getPreAuthenticationProviders();
2365 $providers +
= $this->getPrimaryAuthenticationProviders();
2368 $providers +
= $this->getSecondaryAuthenticationProviders();
2370 foreach ( $providers as $provider ) {
2371 call_user_func_array( [ $provider, $method ], $args );
2376 * Reset the internal caching for unit testing
2378 public static function resetCache() {
2379 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2380 // @codeCoverageIgnoreStart
2381 throw new \
MWException( __METHOD__
. ' may only be called from unit tests!' );
2382 // @codeCoverageIgnoreEnd
2385 self
::$instance = null;
2393 * For really cool vim folding this needs to be at the end:
2394 * vim: foldmarker=@{,@} foldmethod=marker