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 MediaWiki\MediaWikiServices
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
34 use Wikimedia\ObjectFactory
;
37 * This serves as the entry point to the authentication system.
39 * In the future, it may also serve as the entry point to the authorization
42 * If you are looking at this because you are working on an extension that creates its own
43 * login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
44 * have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
45 * or the createaccount API. Trying to call this class directly will very likely end up in
46 * security vulnerabilities or broken UX in edge cases.
48 * If you are working on an extension that needs to integrate with the authentication system
49 * (e.g. by providing a new login method, or doing extra permission checks), you'll probably
50 * need to write an AuthenticationProvider.
52 * If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
53 * you are looking for. If you want to change user data, use User::changeAuthenticationData().
54 * Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
55 * create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
56 * responsibility to ensure that the user can authenticate somehow (see especially
57 * PrimaryAuthenticationProvider::autoCreatedAccount()). The same functionality can also be used
58 * from Maintenance scripts such as createAndPromote.php.
59 * If you are writing code that is not associated with such a provider and needs to create accounts
60 * programmatically for real users, you should rethink your architecture. There is no good way to
61 * do that as such code has no knowledge of what authentication methods are enabled on the wiki and
62 * cannot provide any means for users to access the accounts it would create.
64 * The two main control flows when using this class are as follows:
65 * * Login, user creation or account linking code will call getAuthenticationRequests(), populate
66 * the requests with data (by using them to build a HTMLForm and have the user fill it, or by
67 * exposing a form specification via the API, so that the client can build it), and pass them to
68 * the appropriate begin* method. That will return either a success/failure response, or more
69 * requests to fill (either by building a form or by redirecting the user to some external
70 * provider which will send the data back), in which case they need to be submitted to the
71 * appropriate continue* method and that step has to be repeated until the response is a success
72 * or failure response. AuthManager will use the session to maintain internal state during the
74 * * Code doing an authentication data change will call getAuthenticationRequests(), select
75 * a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
76 * changeAuthenticationData(). If the data change is user-initiated, the whole process needs
77 * to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
82 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
84 class AuthManager
implements LoggerAwareInterface
{
85 /** Log in with an existing (not necessarily local) user */
86 const ACTION_LOGIN
= 'login';
87 /** Continue a login process that was interrupted by the need for user input or communication
88 * with an external provider */
89 const ACTION_LOGIN_CONTINUE
= 'login-continue';
90 /** Create a new user */
91 const ACTION_CREATE
= 'create';
92 /** Continue a user creation process that was interrupted by the need for user input or
93 * communication with an external provider */
94 const ACTION_CREATE_CONTINUE
= 'create-continue';
95 /** Link an existing user to a third-party account */
96 const ACTION_LINK
= 'link';
97 /** Continue a user linking process that was interrupted by the need for user input or
98 * communication with an external provider */
99 const ACTION_LINK_CONTINUE
= 'link-continue';
100 /** Change a user's credentials */
101 const ACTION_CHANGE
= 'change';
102 /** Remove a user's credentials */
103 const ACTION_REMOVE
= 'remove';
104 /** Like ACTION_REMOVE but for linking providers only */
105 const ACTION_UNLINK
= 'unlink';
107 /** Security-sensitive operations are ok. */
109 /** Security-sensitive operations should re-authenticate. */
110 const SEC_REAUTH
= 'reauth';
111 /** Security-sensitive should not be performed. */
112 const SEC_FAIL
= 'fail';
114 /** Auto-creation is due to SessionManager */
115 const AUTOCREATE_SOURCE_SESSION
= \MediaWiki\Session\SessionManager
::class;
117 /** Auto-creation is due to a Maintenance script */
118 const AUTOCREATE_SOURCE_MAINT
= '::Maintenance::';
120 /** @var AuthManager|null */
121 private static $instance = null;
123 /** @var WebRequest */
129 /** @var LoggerInterface */
132 /** @var AuthenticationProvider[] */
133 private $allAuthenticationProviders = [];
135 /** @var PreAuthenticationProvider[] */
136 private $preAuthenticationProviders = null;
138 /** @var PrimaryAuthenticationProvider[] */
139 private $primaryAuthenticationProviders = null;
141 /** @var SecondaryAuthenticationProvider[] */
142 private $secondaryAuthenticationProviders = null;
144 /** @var CreatedAccountAuthenticationRequest[] */
145 private $createdAccountAuthenticationRequests = [];
148 * Get the global AuthManager
149 * @return AuthManager
151 public static function singleton() {
152 if ( self
::$instance === null ) {
153 self
::$instance = new self(
154 \RequestContext
::getMain()->getRequest(),
155 MediaWikiServices
::getInstance()->getMainConfig()
158 return self
::$instance;
162 * @param WebRequest $request
163 * @param Config $config
165 public function __construct( WebRequest
$request, Config
$config ) {
166 $this->request
= $request;
167 $this->config
= $config;
168 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' ) );
172 * @param LoggerInterface $logger
174 public function setLogger( LoggerInterface
$logger ) {
175 $this->logger
= $logger;
181 public function getRequest() {
182 return $this->request
;
186 * Force certain PrimaryAuthenticationProviders
187 * @deprecated For backwards compatibility only
188 * @param PrimaryAuthenticationProvider[] $providers
191 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
192 $this->logger
->warning( "Overriding AuthManager primary authn because $why" );
194 if ( $this->primaryAuthenticationProviders
!== null ) {
195 $this->logger
->warning(
196 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
199 $this->allAuthenticationProviders
= array_diff_key(
200 $this->allAuthenticationProviders
,
201 $this->primaryAuthenticationProviders
203 $session = $this->request
->getSession();
204 $session->remove( 'AuthManager::authnState' );
205 $session->remove( 'AuthManager::accountCreationState' );
206 $session->remove( 'AuthManager::accountLinkState' );
207 $this->createdAccountAuthenticationRequests
= [];
210 $this->primaryAuthenticationProviders
= [];
211 foreach ( $providers as $provider ) {
212 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
213 throw new \
RuntimeException(
214 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
215 get_class( $provider )
218 $provider->setLogger( $this->logger
);
219 $provider->setManager( $this );
220 $provider->setConfig( $this->config
);
221 $id = $provider->getUniqueId();
222 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
223 throw new \
RuntimeException(
224 "Duplicate specifications for id $id (classes " .
225 get_class( $provider ) . ' and ' .
226 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
229 $this->allAuthenticationProviders
[$id] = $provider;
230 $this->primaryAuthenticationProviders
[$id] = $provider;
235 * This used to call a legacy AuthPlugin method, if necessary. Since that code has
236 * been removed, it now just returns the $return parameter.
238 * @codeCoverageIgnore
239 * @deprecated For backwards compatibility only, should be avoided in new code
240 * @param string $method AuthPlugin method to call
241 * @param array $params Parameters to pass
242 * @param mixed $return Return value if AuthPlugin wasn't called
243 * @return mixed Return value from the AuthPlugin method, or $return
245 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
246 wfDeprecated( __METHOD__
, '1.33' );
251 * @name Authentication
256 * Indicate whether user authentication is possible
258 * It may not be if the session is provided by something like OAuth
259 * for which each individual request includes authentication data.
263 public function canAuthenticateNow() {
264 return $this->request
->getSession()->canSetUser();
268 * Start an authentication flow
270 * In addition to the AuthenticationRequests returned by
271 * $this->getAuthenticationRequests(), a client might include a
272 * CreateFromLoginAuthenticationRequest from a previous login attempt to
275 * Instead of the AuthenticationRequests returned by
276 * $this->getAuthenticationRequests(), a client might pass a
277 * CreatedAccountAuthenticationRequest from an account creation that just
278 * succeeded to log in to the just-created account.
280 * @param AuthenticationRequest[] $reqs
281 * @param string $returnToUrl Url that REDIRECT responses should eventually
283 * @return AuthenticationResponse See self::continueAuthentication()
285 public function beginAuthentication( array $reqs, $returnToUrl ) {
286 $session = $this->request
->getSession();
287 if ( !$session->canSetUser() ) {
288 // Caller should have called canAuthenticateNow()
289 $session->remove( 'AuthManager::authnState' );
290 throw new \
LogicException( 'Authentication is not possible now' );
293 $guessUserName = null;
294 foreach ( $reqs as $req ) {
295 $req->returnToUrl
= $returnToUrl;
296 // @codeCoverageIgnoreStart
297 if ( $req->username
!== null && $req->username
!== '' ) {
298 if ( $guessUserName === null ) {
299 $guessUserName = $req->username
;
300 } elseif ( $guessUserName !== $req->username
) {
301 $guessUserName = null;
305 // @codeCoverageIgnoreEnd
308 // Check for special-case login of a just-created account
309 $req = AuthenticationRequest
::getRequestByClass(
310 $reqs, CreatedAccountAuthenticationRequest
::class
313 if ( !in_array( $req, $this->createdAccountAuthenticationRequests
, true ) ) {
314 throw new \
LogicException(
315 'CreatedAccountAuthenticationRequests are only valid on ' .
316 'the same AuthManager that created the account'
320 $user = User
::newFromName( $req->username
);
321 // @codeCoverageIgnoreStart
323 throw new \
UnexpectedValueException(
324 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
326 } elseif ( $user->getId() != $req->id
) {
327 throw new \
UnexpectedValueException(
328 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
331 // @codeCoverageIgnoreEnd
333 $this->logger
->info( 'Logging in {user} after account creation', [
334 'user' => $user->getName(),
336 $ret = AuthenticationResponse
::newPass( $user->getName() );
337 $this->setSessionDataForUser( $user );
338 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
339 $session->remove( 'AuthManager::authnState' );
340 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
344 $this->removeAuthenticationSessionData( null );
346 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
347 $status = $provider->testForAuthentication( $reqs );
348 if ( !$status->isGood() ) {
349 $this->logger
->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
350 $ret = AuthenticationResponse
::newFail(
351 Status
::wrap( $status )->getMessage()
353 $this->callMethodOnProviders( 7, 'postAuthentication',
354 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
356 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName, [] ] );
363 'returnToUrl' => $returnToUrl,
364 'guessUserName' => $guessUserName,
366 'primaryResponse' => null,
369 'continueRequests' => [],
372 // Preserve state from a previous failed login
373 $req = AuthenticationRequest
::getRequestByClass(
374 $reqs, CreateFromLoginAuthenticationRequest
::class
377 $state['maybeLink'] = $req->maybeLink
;
380 $session = $this->request
->getSession();
381 $session->setSecret( 'AuthManager::authnState', $state );
384 return $this->continueAuthentication( $reqs );
388 * Continue an authentication flow
390 * Return values are interpreted as follows:
391 * - status FAIL: Authentication failed. If $response->createRequest is
392 * set, that may be passed to self::beginAuthentication() or to
393 * self::beginAccountCreation() to preserve state.
394 * - status REDIRECT: The client should be redirected to the contained URL,
395 * new AuthenticationRequests should be made (if any), then
396 * AuthManager::continueAuthentication() should be called.
397 * - status UI: The client should be presented with a user interface for
398 * the fields in the specified AuthenticationRequests, then new
399 * AuthenticationRequests should be made, then
400 * AuthManager::continueAuthentication() should be called.
401 * - status RESTART: The user logged in successfully with a third-party
402 * service, but the third-party credentials aren't attached to any local
403 * account. This could be treated as a UI or a FAIL.
404 * - status PASS: Authentication was successful.
406 * @param AuthenticationRequest[] $reqs
407 * @return AuthenticationResponse
409 public function continueAuthentication( array $reqs ) {
410 $session = $this->request
->getSession();
412 if ( !$session->canSetUser() ) {
413 // Caller should have called canAuthenticateNow()
414 // @codeCoverageIgnoreStart
415 throw new \
LogicException( 'Authentication is not possible now' );
416 // @codeCoverageIgnoreEnd
419 $state = $session->getSecret( 'AuthManager::authnState' );
420 if ( !is_array( $state ) ) {
421 return AuthenticationResponse
::newFail(
422 wfMessage( 'authmanager-authn-not-in-progress' )
425 $state['continueRequests'] = [];
427 $guessUserName = $state['guessUserName'];
429 foreach ( $reqs as $req ) {
430 $req->returnToUrl
= $state['returnToUrl'];
433 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
435 if ( $state['primary'] === null ) {
436 // We haven't picked a PrimaryAuthenticationProvider yet
437 // @codeCoverageIgnoreStart
438 $guessUserName = null;
439 foreach ( $reqs as $req ) {
440 if ( $req->username
!== null && $req->username
!== '' ) {
441 if ( $guessUserName === null ) {
442 $guessUserName = $req->username
;
443 } elseif ( $guessUserName !== $req->username
) {
444 $guessUserName = null;
449 $state['guessUserName'] = $guessUserName;
450 // @codeCoverageIgnoreEnd
451 $state['reqs'] = $reqs;
453 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
454 $res = $provider->beginPrimaryAuthentication( $reqs );
455 switch ( $res->status
) {
456 case AuthenticationResponse
::PASS
;
457 $state['primary'] = $id;
458 $state['primaryResponse'] = $res;
459 $this->logger
->debug( "Primary login with $id succeeded" );
461 case AuthenticationResponse
::FAIL
;
462 $this->logger
->debug( "Login failed in primary authentication by $id" );
463 if ( $res->createRequest ||
$state['maybeLink'] ) {
464 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
465 $res->createRequest
, $state['maybeLink']
468 $this->callMethodOnProviders( 7, 'postAuthentication',
469 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
471 $session->remove( 'AuthManager::authnState' );
472 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName, [] ] );
474 case AuthenticationResponse
::ABSTAIN
;
477 case AuthenticationResponse
::REDIRECT
;
478 case AuthenticationResponse
::UI
;
479 $this->logger
->debug( "Primary login with $id returned $res->status" );
480 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
481 $state['primary'] = $id;
482 $state['continueRequests'] = $res->neededRequests
;
483 $session->setSecret( 'AuthManager::authnState', $state );
486 // @codeCoverageIgnoreStart
488 throw new \
DomainException(
489 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
491 // @codeCoverageIgnoreEnd
494 if ( $state['primary'] === null ) {
495 $this->logger
->debug( 'Login failed in primary authentication because no provider accepted' );
496 $ret = AuthenticationResponse
::newFail(
497 wfMessage( 'authmanager-authn-no-primary' )
499 $this->callMethodOnProviders( 7, 'postAuthentication',
500 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
502 $session->remove( 'AuthManager::authnState' );
505 } elseif ( $state['primaryResponse'] === null ) {
506 $provider = $this->getAuthenticationProvider( $state['primary'] );
507 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
508 // Configuration changed? Force them to start over.
509 // @codeCoverageIgnoreStart
510 $ret = AuthenticationResponse
::newFail(
511 wfMessage( 'authmanager-authn-not-in-progress' )
513 $this->callMethodOnProviders( 7, 'postAuthentication',
514 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
516 $session->remove( 'AuthManager::authnState' );
518 // @codeCoverageIgnoreEnd
520 $id = $provider->getUniqueId();
521 $res = $provider->continuePrimaryAuthentication( $reqs );
522 switch ( $res->status
) {
523 case AuthenticationResponse
::PASS
;
524 $state['primaryResponse'] = $res;
525 $this->logger
->debug( "Primary login with $id succeeded" );
527 case AuthenticationResponse
::FAIL
;
528 $this->logger
->debug( "Login failed in primary authentication by $id" );
529 if ( $res->createRequest ||
$state['maybeLink'] ) {
530 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
531 $res->createRequest
, $state['maybeLink']
534 $this->callMethodOnProviders( 7, 'postAuthentication',
535 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
537 $session->remove( 'AuthManager::authnState' );
538 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName, [] ] );
540 case AuthenticationResponse
::REDIRECT
;
541 case AuthenticationResponse
::UI
;
542 $this->logger
->debug( "Primary login with $id returned $res->status" );
543 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
544 $state['continueRequests'] = $res->neededRequests
;
545 $session->setSecret( 'AuthManager::authnState', $state );
548 throw new \
DomainException(
549 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
554 $res = $state['primaryResponse'];
555 if ( $res->username
=== null ) {
556 $provider = $this->getAuthenticationProvider( $state['primary'] );
557 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
558 // Configuration changed? Force them to start over.
559 // @codeCoverageIgnoreStart
560 $ret = AuthenticationResponse
::newFail(
561 wfMessage( 'authmanager-authn-not-in-progress' )
563 $this->callMethodOnProviders( 7, 'postAuthentication',
564 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
566 $session->remove( 'AuthManager::authnState' );
568 // @codeCoverageIgnoreEnd
571 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
&&
573 // don't confuse the user with an incorrect message if linking is disabled
574 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider
::class )
576 $state['maybeLink'][$res->linkRequest
->getUniqueId()] = $res->linkRequest
;
577 $msg = 'authmanager-authn-no-local-user-link';
579 $msg = 'authmanager-authn-no-local-user';
581 $this->logger
->debug(
582 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
584 $ret = AuthenticationResponse
::newRestart( wfMessage( $msg ) );
585 $ret->neededRequests
= $this->getAuthenticationRequestsInternal(
588 $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders()
590 if ( $res->createRequest ||
$state['maybeLink'] ) {
591 $ret->createRequest
= new CreateFromLoginAuthenticationRequest(
592 $res->createRequest
, $state['maybeLink']
594 $ret->neededRequests
[] = $ret->createRequest
;
596 $this->fillRequests( $ret->neededRequests
, self
::ACTION_LOGIN
, null, true );
597 $session->setSecret( 'AuthManager::authnState', [
598 'reqs' => [], // Will be filled in later
600 'primaryResponse' => null,
602 'continueRequests' => $ret->neededRequests
,
607 // Step 2: Primary authentication succeeded, create the User object
608 // (and add the user locally if necessary)
610 $user = User
::newFromName( $res->username
, 'usable' );
612 $provider = $this->getAuthenticationProvider( $state['primary'] );
613 throw new \
DomainException(
614 get_class( $provider ) . " returned an invalid username: {$res->username}"
617 if ( $user->getId() === 0 ) {
618 // User doesn't exist locally. Create it.
619 $this->logger
->info( 'Auto-creating {user} on login', [
620 'user' => $user->getName(),
622 $status = $this->autoCreateUser( $user, $state['primary'], false );
623 if ( !$status->isGood() ) {
624 $ret = AuthenticationResponse
::newFail(
625 Status
::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
627 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
628 $session->remove( 'AuthManager::authnState' );
629 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
634 // Step 3: Iterate over all the secondary authentication providers.
636 $beginReqs = $state['reqs'];
638 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
639 if ( !isset( $state['secondary'][$id] ) ) {
640 // This provider isn't started yet, so we pass it the set
641 // of reqs from beginAuthentication instead of whatever
642 // might have been used by a previous provider in line.
643 $func = 'beginSecondaryAuthentication';
644 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
645 } elseif ( !$state['secondary'][$id] ) {
646 $func = 'continueSecondaryAuthentication';
647 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
651 switch ( $res->status
) {
652 case AuthenticationResponse
::PASS
;
653 $this->logger
->debug( "Secondary login with $id succeeded" );
655 case AuthenticationResponse
::ABSTAIN
;
656 $state['secondary'][$id] = true;
658 case AuthenticationResponse
::FAIL
;
659 $this->logger
->debug( "Login failed in secondary authentication by $id" );
660 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
661 $session->remove( 'AuthManager::authnState' );
662 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName(), [] ] );
664 case AuthenticationResponse
::REDIRECT
;
665 case AuthenticationResponse
::UI
;
666 $this->logger
->debug( "Secondary login with $id returned " . $res->status
);
667 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $user->getName() );
668 $state['secondary'][$id] = false;
669 $state['continueRequests'] = $res->neededRequests
;
670 $session->setSecret( 'AuthManager::authnState', $state );
673 // @codeCoverageIgnoreStart
675 throw new \
DomainException(
676 get_class( $provider ) . "::{$func}() returned $res->status"
678 // @codeCoverageIgnoreEnd
682 // Step 4: Authentication complete! Set the user in the session and
685 $this->logger
->info( 'Login for {user} succeeded from {clientip}', [
686 'user' => $user->getName(),
687 'clientip' => $this->request
->getIP(),
689 /** @var RememberMeAuthenticationRequest $req */
690 $req = AuthenticationRequest
::getRequestByClass(
691 $beginReqs, RememberMeAuthenticationRequest
::class
693 $this->setSessionDataForUser( $user, $req && $req->rememberMe
);
694 $ret = AuthenticationResponse
::newPass( $user->getName() );
695 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
696 $session->remove( 'AuthManager::authnState' );
697 $this->removeAuthenticationSessionData( null );
698 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
700 } catch ( \Exception
$ex ) {
701 $session->remove( 'AuthManager::authnState' );
707 * Whether security-sensitive operations should proceed.
709 * A "security-sensitive operation" is something like a password or email
710 * change, that would normally have a "reenter your password to confirm"
711 * box if we only supported password-based authentication.
713 * @param string $operation Operation being checked. This should be a
714 * message-key-like string such as 'change-password' or 'change-email'.
715 * @return string One of the SEC_* constants.
717 public function securitySensitiveOperationStatus( $operation ) {
718 $status = self
::SEC_OK
;
720 $this->logger
->debug( __METHOD__
. ": Checking $operation" );
722 $session = $this->request
->getSession();
723 $aId = $session->getUser()->getId();
725 // User isn't authenticated. DWIM?
726 $status = $this->canAuthenticateNow() ? self
::SEC_REAUTH
: self
::SEC_FAIL
;
727 $this->logger
->info( __METHOD__
. ": Not logged in! $operation is $status" );
731 if ( $session->canSetUser() ) {
732 $id = $session->get( 'AuthManager:lastAuthId' );
733 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
734 if ( $id !== $aId ||
$last === null ) {
735 $timeSinceLogin = PHP_INT_MAX
; // Forever ago
737 $timeSinceLogin = max( 0, time() - $last );
740 $thresholds = $this->config
->get( 'ReauthenticateTime' );
741 if ( isset( $thresholds[$operation] ) ) {
742 $threshold = $thresholds[$operation];
743 } elseif ( isset( $thresholds['default'] ) ) {
744 $threshold = $thresholds['default'];
746 throw new \
UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
749 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
750 $status = self
::SEC_REAUTH
;
753 $timeSinceLogin = -1;
755 $pass = $this->config
->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
756 if ( isset( $pass[$operation] ) ) {
757 $status = $pass[$operation] ? self
::SEC_OK
: self
::SEC_FAIL
;
758 } elseif ( isset( $pass['default'] ) ) {
759 $status = $pass['default'] ? self
::SEC_OK
: self
::SEC_FAIL
;
761 throw new \
UnexpectedValueException(
762 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
767 \Hooks
::run( 'SecuritySensitiveOperationStatus', [
768 &$status, $operation, $session, $timeSinceLogin
771 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
772 if ( !$this->canAuthenticateNow() && $status === self
::SEC_REAUTH
) {
773 $status = self
::SEC_FAIL
;
776 $this->logger
->info( __METHOD__
. ": $operation is $status for '{user}'",
778 'user' => $session->getUser()->getName(),
779 'clientip' => $this->getRequest()->getIP(),
787 * Determine whether a username can authenticate
789 * This is mainly for internal purposes and only takes authentication data into account,
790 * not things like blocks that can change without the authentication system being aware.
792 * @param string $username MediaWiki username
795 public function userCanAuthenticate( $username ) {
796 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
797 if ( $provider->testUserCanAuthenticate( $username ) ) {
805 * Provide normalized versions of the username for security checks
807 * Since different providers can normalize the input in different ways,
808 * this returns an array of all the different ways the name might be
809 * normalized for authentication.
811 * The returned strings should not be revealed to the user, as that might
812 * leak private information (e.g. an email address might be normalized to a
815 * @param string $username
818 public function normalizeUsername( $username ) {
820 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
821 $normalized = $provider->providerNormalizeUsername( $username );
822 if ( $normalized !== null ) {
823 $ret[$normalized] = true;
826 return array_keys( $ret );
832 * @name Authentication data changing
837 * Revoke any authentication credentials for a user
839 * After this, the user should no longer be able to log in.
841 * @param string $username
843 public function revokeAccessForUser( $username ) {
844 $this->logger
->info( 'Revoking access for {user}', [
847 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
851 * Validate a change of authentication data (e.g. passwords)
852 * @param AuthenticationRequest $req
853 * @param bool $checkData If false, $req hasn't been loaded from the
854 * submission so checks on user-submitted fields should be skipped. $req->username is
855 * considered user-submitted for this purpose, even if it cannot be changed via
856 * $req->loadFromSubmission.
859 public function allowsAuthenticationDataChange( AuthenticationRequest
$req, $checkData = true ) {
861 $providers = $this->getPrimaryAuthenticationProviders() +
862 $this->getSecondaryAuthenticationProviders();
863 foreach ( $providers as $provider ) {
864 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
865 if ( !$status->isGood() ) {
866 return Status
::wrap( $status );
868 $any = $any ||
$status->value
!== 'ignored';
871 $status = Status
::newGood( 'ignored' );
872 $status->warning( 'authmanager-change-not-supported' );
875 return Status
::newGood();
879 * Change authentication data (e.g. passwords)
881 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
882 * result in a successful login in the future.
884 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
885 * no longer result in a successful login.
887 * This method should only be called if allowsAuthenticationDataChange( $req, true )
890 * @param AuthenticationRequest $req
891 * @param bool $isAddition Set true if this represents an addition of
892 * credentials rather than a change. The main difference is that additions
893 * should not invalidate BotPasswords. If you're not sure, leave it false.
895 public function changeAuthenticationData( AuthenticationRequest
$req, $isAddition = false ) {
896 $this->logger
->info( 'Changing authentication data for {user} class {what}', [
897 'user' => is_string( $req->username
) ?
$req->username
: '<no name>',
898 'what' => get_class( $req ),
901 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
903 // When the main account's authentication data is changed, invalidate
904 // all BotPasswords too.
905 if ( !$isAddition ) {
906 \BotPassword
::invalidateAllPasswordsForUser( $req->username
);
913 * @name Account creation
918 * Determine whether accounts can be created
921 public function canCreateAccounts() {
922 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
923 switch ( $provider->accountCreationType() ) {
924 case PrimaryAuthenticationProvider
::TYPE_CREATE
:
925 case PrimaryAuthenticationProvider
::TYPE_LINK
:
933 * Determine whether a particular account can be created
934 * @param string $username MediaWiki username
935 * @param array $options
936 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
937 * - creating: (bool) For internal use only. Never specify this.
940 public function canCreateAccount( $username, $options = [] ) {
942 if ( is_int( $options ) ) {
943 $options = [ 'flags' => $options ];
946 'flags' => User
::READ_NORMAL
,
949 $flags = $options['flags'];
951 if ( !$this->canCreateAccounts() ) {
952 return Status
::newFatal( 'authmanager-create-disabled' );
955 if ( $this->userExists( $username, $flags ) ) {
956 return Status
::newFatal( 'userexists' );
959 $user = User
::newFromName( $username, 'creatable' );
960 if ( !is_object( $user ) ) {
961 return Status
::newFatal( 'noname' );
963 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
964 if ( $user->getId() !== 0 ) {
965 return Status
::newFatal( 'userexists' );
969 // Denied by providers?
970 $providers = $this->getPreAuthenticationProviders() +
971 $this->getPrimaryAuthenticationProviders() +
972 $this->getSecondaryAuthenticationProviders();
973 foreach ( $providers as $provider ) {
974 $status = $provider->testUserForCreation( $user, false, $options );
975 if ( !$status->isGood() ) {
976 return Status
::wrap( $status );
980 return Status
::newGood();
984 * Basic permissions checks on whether a user can create accounts
985 * @param User $creator User doing the account creation
988 public function checkAccountCreatePermissions( User
$creator ) {
989 // Wiki is read-only?
990 if ( wfReadOnly() ) {
991 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
994 // This is awful, this permission check really shouldn't go through Title.
995 $permErrors = \SpecialPage
::getTitleFor( 'CreateAccount' )
996 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
998 $status = Status
::newGood();
999 foreach ( $permErrors as $args ) {
1000 $status->fatal( ...$args );
1005 $block = $creator->isBlockedFromCreateAccount();
1008 $block->getTarget(),
1009 $block->getReason() ?
: wfMessage( 'blockednoreason' )->text(),
1013 if ( $block->getType() === \Block
::TYPE_RANGE
) {
1014 $errorMessage = 'cantcreateaccount-range-text';
1015 $errorParams[] = $this->getRequest()->getIP();
1017 $errorMessage = 'cantcreateaccount-text';
1020 return Status
::newFatal( wfMessage( $errorMessage, $errorParams ) );
1023 $ip = $this->getRequest()->getIP();
1024 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1025 return Status
::newFatal( 'sorbs_create_account_reason' );
1028 return Status
::newGood();
1032 * Start an account creation flow
1034 * In addition to the AuthenticationRequests returned by
1035 * $this->getAuthenticationRequests(), a client might include a
1036 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1038 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1040 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1041 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1042 * username set, that username must be used for all other requests.
1044 * @param User $creator User doing the account creation
1045 * @param AuthenticationRequest[] $reqs
1046 * @param string $returnToUrl Url that REDIRECT responses should eventually
1048 * @return AuthenticationResponse
1050 public function beginAccountCreation( User
$creator, array $reqs, $returnToUrl ) {
1051 $session = $this->request
->getSession();
1052 if ( !$this->canCreateAccounts() ) {
1053 // Caller should have called canCreateAccounts()
1054 $session->remove( 'AuthManager::accountCreationState' );
1055 throw new \
LogicException( 'Account creation is not possible' );
1059 $username = AuthenticationRequest
::getUsernameFromRequests( $reqs );
1060 } catch ( \UnexpectedValueException
$ex ) {
1063 if ( $username === null ) {
1064 $this->logger
->debug( __METHOD__
. ': No username provided' );
1065 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1068 // Permissions check
1069 $status = $this->checkAccountCreatePermissions( $creator );
1070 if ( !$status->isGood() ) {
1071 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1072 'user' => $username,
1073 'creator' => $creator->getName(),
1074 'reason' => $status->getWikiText( null, null, 'en' )
1076 return AuthenticationResponse
::newFail( $status->getMessage() );
1079 $status = $this->canCreateAccount(
1080 $username, [ 'flags' => User
::READ_LOCKING
, 'creating' => true ]
1082 if ( !$status->isGood() ) {
1083 $this->logger
->debug( __METHOD__
. ': {user} cannot be created: {reason}', [
1084 'user' => $username,
1085 'creator' => $creator->getName(),
1086 'reason' => $status->getWikiText( null, null, 'en' )
1088 return AuthenticationResponse
::newFail( $status->getMessage() );
1091 $user = User
::newFromName( $username, 'creatable' );
1092 foreach ( $reqs as $req ) {
1093 $req->username
= $username;
1094 $req->returnToUrl
= $returnToUrl;
1095 if ( $req instanceof UserDataAuthenticationRequest
) {
1096 $status = $req->populateUser( $user );
1097 if ( !$status->isGood() ) {
1098 $status = Status
::wrap( $status );
1099 $session->remove( 'AuthManager::accountCreationState' );
1100 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1101 'user' => $user->getName(),
1102 'creator' => $creator->getName(),
1103 'reason' => $status->getWikiText( null, null, 'en' ),
1105 return AuthenticationResponse
::newFail( $status->getMessage() );
1110 $this->removeAuthenticationSessionData( null );
1113 'username' => $username,
1115 'creatorid' => $creator->getId(),
1116 'creatorname' => $creator->getName(),
1118 'returnToUrl' => $returnToUrl,
1120 'primaryResponse' => null,
1122 'continueRequests' => [],
1124 'ranPreTests' => false,
1127 // Special case: converting a login to an account creation
1128 $req = AuthenticationRequest
::getRequestByClass(
1129 $reqs, CreateFromLoginAuthenticationRequest
::class
1132 $state['maybeLink'] = $req->maybeLink
;
1134 if ( $req->createRequest
) {
1135 $reqs[] = $req->createRequest
;
1136 $state['reqs'][] = $req->createRequest
;
1140 $session->setSecret( 'AuthManager::accountCreationState', $state );
1141 $session->persist();
1143 return $this->continueAccountCreation( $reqs );
1147 * Continue an account creation flow
1148 * @param AuthenticationRequest[] $reqs
1149 * @return AuthenticationResponse
1151 public function continueAccountCreation( array $reqs ) {
1152 $session = $this->request
->getSession();
1154 if ( !$this->canCreateAccounts() ) {
1155 // Caller should have called canCreateAccounts()
1156 $session->remove( 'AuthManager::accountCreationState' );
1157 throw new \
LogicException( 'Account creation is not possible' );
1160 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1161 if ( !is_array( $state ) ) {
1162 return AuthenticationResponse
::newFail(
1163 wfMessage( 'authmanager-create-not-in-progress' )
1166 $state['continueRequests'] = [];
1168 // Step 0: Prepare and validate the input
1170 $user = User
::newFromName( $state['username'], 'creatable' );
1171 if ( !is_object( $user ) ) {
1172 $session->remove( 'AuthManager::accountCreationState' );
1173 $this->logger
->debug( __METHOD__
. ': Invalid username', [
1174 'user' => $state['username'],
1176 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1179 if ( $state['creatorid'] ) {
1180 $creator = User
::newFromId( $state['creatorid'] );
1182 $creator = new User
;
1183 $creator->setName( $state['creatorname'] );
1186 // Avoid account creation races on double submissions
1187 $cache = \ObjectCache
::getLocalClusterInstance();
1188 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1190 // Don't clear AuthManager::accountCreationState for this code
1191 // path because the process that won the race owns it.
1192 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1193 'user' => $user->getName(),
1194 'creator' => $creator->getName(),
1196 return AuthenticationResponse
::newFail( wfMessage( 'usernameinprogress' ) );
1199 // Permissions check
1200 $status = $this->checkAccountCreatePermissions( $creator );
1201 if ( !$status->isGood() ) {
1202 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1203 'user' => $user->getName(),
1204 'creator' => $creator->getName(),
1205 'reason' => $status->getWikiText( null, null, 'en' )
1207 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1208 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1209 $session->remove( 'AuthManager::accountCreationState' );
1213 // Load from master for existence check
1214 $user->load( User
::READ_LOCKING
);
1216 if ( $state['userid'] === 0 ) {
1217 if ( $user->getId() !== 0 ) {
1218 $this->logger
->debug( __METHOD__
. ': User exists locally', [
1219 'user' => $user->getName(),
1220 'creator' => $creator->getName(),
1222 $ret = AuthenticationResponse
::newFail( wfMessage( 'userexists' ) );
1223 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1224 $session->remove( 'AuthManager::accountCreationState' );
1228 if ( $user->getId() === 0 ) {
1229 $this->logger
->debug( __METHOD__
. ': User does not exist locally when it should', [
1230 'user' => $user->getName(),
1231 'creator' => $creator->getName(),
1232 'expected_id' => $state['userid'],
1234 throw new \
UnexpectedValueException(
1235 "User \"{$state['username']}\" should exist now, but doesn't!"
1238 if ( $user->getId() !== $state['userid'] ) {
1239 $this->logger
->debug( __METHOD__
. ': User ID/name mismatch', [
1240 'user' => $user->getName(),
1241 'creator' => $creator->getName(),
1242 'expected_id' => $state['userid'],
1243 'actual_id' => $user->getId(),
1245 throw new \
UnexpectedValueException(
1246 "User \"{$state['username']}\" exists, but " .
1247 "ID {$user->getId()} !== {$state['userid']}!"
1251 foreach ( $state['reqs'] as $req ) {
1252 if ( $req instanceof UserDataAuthenticationRequest
) {
1253 $status = $req->populateUser( $user );
1254 if ( !$status->isGood() ) {
1255 // This should never happen...
1256 $status = Status
::wrap( $status );
1257 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1258 'user' => $user->getName(),
1259 'creator' => $creator->getName(),
1260 'reason' => $status->getWikiText( null, null, 'en' ),
1262 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1263 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1264 $session->remove( 'AuthManager::accountCreationState' );
1270 foreach ( $reqs as $req ) {
1271 $req->returnToUrl
= $state['returnToUrl'];
1272 $req->username
= $state['username'];
1275 // Run pre-creation tests, if we haven't already
1276 if ( !$state['ranPreTests'] ) {
1277 $providers = $this->getPreAuthenticationProviders() +
1278 $this->getPrimaryAuthenticationProviders() +
1279 $this->getSecondaryAuthenticationProviders();
1280 foreach ( $providers as $id => $provider ) {
1281 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1282 if ( !$status->isGood() ) {
1283 $this->logger
->debug( __METHOD__
. ": Fail in pre-authentication by $id", [
1284 'user' => $user->getName(),
1285 'creator' => $creator->getName(),
1287 $ret = AuthenticationResponse
::newFail(
1288 Status
::wrap( $status )->getMessage()
1290 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1291 $session->remove( 'AuthManager::accountCreationState' );
1296 $state['ranPreTests'] = true;
1299 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1301 if ( $state['primary'] === null ) {
1302 // We haven't picked a PrimaryAuthenticationProvider yet
1303 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1304 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_NONE
) {
1307 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1308 switch ( $res->status
) {
1309 case AuthenticationResponse
::PASS
;
1310 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1311 'user' => $user->getName(),
1312 'creator' => $creator->getName(),
1314 $state['primary'] = $id;
1315 $state['primaryResponse'] = $res;
1317 case AuthenticationResponse
::FAIL
;
1318 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1319 'user' => $user->getName(),
1320 'creator' => $creator->getName(),
1322 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1323 $session->remove( 'AuthManager::accountCreationState' );
1325 case AuthenticationResponse
::ABSTAIN
;
1328 case AuthenticationResponse
::REDIRECT
;
1329 case AuthenticationResponse
::UI
;
1330 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1331 'user' => $user->getName(),
1332 'creator' => $creator->getName(),
1334 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1335 $state['primary'] = $id;
1336 $state['continueRequests'] = $res->neededRequests
;
1337 $session->setSecret( 'AuthManager::accountCreationState', $state );
1340 // @codeCoverageIgnoreStart
1342 throw new \
DomainException(
1343 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1345 // @codeCoverageIgnoreEnd
1348 if ( $state['primary'] === null ) {
1349 $this->logger
->debug( __METHOD__
. ': Primary creation failed because no provider accepted', [
1350 'user' => $user->getName(),
1351 'creator' => $creator->getName(),
1353 $ret = AuthenticationResponse
::newFail(
1354 wfMessage( 'authmanager-create-no-primary' )
1356 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1357 $session->remove( 'AuthManager::accountCreationState' );
1360 } elseif ( $state['primaryResponse'] === null ) {
1361 $provider = $this->getAuthenticationProvider( $state['primary'] );
1362 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1363 // Configuration changed? Force them to start over.
1364 // @codeCoverageIgnoreStart
1365 $ret = AuthenticationResponse
::newFail(
1366 wfMessage( 'authmanager-create-not-in-progress' )
1368 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1369 $session->remove( 'AuthManager::accountCreationState' );
1371 // @codeCoverageIgnoreEnd
1373 $id = $provider->getUniqueId();
1374 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1375 switch ( $res->status
) {
1376 case AuthenticationResponse
::PASS
;
1377 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1378 'user' => $user->getName(),
1379 'creator' => $creator->getName(),
1381 $state['primaryResponse'] = $res;
1383 case AuthenticationResponse
::FAIL
;
1384 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1385 'user' => $user->getName(),
1386 'creator' => $creator->getName(),
1388 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1389 $session->remove( 'AuthManager::accountCreationState' );
1391 case AuthenticationResponse
::REDIRECT
;
1392 case AuthenticationResponse
::UI
;
1393 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1394 'user' => $user->getName(),
1395 'creator' => $creator->getName(),
1397 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1398 $state['continueRequests'] = $res->neededRequests
;
1399 $session->setSecret( 'AuthManager::accountCreationState', $state );
1402 throw new \
DomainException(
1403 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1408 // Step 2: Primary authentication succeeded, create the User object
1409 // and add the user locally.
1411 if ( $state['userid'] === 0 ) {
1412 $this->logger
->info( 'Creating user {user} during account creation', [
1413 'user' => $user->getName(),
1414 'creator' => $creator->getName(),
1416 $status = $user->addToDatabase();
1417 if ( !$status->isOK() ) {
1418 // @codeCoverageIgnoreStart
1419 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1420 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1421 $session->remove( 'AuthManager::accountCreationState' );
1423 // @codeCoverageIgnoreEnd
1425 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1426 \Hooks
::run( 'LocalUserCreated', [ $user, false ] );
1427 $user->saveSettings();
1428 $state['userid'] = $user->getId();
1430 // Update user count
1431 \DeferredUpdates
::addUpdate( \SiteStatsUpdate
::factory( [ 'users' => 1 ] ) );
1433 // Watch user's userpage and talk page
1434 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1436 // Inform the provider
1437 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1440 if ( $this->config
->get( 'NewUserLog' ) ) {
1441 $isAnon = $creator->isAnon();
1442 $logEntry = new \
ManualLogEntry(
1444 $logSubtype ?
: ( $isAnon ?
'create' : 'create2' )
1446 $logEntry->setPerformer( $isAnon ?
$user : $creator );
1447 $logEntry->setTarget( $user->getUserPage() );
1448 /** @var CreationReasonAuthenticationRequest $req */
1449 $req = AuthenticationRequest
::getRequestByClass(
1450 $state['reqs'], CreationReasonAuthenticationRequest
::class
1452 $logEntry->setComment( $req ?
$req->reason
: '' );
1453 $logEntry->setParameters( [
1454 '4::userid' => $user->getId(),
1456 $logid = $logEntry->insert();
1457 $logEntry->publish( $logid );
1461 // Step 3: Iterate over all the secondary authentication providers.
1463 $beginReqs = $state['reqs'];
1465 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1466 if ( !isset( $state['secondary'][$id] ) ) {
1467 // This provider isn't started yet, so we pass it the set
1468 // of reqs from beginAuthentication instead of whatever
1469 // might have been used by a previous provider in line.
1470 $func = 'beginSecondaryAccountCreation';
1471 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1472 } elseif ( !$state['secondary'][$id] ) {
1473 $func = 'continueSecondaryAccountCreation';
1474 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1478 switch ( $res->status
) {
1479 case AuthenticationResponse
::PASS
;
1480 $this->logger
->debug( __METHOD__
. ": Secondary creation passed by $id", [
1481 'user' => $user->getName(),
1482 'creator' => $creator->getName(),
1485 case AuthenticationResponse
::ABSTAIN
;
1486 $state['secondary'][$id] = true;
1488 case AuthenticationResponse
::REDIRECT
;
1489 case AuthenticationResponse
::UI
;
1490 $this->logger
->debug( __METHOD__
. ": Secondary creation $res->status by $id", [
1491 'user' => $user->getName(),
1492 'creator' => $creator->getName(),
1494 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1495 $state['secondary'][$id] = false;
1496 $state['continueRequests'] = $res->neededRequests
;
1497 $session->setSecret( 'AuthManager::accountCreationState', $state );
1499 case AuthenticationResponse
::FAIL
;
1500 throw new \
DomainException(
1501 get_class( $provider ) . "::{$func}() returned $res->status." .
1502 ' Secondary providers are not allowed to fail account creation, that' .
1503 ' should have been done via testForAccountCreation().'
1505 // @codeCoverageIgnoreStart
1507 throw new \
DomainException(
1508 get_class( $provider ) . "::{$func}() returned $res->status"
1510 // @codeCoverageIgnoreEnd
1514 $id = $user->getId();
1515 $name = $user->getName();
1516 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1517 $ret = AuthenticationResponse
::newPass( $name );
1518 $ret->loginRequest
= $req;
1519 $this->createdAccountAuthenticationRequests
[] = $req;
1521 $this->logger
->info( __METHOD__
. ': Account creation succeeded for {user}', [
1522 'user' => $user->getName(),
1523 'creator' => $creator->getName(),
1526 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1527 $session->remove( 'AuthManager::accountCreationState' );
1528 $this->removeAuthenticationSessionData( null );
1530 } catch ( \Exception
$ex ) {
1531 $session->remove( 'AuthManager::accountCreationState' );
1537 * Auto-create an account, and log into that account
1539 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1540 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1541 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1542 * the username of a non-existing user from provideSessionInfo(). Calling this method
1543 * explicitly (e.g. from a maintenance script) is also fine.
1545 * @param User $user User to auto-create
1546 * @param string $source What caused the auto-creation? This must be one of:
1547 * - the ID of a PrimaryAuthenticationProvider,
1548 * - the constant self::AUTOCREATE_SOURCE_SESSION, or
1549 * - the constant AUTOCREATE_SOURCE_MAINT.
1550 * @param bool $login Whether to also log the user in
1551 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1553 public function autoCreateUser( User
$user, $source, $login = true ) {
1554 if ( $source !== self
::AUTOCREATE_SOURCE_SESSION
&&
1555 $source !== self
::AUTOCREATE_SOURCE_MAINT
&&
1556 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1558 throw new \
InvalidArgumentException( "Unknown auto-creation source: $source" );
1561 $username = $user->getName();
1563 // Try the local user from the replica DB
1564 $localId = User
::idFromName( $username );
1565 $flags = User
::READ_NORMAL
;
1567 // Fetch the user ID from the master, so that we don't try to create the user
1568 // when they already exist, due to replication lag
1569 // @codeCoverageIgnoreStart
1572 MediaWikiServices
::getInstance()->getDBLoadBalancer()->getReaderIndex() !== 0
1574 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1575 $flags = User
::READ_LATEST
;
1577 // @codeCoverageIgnoreEnd
1580 $this->logger
->debug( __METHOD__
. ': {username} already exists locally', [
1581 'username' => $username,
1583 $user->setId( $localId );
1584 $user->loadFromId( $flags );
1586 $this->setSessionDataForUser( $user );
1588 $status = Status
::newGood();
1589 $status->warning( 'userexists' );
1593 // Wiki is read-only?
1594 if ( wfReadOnly() ) {
1595 $this->logger
->debug( __METHOD__
. ': denied by wfReadOnly(): {reason}', [
1596 'username' => $username,
1597 'reason' => wfReadOnlyReason(),
1600 $user->loadFromId();
1601 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
1604 // Check the session, if we tried to create this user already there's
1605 // no point in retrying.
1606 $session = $this->request
->getSession();
1607 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1608 $this->logger
->debug( __METHOD__
. ': blacklisted in session {sessionid}', [
1609 'username' => $username,
1610 'sessionid' => $session->getId(),
1613 $user->loadFromId();
1614 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1615 if ( $reason instanceof StatusValue
) {
1616 return Status
::wrap( $reason );
1618 return Status
::newFatal( $reason );
1622 // Is the username creatable?
1623 if ( !User
::isCreatableName( $username ) ) {
1624 $this->logger
->debug( __METHOD__
. ': name "{username}" is not creatable', [
1625 'username' => $username,
1627 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname' );
1629 $user->loadFromId();
1630 return Status
::newFatal( 'noname' );
1633 // Is the IP user able to create accounts?
1635 if ( $source !== self
::AUTOCREATE_SOURCE_MAINT
&&
1636 !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
1638 $this->logger
->debug( __METHOD__
. ': IP lacks the ability to create or autocreate accounts', [
1639 'username' => $username,
1640 'ip' => $anon->getName(),
1642 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm' );
1643 $session->persist();
1645 $user->loadFromId();
1646 return Status
::newFatal( 'authmanager-autocreate-noperm' );
1649 // Avoid account creation races on double submissions
1650 $cache = \ObjectCache
::getLocalClusterInstance();
1651 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1653 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1654 'user' => $username,
1657 $user->loadFromId();
1658 return Status
::newFatal( 'usernameinprogress' );
1661 // Denied by providers?
1663 'flags' => User
::READ_LATEST
,
1666 $providers = $this->getPreAuthenticationProviders() +
1667 $this->getPrimaryAuthenticationProviders() +
1668 $this->getSecondaryAuthenticationProviders();
1669 foreach ( $providers as $provider ) {
1670 $status = $provider->testUserForCreation( $user, $source, $options );
1671 if ( !$status->isGood() ) {
1672 $ret = Status
::wrap( $status );
1673 $this->logger
->debug( __METHOD__
. ': Provider denied creation of {username}: {reason}', [
1674 'username' => $username,
1675 'reason' => $ret->getWikiText( null, null, 'en' ),
1677 $session->set( 'AuthManager::AutoCreateBlacklist', $status );
1679 $user->loadFromId();
1684 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1685 if ( $cache->get( $backoffKey ) ) {
1686 $this->logger
->debug( __METHOD__
. ': {username} denied by prior creation attempt failures', [
1687 'username' => $username,
1690 $user->loadFromId();
1691 return Status
::newFatal( 'authmanager-autocreate-exception' );
1694 // Checks passed, create the user...
1695 $from = $_SERVER['REQUEST_URI'] ??
'CLI';
1696 $this->logger
->info( __METHOD__
. ': creating new user ({username}) - from: {from}', [
1697 'username' => $username,
1701 // Ignore warnings about master connections/writes...hard to avoid here
1702 $trxProfiler = \Profiler
::instance()->getTransactionProfiler();
1703 $old = $trxProfiler->setSilenced( true );
1705 $status = $user->addToDatabase();
1706 if ( !$status->isOK() ) {
1707 // Double-check for a race condition (T70012). We make use of the fact that when
1708 // addToDatabase fails due to the user already existing, the user object gets loaded.
1709 if ( $user->getId() ) {
1710 $this->logger
->info( __METHOD__
. ': {username} already exists locally (race)', [
1711 'username' => $username,
1714 $this->setSessionDataForUser( $user );
1716 $status = Status
::newGood();
1717 $status->warning( 'userexists' );
1719 $this->logger
->error( __METHOD__
. ': {username} failed with message {msg}', [
1720 'username' => $username,
1721 'msg' => $status->getWikiText( null, null, 'en' )
1724 $user->loadFromId();
1728 } catch ( \Exception
$ex ) {
1729 $trxProfiler->setSilenced( $old );
1730 $this->logger
->error( __METHOD__
. ': {username} failed with exception {exception}', [
1731 'username' => $username,
1734 // Do not keep throwing errors for a while
1735 $cache->set( $backoffKey, 1, 600 );
1736 // Bubble up error; which should normally trigger DB rollbacks
1740 $this->setDefaultUserOptions( $user, false );
1742 // Inform the providers
1743 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1745 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
1746 $user->saveSettings();
1748 // Update user count
1749 \DeferredUpdates
::addUpdate( \SiteStatsUpdate
::factory( [ 'users' => 1 ] ) );
1750 // Watch user's userpage and talk page
1751 \DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1752 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1756 if ( $this->config
->get( 'NewUserLog' ) ) {
1757 $logEntry = new \
ManualLogEntry( 'newusers', 'autocreate' );
1758 $logEntry->setPerformer( $user );
1759 $logEntry->setTarget( $user->getUserPage() );
1760 $logEntry->setComment( '' );
1761 $logEntry->setParameters( [
1762 '4::userid' => $user->getId(),
1764 $logEntry->insert();
1767 $trxProfiler->setSilenced( $old );
1770 $this->setSessionDataForUser( $user );
1773 return Status
::newGood();
1779 * @name Account linking
1784 * Determine whether accounts can be linked
1787 public function canLinkAccounts() {
1788 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1789 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
) {
1797 * Start an account linking flow
1799 * @param User $user User being linked
1800 * @param AuthenticationRequest[] $reqs
1801 * @param string $returnToUrl Url that REDIRECT responses should eventually
1803 * @return AuthenticationResponse
1805 public function beginAccountLink( User
$user, array $reqs, $returnToUrl ) {
1806 $session = $this->request
->getSession();
1807 $session->remove( 'AuthManager::accountLinkState' );
1809 if ( !$this->canLinkAccounts() ) {
1810 // Caller should have called canLinkAccounts()
1811 throw new \
LogicException( 'Account linking is not possible' );
1814 if ( $user->getId() === 0 ) {
1815 if ( !User
::isUsableName( $user->getName() ) ) {
1816 $msg = wfMessage( 'noname' );
1818 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1820 return AuthenticationResponse
::newFail( $msg );
1822 foreach ( $reqs as $req ) {
1823 $req->username
= $user->getName();
1824 $req->returnToUrl
= $returnToUrl;
1827 $this->removeAuthenticationSessionData( null );
1829 $providers = $this->getPreAuthenticationProviders();
1830 foreach ( $providers as $id => $provider ) {
1831 $status = $provider->testForAccountLink( $user );
1832 if ( !$status->isGood() ) {
1833 $this->logger
->debug( __METHOD__
. ": Account linking pre-check failed by $id", [
1834 'user' => $user->getName(),
1836 $ret = AuthenticationResponse
::newFail(
1837 Status
::wrap( $status )->getMessage()
1839 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1845 'username' => $user->getName(),
1846 'userid' => $user->getId(),
1847 'returnToUrl' => $returnToUrl,
1849 'continueRequests' => [],
1852 $providers = $this->getPrimaryAuthenticationProviders();
1853 foreach ( $providers as $id => $provider ) {
1854 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider
::TYPE_LINK
) {
1858 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1859 switch ( $res->status
) {
1860 case AuthenticationResponse
::PASS
;
1861 $this->logger
->info( "Account linked to {user} by $id", [
1862 'user' => $user->getName(),
1864 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1867 case AuthenticationResponse
::FAIL
;
1868 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1869 'user' => $user->getName(),
1871 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1874 case AuthenticationResponse
::ABSTAIN
;
1878 case AuthenticationResponse
::REDIRECT
;
1879 case AuthenticationResponse
::UI
;
1880 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1881 'user' => $user->getName(),
1883 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1884 $state['primary'] = $id;
1885 $state['continueRequests'] = $res->neededRequests
;
1886 $session->setSecret( 'AuthManager::accountLinkState', $state );
1887 $session->persist();
1890 // @codeCoverageIgnoreStart
1892 throw new \
DomainException(
1893 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1895 // @codeCoverageIgnoreEnd
1899 $this->logger
->debug( __METHOD__
. ': Account linking failed because no provider accepted', [
1900 'user' => $user->getName(),
1902 $ret = AuthenticationResponse
::newFail(
1903 wfMessage( 'authmanager-link-no-primary' )
1905 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1910 * Continue an account linking flow
1911 * @param AuthenticationRequest[] $reqs
1912 * @return AuthenticationResponse
1914 public function continueAccountLink( array $reqs ) {
1915 $session = $this->request
->getSession();
1917 if ( !$this->canLinkAccounts() ) {
1918 // Caller should have called canLinkAccounts()
1919 $session->remove( 'AuthManager::accountLinkState' );
1920 throw new \
LogicException( 'Account linking is not possible' );
1923 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1924 if ( !is_array( $state ) ) {
1925 return AuthenticationResponse
::newFail(
1926 wfMessage( 'authmanager-link-not-in-progress' )
1929 $state['continueRequests'] = [];
1931 // Step 0: Prepare and validate the input
1933 $user = User
::newFromName( $state['username'], 'usable' );
1934 if ( !is_object( $user ) ) {
1935 $session->remove( 'AuthManager::accountLinkState' );
1936 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1938 if ( $user->getId() !== $state['userid'] ) {
1939 throw new \
UnexpectedValueException(
1940 "User \"{$state['username']}\" is valid, but " .
1941 "ID {$user->getId()} !== {$state['userid']}!"
1945 foreach ( $reqs as $req ) {
1946 $req->username
= $state['username'];
1947 $req->returnToUrl
= $state['returnToUrl'];
1950 // Step 1: Call the primary again until it succeeds
1952 $provider = $this->getAuthenticationProvider( $state['primary'] );
1953 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1954 // Configuration changed? Force them to start over.
1955 // @codeCoverageIgnoreStart
1956 $ret = AuthenticationResponse
::newFail(
1957 wfMessage( 'authmanager-link-not-in-progress' )
1959 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1960 $session->remove( 'AuthManager::accountLinkState' );
1962 // @codeCoverageIgnoreEnd
1964 $id = $provider->getUniqueId();
1965 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1966 switch ( $res->status
) {
1967 case AuthenticationResponse
::PASS
;
1968 $this->logger
->info( "Account linked to {user} by $id", [
1969 'user' => $user->getName(),
1971 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1972 $session->remove( 'AuthManager::accountLinkState' );
1974 case AuthenticationResponse
::FAIL
;
1975 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1976 'user' => $user->getName(),
1978 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1979 $session->remove( 'AuthManager::accountLinkState' );
1981 case AuthenticationResponse
::REDIRECT
;
1982 case AuthenticationResponse
::UI
;
1983 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1984 'user' => $user->getName(),
1986 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1987 $state['continueRequests'] = $res->neededRequests
;
1988 $session->setSecret( 'AuthManager::accountLinkState', $state );
1991 throw new \
DomainException(
1992 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1995 } catch ( \Exception
$ex ) {
1996 $session->remove( 'AuthManager::accountLinkState' );
2004 * @name Information methods
2009 * Return the applicable list of AuthenticationRequests
2011 * Possible values for $action:
2012 * - ACTION_LOGIN: Valid for passing to beginAuthentication
2013 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
2014 * - ACTION_CREATE: Valid for passing to beginAccountCreation
2015 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
2016 * - ACTION_LINK: Valid for passing to beginAccountLink
2017 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
2018 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
2019 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2020 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2022 * @param string $action One of the AuthManager::ACTION_* constants
2023 * @param User|null $user User being acted on, instead of the current user.
2024 * @return AuthenticationRequest[]
2026 public function getAuthenticationRequests( $action, User
$user = null ) {
2028 $providerAction = $action;
2030 // Figure out which providers to query
2031 switch ( $action ) {
2032 case self
::ACTION_LOGIN
:
2033 case self
::ACTION_CREATE
:
2034 $providers = $this->getPreAuthenticationProviders() +
2035 $this->getPrimaryAuthenticationProviders() +
2036 $this->getSecondaryAuthenticationProviders();
2039 case self
::ACTION_LOGIN_CONTINUE
:
2040 $state = $this->request
->getSession()->getSecret( 'AuthManager::authnState' );
2041 return is_array( $state ) ?
$state['continueRequests'] : [];
2043 case self
::ACTION_CREATE_CONTINUE
:
2044 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountCreationState' );
2045 return is_array( $state ) ?
$state['continueRequests'] : [];
2047 case self
::ACTION_LINK
:
2048 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2049 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
2053 case self
::ACTION_UNLINK
:
2054 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2055 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
2058 // To providers, unlink and remove are identical.
2059 $providerAction = self
::ACTION_REMOVE
;
2062 case self
::ACTION_LINK_CONTINUE
:
2063 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountLinkState' );
2064 return is_array( $state ) ?
$state['continueRequests'] : [];
2066 case self
::ACTION_CHANGE
:
2067 case self
::ACTION_REMOVE
:
2068 $providers = $this->getPrimaryAuthenticationProviders() +
2069 $this->getSecondaryAuthenticationProviders();
2072 // @codeCoverageIgnoreStart
2074 throw new \
DomainException( __METHOD__
. ": Invalid action \"$action\"" );
2076 // @codeCoverageIgnoreEnd
2078 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2082 * Internal request lookup for self::getAuthenticationRequests
2084 * @param string $providerAction Action to pass to providers
2085 * @param array $options Options to pass to providers
2086 * @param AuthenticationProvider[] $providers
2087 * @param User|null $user
2088 * @return AuthenticationRequest[]
2090 private function getAuthenticationRequestsInternal(
2091 $providerAction, array $options, array $providers, User
$user = null
2093 $user = $user ?
: \RequestContext
::getMain()->getUser();
2094 $options['username'] = $user->isAnon() ?
null : $user->getName();
2096 // Query them and merge results
2098 foreach ( $providers as $provider ) {
2099 $isPrimary = $provider instanceof PrimaryAuthenticationProvider
;
2100 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2101 $id = $req->getUniqueId();
2103 // If a required request if from a Primary, mark it as "primary-required" instead
2105 if ( $req->required
) {
2106 $req->required
= AuthenticationRequest
::PRIMARY_REQUIRED
;
2111 !isset( $reqs[$id] )
2112 ||
$req->required
=== AuthenticationRequest
::REQUIRED
2113 ||
$reqs[$id] === AuthenticationRequest
::OPTIONAL
2120 // AuthManager has its own req for some actions
2121 switch ( $providerAction ) {
2122 case self
::ACTION_LOGIN
:
2123 $reqs[] = new RememberMeAuthenticationRequest
;
2126 case self
::ACTION_CREATE
:
2127 $reqs[] = new UsernameAuthenticationRequest
;
2128 $reqs[] = new UserDataAuthenticationRequest
;
2129 if ( $options['username'] !== null ) {
2130 $reqs[] = new CreationReasonAuthenticationRequest
;
2131 $options['username'] = null; // Don't fill in the username below
2136 // Fill in reqs data
2137 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2139 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2140 if ( $providerAction === self
::ACTION_CHANGE ||
$providerAction === self
::ACTION_REMOVE
) {
2141 $reqs = array_filter( $reqs, function ( $req ) {
2142 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2146 return array_values( $reqs );
2150 * Set values in an array of requests
2151 * @param AuthenticationRequest[] &$reqs
2152 * @param string $action
2153 * @param string|null $username
2154 * @param bool $forceAction
2156 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2157 foreach ( $reqs as $req ) {
2158 if ( !$req->action ||
$forceAction ) {
2159 $req->action
= $action;
2161 if ( $req->username
=== null ) {
2162 $req->username
= $username;
2168 * Determine whether a username exists
2169 * @param string $username
2170 * @param int $flags Bitfield of User:READ_* constants
2173 public function userExists( $username, $flags = User
::READ_NORMAL
) {
2174 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2175 if ( $provider->testUserExists( $username, $flags ) ) {
2184 * Determine whether a user property should be allowed to be changed.
2186 * Supported properties are:
2191 * @param string $property
2194 public function allowsPropertyChange( $property ) {
2195 $providers = $this->getPrimaryAuthenticationProviders() +
2196 $this->getSecondaryAuthenticationProviders();
2197 foreach ( $providers as $provider ) {
2198 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2206 * Get a provider by ID
2207 * @note This is public so extensions can check whether their own provider
2208 * is installed and so they can read its configuration if necessary.
2209 * Other uses are not recommended.
2211 * @return AuthenticationProvider|null
2213 public function getAuthenticationProvider( $id ) {
2215 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2216 return $this->allAuthenticationProviders
[$id];
2219 // Slow version: instantiate each kind and check
2220 $providers = $this->getPrimaryAuthenticationProviders();
2221 if ( isset( $providers[$id] ) ) {
2222 return $providers[$id];
2224 $providers = $this->getSecondaryAuthenticationProviders();
2225 if ( isset( $providers[$id] ) ) {
2226 return $providers[$id];
2228 $providers = $this->getPreAuthenticationProviders();
2229 if ( isset( $providers[$id] ) ) {
2230 return $providers[$id];
2239 * @name Internal methods
2244 * Store authentication in the current session
2245 * @protected For use by AuthenticationProviders
2246 * @param string $key
2247 * @param mixed $data Must be serializable
2249 public function setAuthenticationSessionData( $key, $data ) {
2250 $session = $this->request
->getSession();
2251 $arr = $session->getSecret( 'authData' );
2252 if ( !is_array( $arr ) ) {
2256 $session->setSecret( 'authData', $arr );
2260 * Fetch authentication data from the current session
2261 * @protected For use by AuthenticationProviders
2262 * @param string $key
2263 * @param mixed|null $default
2266 public function getAuthenticationSessionData( $key, $default = null ) {
2267 $arr = $this->request
->getSession()->getSecret( 'authData' );
2268 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2276 * Remove authentication data
2277 * @protected For use by AuthenticationProviders
2278 * @param string|null $key If null, all data is removed
2280 public function removeAuthenticationSessionData( $key ) {
2281 $session = $this->request
->getSession();
2282 if ( $key === null ) {
2283 $session->remove( 'authData' );
2285 $arr = $session->getSecret( 'authData' );
2286 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2287 unset( $arr[$key] );
2288 $session->setSecret( 'authData', $arr );
2294 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2295 * @param string $class
2296 * @param array[] $specs
2297 * @return AuthenticationProvider[]
2299 protected function providerArrayFromSpecs( $class, array $specs ) {
2301 foreach ( $specs as &$spec ) {
2302 $spec = [ 'sort2' => $i++
] +
$spec +
[ 'sort' => 0 ];
2305 // Sort according to the 'sort' field, and if they are equal, according to 'sort2'
2306 usort( $specs, function ( $a, $b ) {
2307 return $a['sort'] <=> $b['sort']
2308 ?
: $a['sort2'] <=> $b['sort2'];
2312 foreach ( $specs as $spec ) {
2313 $provider = ObjectFactory
::getObjectFromSpec( $spec );
2314 if ( !$provider instanceof $class ) {
2315 throw new \
RuntimeException(
2316 "Expected instance of $class, got " . get_class( $provider )
2319 $provider->setLogger( $this->logger
);
2320 $provider->setManager( $this );
2321 $provider->setConfig( $this->config
);
2322 $id = $provider->getUniqueId();
2323 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2324 throw new \
RuntimeException(
2325 "Duplicate specifications for id $id (classes " .
2326 get_class( $provider ) . ' and ' .
2327 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
2330 $this->allAuthenticationProviders
[$id] = $provider;
2331 $ret[$id] = $provider;
2337 * Get the configuration
2340 private function getConfiguration() {
2341 return $this->config
->get( 'AuthManagerConfig' ) ?
: $this->config
->get( 'AuthManagerAutoConfig' );
2345 * Get the list of PreAuthenticationProviders
2346 * @return PreAuthenticationProvider[]
2348 protected function getPreAuthenticationProviders() {
2349 if ( $this->preAuthenticationProviders
=== null ) {
2350 $conf = $this->getConfiguration();
2351 $this->preAuthenticationProviders
= $this->providerArrayFromSpecs(
2352 PreAuthenticationProvider
::class, $conf['preauth']
2355 return $this->preAuthenticationProviders
;
2359 * Get the list of PrimaryAuthenticationProviders
2360 * @return PrimaryAuthenticationProvider[]
2362 protected function getPrimaryAuthenticationProviders() {
2363 if ( $this->primaryAuthenticationProviders
=== null ) {
2364 $conf = $this->getConfiguration();
2365 $this->primaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2366 PrimaryAuthenticationProvider
::class, $conf['primaryauth']
2369 return $this->primaryAuthenticationProviders
;
2373 * Get the list of SecondaryAuthenticationProviders
2374 * @return SecondaryAuthenticationProvider[]
2376 protected function getSecondaryAuthenticationProviders() {
2377 if ( $this->secondaryAuthenticationProviders
=== null ) {
2378 $conf = $this->getConfiguration();
2379 $this->secondaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2380 SecondaryAuthenticationProvider
::class, $conf['secondaryauth']
2383 return $this->secondaryAuthenticationProviders
;
2389 * @param bool|null $remember
2391 private function setSessionDataForUser( $user, $remember = null ) {
2392 $session = $this->request
->getSession();
2393 $delay = $session->delaySave();
2395 $session->resetId();
2396 $session->resetAllTokens();
2397 if ( $session->canSetUser() ) {
2398 $session->setUser( $user );
2400 if ( $remember !== null ) {
2401 $session->setRememberUser( $remember );
2403 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2404 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2405 $session->persist();
2407 \Wikimedia\ScopedCallback
::consume( $delay );
2409 \Hooks
::run( 'UserLoggedIn', [ $user ] );
2414 * @param bool $useContextLang Use 'uselang' to set the user's language
2416 private function setDefaultUserOptions( User
$user, $useContextLang ) {
2419 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
2421 $lang = $useContextLang ? \RequestContext
::getMain()->getLanguage() : $contLang;
2422 $user->setOption( 'language', $lang->getPreferredVariant() );
2424 if ( $contLang->hasVariants() ) {
2425 $user->setOption( 'variant', $contLang->getPreferredVariant() );
2430 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2431 * @param string $method
2432 * @param array $args
2434 private function callMethodOnProviders( $which, $method, array $args ) {
2437 $providers +
= $this->getPreAuthenticationProviders();
2440 $providers +
= $this->getPrimaryAuthenticationProviders();
2443 $providers +
= $this->getSecondaryAuthenticationProviders();
2445 foreach ( $providers as $provider ) {
2446 $provider->$method( ...$args );
2451 * Reset the internal caching for unit testing
2452 * @protected Unit tests only
2454 public static function resetCache() {
2455 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2456 // @codeCoverageIgnoreStart
2457 throw new \
MWException( __METHOD__
. ' may only be called from unit tests!' );
2458 // @codeCoverageIgnoreEnd
2461 self
::$instance = null;
2469 * For really cool vim folding this needs to be at the end:
2470 * vim: foldmarker=@{,@} foldmethod=marker