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()).
58 * If you are writing code that is not associated with such a provider and needs to create accounts
59 * programmatically for real users, you should rethink your architecture. There is no good way to
60 * do that as such code has no knowledge of what authentication methods are enabled on the wiki and
61 * cannot provide any means for users to access the accounts it would create.
63 * The two main control flows when using this class are as follows:
64 * * Login, user creation or account linking code will call getAuthenticationRequests(), populate
65 * the requests with data (by using them to build a HTMLForm and have the user fill it, or by
66 * exposing a form specification via the API, so that the client can build it), and pass them to
67 * the appropriate begin* method. That will return either a success/failure response, or more
68 * requests to fill (either by building a form or by redirecting the user to some external
69 * provider which will send the data back), in which case they need to be submitted to the
70 * appropriate continue* method and that step has to be repeated until the response is a success
71 * or failure response. AuthManager will use the session to maintain internal state during the
73 * * Code doing an authentication data change will call getAuthenticationRequests(), select
74 * a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
75 * changeAuthenticationData(). If the data change is user-initiated, the whole process needs
76 * to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
81 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
83 class AuthManager
implements LoggerAwareInterface
{
84 /** Log in with an existing (not necessarily local) user */
85 const ACTION_LOGIN
= 'login';
86 /** Continue a login process that was interrupted by the need for user input or communication
87 * with an external provider */
88 const ACTION_LOGIN_CONTINUE
= 'login-continue';
89 /** Create a new user */
90 const ACTION_CREATE
= 'create';
91 /** Continue a user creation process that was interrupted by the need for user input or
92 * communication with an external provider */
93 const ACTION_CREATE_CONTINUE
= 'create-continue';
94 /** Link an existing user to a third-party account */
95 const ACTION_LINK
= 'link';
96 /** Continue a user linking process that was interrupted by the need for user input or
97 * communication with an external provider */
98 const ACTION_LINK_CONTINUE
= 'link-continue';
99 /** Change a user's credentials */
100 const ACTION_CHANGE
= 'change';
101 /** Remove a user's credentials */
102 const ACTION_REMOVE
= 'remove';
103 /** Like ACTION_REMOVE but for linking providers only */
104 const ACTION_UNLINK
= 'unlink';
106 /** Security-sensitive operations are ok. */
108 /** Security-sensitive operations should re-authenticate. */
109 const SEC_REAUTH
= 'reauth';
110 /** Security-sensitive should not be performed. */
111 const SEC_FAIL
= 'fail';
113 /** Auto-creation is due to SessionManager */
114 const AUTOCREATE_SOURCE_SESSION
= \MediaWiki\Session\SessionManager
::class;
116 /** @var AuthManager|null */
117 private static $instance = null;
119 /** @var WebRequest */
125 /** @var LoggerInterface */
128 /** @var AuthenticationProvider[] */
129 private $allAuthenticationProviders = [];
131 /** @var PreAuthenticationProvider[] */
132 private $preAuthenticationProviders = null;
134 /** @var PrimaryAuthenticationProvider[] */
135 private $primaryAuthenticationProviders = null;
137 /** @var SecondaryAuthenticationProvider[] */
138 private $secondaryAuthenticationProviders = null;
140 /** @var CreatedAccountAuthenticationRequest[] */
141 private $createdAccountAuthenticationRequests = [];
144 * Get the global AuthManager
145 * @return AuthManager
147 public static function singleton() {
148 if ( self
::$instance === null ) {
149 self
::$instance = new self(
150 \RequestContext
::getMain()->getRequest(),
151 MediaWikiServices
::getInstance()->getMainConfig()
154 return self
::$instance;
158 * @param WebRequest $request
159 * @param Config $config
161 public function __construct( WebRequest
$request, Config
$config ) {
162 $this->request
= $request;
163 $this->config
= $config;
164 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' ) );
168 * @param LoggerInterface $logger
170 public function setLogger( LoggerInterface
$logger ) {
171 $this->logger
= $logger;
177 public function getRequest() {
178 return $this->request
;
182 * Force certain PrimaryAuthenticationProviders
183 * @deprecated For backwards compatibility only
184 * @param PrimaryAuthenticationProvider[] $providers
187 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
188 $this->logger
->warning( "Overriding AuthManager primary authn because $why" );
190 if ( $this->primaryAuthenticationProviders
!== null ) {
191 $this->logger
->warning(
192 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
195 $this->allAuthenticationProviders
= array_diff_key(
196 $this->allAuthenticationProviders
,
197 $this->primaryAuthenticationProviders
199 $session = $this->request
->getSession();
200 $session->remove( 'AuthManager::authnState' );
201 $session->remove( 'AuthManager::accountCreationState' );
202 $session->remove( 'AuthManager::accountLinkState' );
203 $this->createdAccountAuthenticationRequests
= [];
206 $this->primaryAuthenticationProviders
= [];
207 foreach ( $providers as $provider ) {
208 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
209 throw new \
RuntimeException(
210 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
211 get_class( $provider )
214 $provider->setLogger( $this->logger
);
215 $provider->setManager( $this );
216 $provider->setConfig( $this->config
);
217 $id = $provider->getUniqueId();
218 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
219 throw new \
RuntimeException(
220 "Duplicate specifications for id $id (classes " .
221 get_class( $provider ) . ' and ' .
222 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
225 $this->allAuthenticationProviders
[$id] = $provider;
226 $this->primaryAuthenticationProviders
[$id] = $provider;
231 * Call a legacy AuthPlugin method, if necessary
232 * @codeCoverageIgnore
233 * @deprecated For backwards compatibility only, should be avoided in new code
234 * @param string $method AuthPlugin method to call
235 * @param array $params Parameters to pass
236 * @param mixed $return Return value if AuthPlugin wasn't called
237 * @return mixed Return value from the AuthPlugin method, or $return
239 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
242 if ( $wgAuth && !$wgAuth instanceof AuthManagerAuthPlugin
) {
243 return call_user_func_array( [ $wgAuth, $method ], $params );
250 * @name Authentication
255 * Indicate whether user authentication is possible
257 * It may not be if the session is provided by something like OAuth
258 * for which each individual request includes authentication data.
262 public function canAuthenticateNow() {
263 return $this->request
->getSession()->canSetUser();
267 * Start an authentication flow
269 * In addition to the AuthenticationRequests returned by
270 * $this->getAuthenticationRequests(), a client might include a
271 * CreateFromLoginAuthenticationRequest from a previous login attempt to
274 * Instead of the AuthenticationRequests returned by
275 * $this->getAuthenticationRequests(), a client might pass a
276 * CreatedAccountAuthenticationRequest from an account creation that just
277 * succeeded to log in to the just-created account.
279 * @param AuthenticationRequest[] $reqs
280 * @param string $returnToUrl Url that REDIRECT responses should eventually
282 * @return AuthenticationResponse See self::continueAuthentication()
284 public function beginAuthentication( array $reqs, $returnToUrl ) {
285 $session = $this->request
->getSession();
286 if ( !$session->canSetUser() ) {
287 // Caller should have called canAuthenticateNow()
288 $session->remove( 'AuthManager::authnState' );
289 throw new \
LogicException( 'Authentication is not possible now' );
292 $guessUserName = null;
293 foreach ( $reqs as $req ) {
294 $req->returnToUrl
= $returnToUrl;
295 // @codeCoverageIgnoreStart
296 if ( $req->username
!== null && $req->username
!== '' ) {
297 if ( $guessUserName === null ) {
298 $guessUserName = $req->username
;
299 } elseif ( $guessUserName !== $req->username
) {
300 $guessUserName = null;
304 // @codeCoverageIgnoreEnd
307 // Check for special-case login of a just-created account
308 $req = AuthenticationRequest
::getRequestByClass(
309 $reqs, CreatedAccountAuthenticationRequest
::class
312 if ( !in_array( $req, $this->createdAccountAuthenticationRequests
, true ) ) {
313 throw new \
LogicException(
314 'CreatedAccountAuthenticationRequests are only valid on ' .
315 'the same AuthManager that created the account'
319 $user = User
::newFromName( $req->username
);
320 // @codeCoverageIgnoreStart
322 throw new \
UnexpectedValueException(
323 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
325 } elseif ( $user->getId() != $req->id
) {
326 throw new \
UnexpectedValueException(
327 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
330 // @codeCoverageIgnoreEnd
332 $this->logger
->info( 'Logging in {user} after account creation', [
333 'user' => $user->getName(),
335 $ret = AuthenticationResponse
::newPass( $user->getName() );
336 $this->setSessionDataForUser( $user );
337 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
338 $session->remove( 'AuthManager::authnState' );
339 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
343 $this->removeAuthenticationSessionData( null );
345 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
346 $status = $provider->testForAuthentication( $reqs );
347 if ( !$status->isGood() ) {
348 $this->logger
->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
349 $ret = AuthenticationResponse
::newFail(
350 Status
::wrap( $status )->getMessage()
352 $this->callMethodOnProviders( 7, 'postAuthentication',
353 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
355 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName ] );
362 'returnToUrl' => $returnToUrl,
363 'guessUserName' => $guessUserName,
365 'primaryResponse' => null,
368 'continueRequests' => [],
371 // Preserve state from a previous failed login
372 $req = AuthenticationRequest
::getRequestByClass(
373 $reqs, CreateFromLoginAuthenticationRequest
::class
376 $state['maybeLink'] = $req->maybeLink
;
379 $session = $this->request
->getSession();
380 $session->setSecret( 'AuthManager::authnState', $state );
383 return $this->continueAuthentication( $reqs );
387 * Continue an authentication flow
389 * Return values are interpreted as follows:
390 * - status FAIL: Authentication failed. If $response->createRequest is
391 * set, that may be passed to self::beginAuthentication() or to
392 * self::beginAccountCreation() to preserve state.
393 * - status REDIRECT: The client should be redirected to the contained URL,
394 * new AuthenticationRequests should be made (if any), then
395 * AuthManager::continueAuthentication() should be called.
396 * - status UI: The client should be presented with a user interface for
397 * the fields in the specified AuthenticationRequests, then new
398 * AuthenticationRequests should be made, then
399 * AuthManager::continueAuthentication() should be called.
400 * - status RESTART: The user logged in successfully with a third-party
401 * service, but the third-party credentials aren't attached to any local
402 * account. This could be treated as a UI or a FAIL.
403 * - status PASS: Authentication was successful.
405 * @param AuthenticationRequest[] $reqs
406 * @return AuthenticationResponse
408 public function continueAuthentication( array $reqs ) {
409 $session = $this->request
->getSession();
411 if ( !$session->canSetUser() ) {
412 // Caller should have called canAuthenticateNow()
413 // @codeCoverageIgnoreStart
414 throw new \
LogicException( 'Authentication is not possible now' );
415 // @codeCoverageIgnoreEnd
418 $state = $session->getSecret( 'AuthManager::authnState' );
419 if ( !is_array( $state ) ) {
420 return AuthenticationResponse
::newFail(
421 wfMessage( 'authmanager-authn-not-in-progress' )
424 $state['continueRequests'] = [];
426 $guessUserName = $state['guessUserName'];
428 foreach ( $reqs as $req ) {
429 $req->returnToUrl
= $state['returnToUrl'];
432 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
434 if ( $state['primary'] === null ) {
435 // We haven't picked a PrimaryAuthenticationProvider yet
436 // @codeCoverageIgnoreStart
437 $guessUserName = null;
438 foreach ( $reqs as $req ) {
439 if ( $req->username
!== null && $req->username
!== '' ) {
440 if ( $guessUserName === null ) {
441 $guessUserName = $req->username
;
442 } elseif ( $guessUserName !== $req->username
) {
443 $guessUserName = null;
448 $state['guessUserName'] = $guessUserName;
449 // @codeCoverageIgnoreEnd
450 $state['reqs'] = $reqs;
452 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
453 $res = $provider->beginPrimaryAuthentication( $reqs );
454 switch ( $res->status
) {
455 case AuthenticationResponse
::PASS
;
456 $state['primary'] = $id;
457 $state['primaryResponse'] = $res;
458 $this->logger
->debug( "Primary login with $id succeeded" );
460 case AuthenticationResponse
::FAIL
;
461 $this->logger
->debug( "Login failed in primary authentication by $id" );
462 if ( $res->createRequest ||
$state['maybeLink'] ) {
463 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
464 $res->createRequest
, $state['maybeLink']
467 $this->callMethodOnProviders( 7, 'postAuthentication',
468 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
470 $session->remove( 'AuthManager::authnState' );
471 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
473 case AuthenticationResponse
::ABSTAIN
;
476 case AuthenticationResponse
::REDIRECT
;
477 case AuthenticationResponse
::UI
;
478 $this->logger
->debug( "Primary login with $id returned $res->status" );
479 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
480 $state['primary'] = $id;
481 $state['continueRequests'] = $res->neededRequests
;
482 $session->setSecret( 'AuthManager::authnState', $state );
485 // @codeCoverageIgnoreStart
487 throw new \
DomainException(
488 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
490 // @codeCoverageIgnoreEnd
493 if ( $state['primary'] === null ) {
494 $this->logger
->debug( 'Login failed in primary authentication because no provider accepted' );
495 $ret = AuthenticationResponse
::newFail(
496 wfMessage( 'authmanager-authn-no-primary' )
498 $this->callMethodOnProviders( 7, 'postAuthentication',
499 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
501 $session->remove( 'AuthManager::authnState' );
504 } elseif ( $state['primaryResponse'] === null ) {
505 $provider = $this->getAuthenticationProvider( $state['primary'] );
506 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
507 // Configuration changed? Force them to start over.
508 // @codeCoverageIgnoreStart
509 $ret = AuthenticationResponse
::newFail(
510 wfMessage( 'authmanager-authn-not-in-progress' )
512 $this->callMethodOnProviders( 7, 'postAuthentication',
513 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
515 $session->remove( 'AuthManager::authnState' );
517 // @codeCoverageIgnoreEnd
519 $id = $provider->getUniqueId();
520 $res = $provider->continuePrimaryAuthentication( $reqs );
521 switch ( $res->status
) {
522 case AuthenticationResponse
::PASS
;
523 $state['primaryResponse'] = $res;
524 $this->logger
->debug( "Primary login with $id succeeded" );
526 case AuthenticationResponse
::FAIL
;
527 $this->logger
->debug( "Login failed in primary authentication by $id" );
528 if ( $res->createRequest ||
$state['maybeLink'] ) {
529 $res->createRequest
= new CreateFromLoginAuthenticationRequest(
530 $res->createRequest
, $state['maybeLink']
533 $this->callMethodOnProviders( 7, 'postAuthentication',
534 [ User
::newFromName( $guessUserName ) ?
: null, $res ]
536 $session->remove( 'AuthManager::authnState' );
537 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
539 case AuthenticationResponse
::REDIRECT
;
540 case AuthenticationResponse
::UI
;
541 $this->logger
->debug( "Primary login with $id returned $res->status" );
542 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $guessUserName );
543 $state['continueRequests'] = $res->neededRequests
;
544 $session->setSecret( 'AuthManager::authnState', $state );
547 throw new \
DomainException(
548 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
553 $res = $state['primaryResponse'];
554 if ( $res->username
=== null ) {
555 $provider = $this->getAuthenticationProvider( $state['primary'] );
556 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
557 // Configuration changed? Force them to start over.
558 // @codeCoverageIgnoreStart
559 $ret = AuthenticationResponse
::newFail(
560 wfMessage( 'authmanager-authn-not-in-progress' )
562 $this->callMethodOnProviders( 7, 'postAuthentication',
563 [ User
::newFromName( $guessUserName ) ?
: null, $ret ]
565 $session->remove( 'AuthManager::authnState' );
567 // @codeCoverageIgnoreEnd
570 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
&&
572 // don't confuse the user with an incorrect message if linking is disabled
573 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider
::class )
575 $state['maybeLink'][$res->linkRequest
->getUniqueId()] = $res->linkRequest
;
576 $msg = 'authmanager-authn-no-local-user-link';
578 $msg = 'authmanager-authn-no-local-user';
580 $this->logger
->debug(
581 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
583 $ret = AuthenticationResponse
::newRestart( wfMessage( $msg ) );
584 $ret->neededRequests
= $this->getAuthenticationRequestsInternal(
587 $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders()
589 if ( $res->createRequest ||
$state['maybeLink'] ) {
590 $ret->createRequest
= new CreateFromLoginAuthenticationRequest(
591 $res->createRequest
, $state['maybeLink']
593 $ret->neededRequests
[] = $ret->createRequest
;
595 $this->fillRequests( $ret->neededRequests
, self
::ACTION_LOGIN
, null, true );
596 $session->setSecret( 'AuthManager::authnState', [
597 'reqs' => [], // Will be filled in later
599 'primaryResponse' => null,
601 'continueRequests' => $ret->neededRequests
,
606 // Step 2: Primary authentication succeeded, create the User object
607 // (and add the user locally if necessary)
609 $user = User
::newFromName( $res->username
, 'usable' );
611 $provider = $this->getAuthenticationProvider( $state['primary'] );
612 throw new \
DomainException(
613 get_class( $provider ) . " returned an invalid username: {$res->username}"
616 if ( $user->getId() === 0 ) {
617 // User doesn't exist locally. Create it.
618 $this->logger
->info( 'Auto-creating {user} on login', [
619 'user' => $user->getName(),
621 $status = $this->autoCreateUser( $user, $state['primary'], false );
622 if ( !$status->isGood() ) {
623 $ret = AuthenticationResponse
::newFail(
624 Status
::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
626 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
627 $session->remove( 'AuthManager::authnState' );
628 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
633 // Step 3: Iterate over all the secondary authentication providers.
635 $beginReqs = $state['reqs'];
637 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
638 if ( !isset( $state['secondary'][$id] ) ) {
639 // This provider isn't started yet, so we pass it the set
640 // of reqs from beginAuthentication instead of whatever
641 // might have been used by a previous provider in line.
642 $func = 'beginSecondaryAuthentication';
643 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
644 } elseif ( !$state['secondary'][$id] ) {
645 $func = 'continueSecondaryAuthentication';
646 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
650 switch ( $res->status
) {
651 case AuthenticationResponse
::PASS
;
652 $this->logger
->debug( "Secondary login with $id succeeded" );
654 case AuthenticationResponse
::ABSTAIN
;
655 $state['secondary'][$id] = true;
657 case AuthenticationResponse
::FAIL
;
658 $this->logger
->debug( "Login failed in secondary authentication by $id" );
659 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
660 $session->remove( 'AuthManager::authnState' );
661 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName() ] );
663 case AuthenticationResponse
::REDIRECT
;
664 case AuthenticationResponse
::UI
;
665 $this->logger
->debug( "Secondary login with $id returned " . $res->status
);
666 $this->fillRequests( $res->neededRequests
, self
::ACTION_LOGIN
, $user->getName() );
667 $state['secondary'][$id] = false;
668 $state['continueRequests'] = $res->neededRequests
;
669 $session->setSecret( 'AuthManager::authnState', $state );
672 // @codeCoverageIgnoreStart
674 throw new \
DomainException(
675 get_class( $provider ) . "::{$func}() returned $res->status"
677 // @codeCoverageIgnoreEnd
681 // Step 4: Authentication complete! Set the user in the session and
684 $this->logger
->info( 'Login for {user} succeeded', [
685 'user' => $user->getName(),
687 /** @var RememberMeAuthenticationRequest $req */
688 $req = AuthenticationRequest
::getRequestByClass(
689 $beginReqs, RememberMeAuthenticationRequest
::class
691 $this->setSessionDataForUser( $user, $req && $req->rememberMe
);
692 $ret = AuthenticationResponse
::newPass( $user->getName() );
693 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
694 $session->remove( 'AuthManager::authnState' );
695 $this->removeAuthenticationSessionData( null );
696 \Hooks
::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
698 } catch ( \Exception
$ex ) {
699 $session->remove( 'AuthManager::authnState' );
705 * Whether security-sensitive operations should proceed.
707 * A "security-sensitive operation" is something like a password or email
708 * change, that would normally have a "reenter your password to confirm"
709 * box if we only supported password-based authentication.
711 * @param string $operation Operation being checked. This should be a
712 * message-key-like string such as 'change-password' or 'change-email'.
713 * @return string One of the SEC_* constants.
715 public function securitySensitiveOperationStatus( $operation ) {
716 $status = self
::SEC_OK
;
718 $this->logger
->debug( __METHOD__
. ": Checking $operation" );
720 $session = $this->request
->getSession();
721 $aId = $session->getUser()->getId();
723 // User isn't authenticated. DWIM?
724 $status = $this->canAuthenticateNow() ? self
::SEC_REAUTH
: self
::SEC_FAIL
;
725 $this->logger
->info( __METHOD__
. ": Not logged in! $operation is $status" );
729 if ( $session->canSetUser() ) {
730 $id = $session->get( 'AuthManager:lastAuthId' );
731 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
732 if ( $id !== $aId ||
$last === null ) {
733 $timeSinceLogin = PHP_INT_MAX
; // Forever ago
735 $timeSinceLogin = max( 0, time() - $last );
738 $thresholds = $this->config
->get( 'ReauthenticateTime' );
739 if ( isset( $thresholds[$operation] ) ) {
740 $threshold = $thresholds[$operation];
741 } elseif ( isset( $thresholds['default'] ) ) {
742 $threshold = $thresholds['default'];
744 throw new \
UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
747 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
748 $status = self
::SEC_REAUTH
;
751 $timeSinceLogin = -1;
753 $pass = $this->config
->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
754 if ( isset( $pass[$operation] ) ) {
755 $status = $pass[$operation] ? self
::SEC_OK
: self
::SEC_FAIL
;
756 } elseif ( isset( $pass['default'] ) ) {
757 $status = $pass['default'] ? self
::SEC_OK
: self
::SEC_FAIL
;
759 throw new \
UnexpectedValueException(
760 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
765 \Hooks
::run( 'SecuritySensitiveOperationStatus', [
766 &$status, $operation, $session, $timeSinceLogin
769 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
770 if ( !$this->canAuthenticateNow() && $status === self
::SEC_REAUTH
) {
771 $status = self
::SEC_FAIL
;
774 $this->logger
->info( __METHOD__
. ": $operation is $status" );
780 * Determine whether a username can authenticate
782 * This is mainly for internal purposes and only takes authentication data into account,
783 * not things like blocks that can change without the authentication system being aware.
785 * @param string $username MediaWiki username
788 public function userCanAuthenticate( $username ) {
789 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
790 if ( $provider->testUserCanAuthenticate( $username ) ) {
798 * Provide normalized versions of the username for security checks
800 * Since different providers can normalize the input in different ways,
801 * this returns an array of all the different ways the name might be
802 * normalized for authentication.
804 * The returned strings should not be revealed to the user, as that might
805 * leak private information (e.g. an email address might be normalized to a
808 * @param string $username
811 public function normalizeUsername( $username ) {
813 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
814 $normalized = $provider->providerNormalizeUsername( $username );
815 if ( $normalized !== null ) {
816 $ret[$normalized] = true;
819 return array_keys( $ret );
825 * @name Authentication data changing
830 * Revoke any authentication credentials for a user
832 * After this, the user should no longer be able to log in.
834 * @param string $username
836 public function revokeAccessForUser( $username ) {
837 $this->logger
->info( 'Revoking access for {user}', [
840 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
844 * Validate a change of authentication data (e.g. passwords)
845 * @param AuthenticationRequest $req
846 * @param bool $checkData If false, $req hasn't been loaded from the
847 * submission so checks on user-submitted fields should be skipped. $req->username is
848 * considered user-submitted for this purpose, even if it cannot be changed via
849 * $req->loadFromSubmission.
852 public function allowsAuthenticationDataChange( AuthenticationRequest
$req, $checkData = true ) {
854 $providers = $this->getPrimaryAuthenticationProviders() +
855 $this->getSecondaryAuthenticationProviders();
856 foreach ( $providers as $provider ) {
857 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
858 if ( !$status->isGood() ) {
859 return Status
::wrap( $status );
861 $any = $any ||
$status->value
!== 'ignored';
864 $status = Status
::newGood( 'ignored' );
865 $status->warning( 'authmanager-change-not-supported' );
868 return Status
::newGood();
872 * Change authentication data (e.g. passwords)
874 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
875 * result in a successful login in the future.
877 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
878 * no longer result in a successful login.
880 * This method should only be called if allowsAuthenticationDataChange( $req, true )
883 * @param AuthenticationRequest $req
885 public function changeAuthenticationData( AuthenticationRequest
$req ) {
886 $this->logger
->info( 'Changing authentication data for {user} class {what}', [
887 'user' => is_string( $req->username
) ?
$req->username
: '<no name>',
888 'what' => get_class( $req ),
891 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
893 // When the main account's authentication data is changed, invalidate
894 // all BotPasswords too.
895 \BotPassword
::invalidateAllPasswordsForUser( $req->username
);
901 * @name Account creation
906 * Determine whether accounts can be created
909 public function canCreateAccounts() {
910 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
911 switch ( $provider->accountCreationType() ) {
912 case PrimaryAuthenticationProvider
::TYPE_CREATE
:
913 case PrimaryAuthenticationProvider
::TYPE_LINK
:
921 * Determine whether a particular account can be created
922 * @param string $username MediaWiki username
923 * @param array $options
924 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
925 * - creating: (bool) For internal use only. Never specify this.
928 public function canCreateAccount( $username, $options = [] ) {
930 if ( is_int( $options ) ) {
931 $options = [ 'flags' => $options ];
934 'flags' => User
::READ_NORMAL
,
937 $flags = $options['flags'];
939 if ( !$this->canCreateAccounts() ) {
940 return Status
::newFatal( 'authmanager-create-disabled' );
943 if ( $this->userExists( $username, $flags ) ) {
944 return Status
::newFatal( 'userexists' );
947 $user = User
::newFromName( $username, 'creatable' );
948 if ( !is_object( $user ) ) {
949 return Status
::newFatal( 'noname' );
951 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
952 if ( $user->getId() !== 0 ) {
953 return Status
::newFatal( 'userexists' );
957 // Denied by providers?
958 $providers = $this->getPreAuthenticationProviders() +
959 $this->getPrimaryAuthenticationProviders() +
960 $this->getSecondaryAuthenticationProviders();
961 foreach ( $providers as $provider ) {
962 $status = $provider->testUserForCreation( $user, false, $options );
963 if ( !$status->isGood() ) {
964 return Status
::wrap( $status );
968 return Status
::newGood();
972 * Basic permissions checks on whether a user can create accounts
973 * @param User $creator User doing the account creation
976 public function checkAccountCreatePermissions( User
$creator ) {
977 // Wiki is read-only?
978 if ( wfReadOnly() ) {
979 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
982 // This is awful, this permission check really shouldn't go through Title.
983 $permErrors = \SpecialPage
::getTitleFor( 'CreateAccount' )
984 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
986 $status = Status
::newGood();
987 foreach ( $permErrors as $args ) {
988 call_user_func_array( [ $status, 'fatal' ], $args );
993 $block = $creator->isBlockedFromCreateAccount();
997 $block->mReason ?
: wfMessage( 'blockednoreason' )->text(),
1001 if ( $block->getType() === \Block
::TYPE_RANGE
) {
1002 $errorMessage = 'cantcreateaccount-range-text';
1003 $errorParams[] = $this->getRequest()->getIP();
1005 $errorMessage = 'cantcreateaccount-text';
1008 return Status
::newFatal( wfMessage( $errorMessage, $errorParams ) );
1011 $ip = $this->getRequest()->getIP();
1012 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1013 return Status
::newFatal( 'sorbs_create_account_reason' );
1016 return Status
::newGood();
1020 * Start an account creation flow
1022 * In addition to the AuthenticationRequests returned by
1023 * $this->getAuthenticationRequests(), a client might include a
1024 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1026 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1028 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1029 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1030 * username set, that username must be used for all other requests.
1032 * @param User $creator User doing the account creation
1033 * @param AuthenticationRequest[] $reqs
1034 * @param string $returnToUrl Url that REDIRECT responses should eventually
1036 * @return AuthenticationResponse
1038 public function beginAccountCreation( User
$creator, array $reqs, $returnToUrl ) {
1039 $session = $this->request
->getSession();
1040 if ( !$this->canCreateAccounts() ) {
1041 // Caller should have called canCreateAccounts()
1042 $session->remove( 'AuthManager::accountCreationState' );
1043 throw new \
LogicException( 'Account creation is not possible' );
1047 $username = AuthenticationRequest
::getUsernameFromRequests( $reqs );
1048 } catch ( \UnexpectedValueException
$ex ) {
1051 if ( $username === null ) {
1052 $this->logger
->debug( __METHOD__
. ': No username provided' );
1053 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1056 // Permissions check
1057 $status = $this->checkAccountCreatePermissions( $creator );
1058 if ( !$status->isGood() ) {
1059 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1060 'user' => $username,
1061 'creator' => $creator->getName(),
1062 'reason' => $status->getWikiText( null, null, 'en' )
1064 return AuthenticationResponse
::newFail( $status->getMessage() );
1067 $status = $this->canCreateAccount(
1068 $username, [ 'flags' => User
::READ_LOCKING
, 'creating' => true ]
1070 if ( !$status->isGood() ) {
1071 $this->logger
->debug( __METHOD__
. ': {user} cannot be created: {reason}', [
1072 'user' => $username,
1073 'creator' => $creator->getName(),
1074 'reason' => $status->getWikiText( null, null, 'en' )
1076 return AuthenticationResponse
::newFail( $status->getMessage() );
1079 $user = User
::newFromName( $username, 'creatable' );
1080 foreach ( $reqs as $req ) {
1081 $req->username
= $username;
1082 $req->returnToUrl
= $returnToUrl;
1083 if ( $req instanceof UserDataAuthenticationRequest
) {
1084 $status = $req->populateUser( $user );
1085 if ( !$status->isGood() ) {
1086 $status = Status
::wrap( $status );
1087 $session->remove( 'AuthManager::accountCreationState' );
1088 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1089 'user' => $user->getName(),
1090 'creator' => $creator->getName(),
1091 'reason' => $status->getWikiText( null, null, 'en' ),
1093 return AuthenticationResponse
::newFail( $status->getMessage() );
1098 $this->removeAuthenticationSessionData( null );
1101 'username' => $username,
1103 'creatorid' => $creator->getId(),
1104 'creatorname' => $creator->getName(),
1106 'returnToUrl' => $returnToUrl,
1108 'primaryResponse' => null,
1110 'continueRequests' => [],
1112 'ranPreTests' => false,
1115 // Special case: converting a login to an account creation
1116 $req = AuthenticationRequest
::getRequestByClass(
1117 $reqs, CreateFromLoginAuthenticationRequest
::class
1120 $state['maybeLink'] = $req->maybeLink
;
1122 if ( $req->createRequest
) {
1123 $reqs[] = $req->createRequest
;
1124 $state['reqs'][] = $req->createRequest
;
1128 $session->setSecret( 'AuthManager::accountCreationState', $state );
1129 $session->persist();
1131 return $this->continueAccountCreation( $reqs );
1135 * Continue an account creation flow
1136 * @param AuthenticationRequest[] $reqs
1137 * @return AuthenticationResponse
1139 public function continueAccountCreation( array $reqs ) {
1140 $session = $this->request
->getSession();
1142 if ( !$this->canCreateAccounts() ) {
1143 // Caller should have called canCreateAccounts()
1144 $session->remove( 'AuthManager::accountCreationState' );
1145 throw new \
LogicException( 'Account creation is not possible' );
1148 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1149 if ( !is_array( $state ) ) {
1150 return AuthenticationResponse
::newFail(
1151 wfMessage( 'authmanager-create-not-in-progress' )
1154 $state['continueRequests'] = [];
1156 // Step 0: Prepare and validate the input
1158 $user = User
::newFromName( $state['username'], 'creatable' );
1159 if ( !is_object( $user ) ) {
1160 $session->remove( 'AuthManager::accountCreationState' );
1161 $this->logger
->debug( __METHOD__
. ': Invalid username', [
1162 'user' => $state['username'],
1164 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1167 if ( $state['creatorid'] ) {
1168 $creator = User
::newFromId( $state['creatorid'] );
1170 $creator = new User
;
1171 $creator->setName( $state['creatorname'] );
1174 // Avoid account creation races on double submissions
1175 $cache = \ObjectCache
::getLocalClusterInstance();
1176 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1178 // Don't clear AuthManager::accountCreationState for this code
1179 // path because the process that won the race owns it.
1180 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1181 'user' => $user->getName(),
1182 'creator' => $creator->getName(),
1184 return AuthenticationResponse
::newFail( wfMessage( 'usernameinprogress' ) );
1187 // Permissions check
1188 $status = $this->checkAccountCreatePermissions( $creator );
1189 if ( !$status->isGood() ) {
1190 $this->logger
->debug( __METHOD__
. ': {creator} cannot create users: {reason}', [
1191 'user' => $user->getName(),
1192 'creator' => $creator->getName(),
1193 'reason' => $status->getWikiText( null, null, 'en' )
1195 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1196 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1197 $session->remove( 'AuthManager::accountCreationState' );
1201 // Load from master for existence check
1202 $user->load( User
::READ_LOCKING
);
1204 if ( $state['userid'] === 0 ) {
1205 if ( $user->getId() != 0 ) {
1206 $this->logger
->debug( __METHOD__
. ': User exists locally', [
1207 'user' => $user->getName(),
1208 'creator' => $creator->getName(),
1210 $ret = AuthenticationResponse
::newFail( wfMessage( 'userexists' ) );
1211 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1212 $session->remove( 'AuthManager::accountCreationState' );
1216 if ( $user->getId() == 0 ) {
1217 $this->logger
->debug( __METHOD__
. ': User does not exist locally when it should', [
1218 'user' => $user->getName(),
1219 'creator' => $creator->getName(),
1220 'expected_id' => $state['userid'],
1222 throw new \
UnexpectedValueException(
1223 "User \"{$state['username']}\" should exist now, but doesn't!"
1226 if ( $user->getId() != $state['userid'] ) {
1227 $this->logger
->debug( __METHOD__
. ': User ID/name mismatch', [
1228 'user' => $user->getName(),
1229 'creator' => $creator->getName(),
1230 'expected_id' => $state['userid'],
1231 'actual_id' => $user->getId(),
1233 throw new \
UnexpectedValueException(
1234 "User \"{$state['username']}\" exists, but " .
1235 "ID {$user->getId()} != {$state['userid']}!"
1239 foreach ( $state['reqs'] as $req ) {
1240 if ( $req instanceof UserDataAuthenticationRequest
) {
1241 $status = $req->populateUser( $user );
1242 if ( !$status->isGood() ) {
1243 // This should never happen...
1244 $status = Status
::wrap( $status );
1245 $this->logger
->debug( __METHOD__
. ': UserData is invalid: {reason}', [
1246 'user' => $user->getName(),
1247 'creator' => $creator->getName(),
1248 'reason' => $status->getWikiText( null, null, 'en' ),
1250 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1251 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1252 $session->remove( 'AuthManager::accountCreationState' );
1258 foreach ( $reqs as $req ) {
1259 $req->returnToUrl
= $state['returnToUrl'];
1260 $req->username
= $state['username'];
1263 // Run pre-creation tests, if we haven't already
1264 if ( !$state['ranPreTests'] ) {
1265 $providers = $this->getPreAuthenticationProviders() +
1266 $this->getPrimaryAuthenticationProviders() +
1267 $this->getSecondaryAuthenticationProviders();
1268 foreach ( $providers as $id => $provider ) {
1269 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1270 if ( !$status->isGood() ) {
1271 $this->logger
->debug( __METHOD__
. ": Fail in pre-authentication by $id", [
1272 'user' => $user->getName(),
1273 'creator' => $creator->getName(),
1275 $ret = AuthenticationResponse
::newFail(
1276 Status
::wrap( $status )->getMessage()
1278 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1279 $session->remove( 'AuthManager::accountCreationState' );
1284 $state['ranPreTests'] = true;
1287 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1289 if ( $state['primary'] === null ) {
1290 // We haven't picked a PrimaryAuthenticationProvider yet
1291 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1292 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_NONE
) {
1295 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1296 switch ( $res->status
) {
1297 case AuthenticationResponse
::PASS
;
1298 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1299 'user' => $user->getName(),
1300 'creator' => $creator->getName(),
1302 $state['primary'] = $id;
1303 $state['primaryResponse'] = $res;
1305 case AuthenticationResponse
::FAIL
;
1306 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1307 'user' => $user->getName(),
1308 'creator' => $creator->getName(),
1310 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1311 $session->remove( 'AuthManager::accountCreationState' );
1313 case AuthenticationResponse
::ABSTAIN
;
1316 case AuthenticationResponse
::REDIRECT
;
1317 case AuthenticationResponse
::UI
;
1318 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1319 'user' => $user->getName(),
1320 'creator' => $creator->getName(),
1322 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1323 $state['primary'] = $id;
1324 $state['continueRequests'] = $res->neededRequests
;
1325 $session->setSecret( 'AuthManager::accountCreationState', $state );
1328 // @codeCoverageIgnoreStart
1330 throw new \
DomainException(
1331 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1333 // @codeCoverageIgnoreEnd
1336 if ( $state['primary'] === null ) {
1337 $this->logger
->debug( __METHOD__
. ': Primary creation failed because no provider accepted', [
1338 'user' => $user->getName(),
1339 'creator' => $creator->getName(),
1341 $ret = AuthenticationResponse
::newFail(
1342 wfMessage( 'authmanager-create-no-primary' )
1344 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1345 $session->remove( 'AuthManager::accountCreationState' );
1348 } elseif ( $state['primaryResponse'] === null ) {
1349 $provider = $this->getAuthenticationProvider( $state['primary'] );
1350 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1351 // Configuration changed? Force them to start over.
1352 // @codeCoverageIgnoreStart
1353 $ret = AuthenticationResponse
::newFail(
1354 wfMessage( 'authmanager-create-not-in-progress' )
1356 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1357 $session->remove( 'AuthManager::accountCreationState' );
1359 // @codeCoverageIgnoreEnd
1361 $id = $provider->getUniqueId();
1362 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1363 switch ( $res->status
) {
1364 case AuthenticationResponse
::PASS
;
1365 $this->logger
->debug( __METHOD__
. ": Primary creation passed by $id", [
1366 'user' => $user->getName(),
1367 'creator' => $creator->getName(),
1369 $state['primaryResponse'] = $res;
1371 case AuthenticationResponse
::FAIL
;
1372 $this->logger
->debug( __METHOD__
. ": Primary creation failed by $id", [
1373 'user' => $user->getName(),
1374 'creator' => $creator->getName(),
1376 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1377 $session->remove( 'AuthManager::accountCreationState' );
1379 case AuthenticationResponse
::REDIRECT
;
1380 case AuthenticationResponse
::UI
;
1381 $this->logger
->debug( __METHOD__
. ": Primary creation $res->status by $id", [
1382 'user' => $user->getName(),
1383 'creator' => $creator->getName(),
1385 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1386 $state['continueRequests'] = $res->neededRequests
;
1387 $session->setSecret( 'AuthManager::accountCreationState', $state );
1390 throw new \
DomainException(
1391 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1396 // Step 2: Primary authentication succeeded, create the User object
1397 // and add the user locally.
1399 if ( $state['userid'] === 0 ) {
1400 $this->logger
->info( 'Creating user {user} during account creation', [
1401 'user' => $user->getName(),
1402 'creator' => $creator->getName(),
1404 $status = $user->addToDatabase();
1405 if ( !$status->isOK() ) {
1406 // @codeCoverageIgnoreStart
1407 $ret = AuthenticationResponse
::newFail( $status->getMessage() );
1408 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1409 $session->remove( 'AuthManager::accountCreationState' );
1411 // @codeCoverageIgnoreEnd
1413 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1414 \Hooks
::run( 'LocalUserCreated', [ $user, false ] );
1415 $user->saveSettings();
1416 $state['userid'] = $user->getId();
1418 // Update user count
1419 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1421 // Watch user's userpage and talk page
1422 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1424 // Inform the provider
1425 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1428 if ( $this->config
->get( 'NewUserLog' ) ) {
1429 $isAnon = $creator->isAnon();
1430 $logEntry = new \
ManualLogEntry(
1432 $logSubtype ?
: ( $isAnon ?
'create' : 'create2' )
1434 $logEntry->setPerformer( $isAnon ?
$user : $creator );
1435 $logEntry->setTarget( $user->getUserPage() );
1436 /** @var CreationReasonAuthenticationRequest $req */
1437 $req = AuthenticationRequest
::getRequestByClass(
1438 $state['reqs'], CreationReasonAuthenticationRequest
::class
1440 $logEntry->setComment( $req ?
$req->reason
: '' );
1441 $logEntry->setParameters( [
1442 '4::userid' => $user->getId(),
1444 $logid = $logEntry->insert();
1445 $logEntry->publish( $logid );
1449 // Step 3: Iterate over all the secondary authentication providers.
1451 $beginReqs = $state['reqs'];
1453 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1454 if ( !isset( $state['secondary'][$id] ) ) {
1455 // This provider isn't started yet, so we pass it the set
1456 // of reqs from beginAuthentication instead of whatever
1457 // might have been used by a previous provider in line.
1458 $func = 'beginSecondaryAccountCreation';
1459 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1460 } elseif ( !$state['secondary'][$id] ) {
1461 $func = 'continueSecondaryAccountCreation';
1462 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1466 switch ( $res->status
) {
1467 case AuthenticationResponse
::PASS
;
1468 $this->logger
->debug( __METHOD__
. ": Secondary creation passed by $id", [
1469 'user' => $user->getName(),
1470 'creator' => $creator->getName(),
1473 case AuthenticationResponse
::ABSTAIN
;
1474 $state['secondary'][$id] = true;
1476 case AuthenticationResponse
::REDIRECT
;
1477 case AuthenticationResponse
::UI
;
1478 $this->logger
->debug( __METHOD__
. ": Secondary creation $res->status by $id", [
1479 'user' => $user->getName(),
1480 'creator' => $creator->getName(),
1482 $this->fillRequests( $res->neededRequests
, self
::ACTION_CREATE
, null );
1483 $state['secondary'][$id] = false;
1484 $state['continueRequests'] = $res->neededRequests
;
1485 $session->setSecret( 'AuthManager::accountCreationState', $state );
1487 case AuthenticationResponse
::FAIL
;
1488 throw new \
DomainException(
1489 get_class( $provider ) . "::{$func}() returned $res->status." .
1490 ' Secondary providers are not allowed to fail account creation, that' .
1491 ' should have been done via testForAccountCreation().'
1493 // @codeCoverageIgnoreStart
1495 throw new \
DomainException(
1496 get_class( $provider ) . "::{$func}() returned $res->status"
1498 // @codeCoverageIgnoreEnd
1502 $id = $user->getId();
1503 $name = $user->getName();
1504 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1505 $ret = AuthenticationResponse
::newPass( $name );
1506 $ret->loginRequest
= $req;
1507 $this->createdAccountAuthenticationRequests
[] = $req;
1509 $this->logger
->info( __METHOD__
. ': Account creation succeeded for {user}', [
1510 'user' => $user->getName(),
1511 'creator' => $creator->getName(),
1514 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1515 $session->remove( 'AuthManager::accountCreationState' );
1516 $this->removeAuthenticationSessionData( null );
1518 } catch ( \Exception
$ex ) {
1519 $session->remove( 'AuthManager::accountCreationState' );
1525 * Auto-create an account, and log into that account
1527 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1528 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1529 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1530 * the username of a non-existing user from provideSessionInfo(). Calling this method
1531 * explicitly (e.g. from a maintenance script) is also fine.
1533 * @param User $user User to auto-create
1534 * @param string $source What caused the auto-creation? This must be the ID
1535 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1536 * @param bool $login Whether to also log the user in
1537 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1539 public function autoCreateUser( User
$user, $source, $login = true ) {
1540 if ( $source !== self
::AUTOCREATE_SOURCE_SESSION
&&
1541 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1543 throw new \
InvalidArgumentException( "Unknown auto-creation source: $source" );
1546 $username = $user->getName();
1548 // Try the local user from the replica DB
1549 $localId = User
::idFromName( $username );
1550 $flags = User
::READ_NORMAL
;
1552 // Fetch the user ID from the master, so that we don't try to create the user
1553 // when they already exist, due to replication lag
1554 // @codeCoverageIgnoreStart
1557 MediaWikiServices
::getInstance()->getDBLoadBalancer()->getReaderIndex() != 0
1559 $localId = User
::idFromName( $username, User
::READ_LATEST
);
1560 $flags = User
::READ_LATEST
;
1562 // @codeCoverageIgnoreEnd
1565 $this->logger
->debug( __METHOD__
. ': {username} already exists locally', [
1566 'username' => $username,
1568 $user->setId( $localId );
1569 $user->loadFromId( $flags );
1571 $this->setSessionDataForUser( $user );
1573 $status = Status
::newGood();
1574 $status->warning( 'userexists' );
1578 // Wiki is read-only?
1579 if ( wfReadOnly() ) {
1580 $this->logger
->debug( __METHOD__
. ': denied by wfReadOnly(): {reason}', [
1581 'username' => $username,
1582 'reason' => wfReadOnlyReason(),
1585 $user->loadFromId();
1586 return Status
::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
1589 // Check the session, if we tried to create this user already there's
1590 // no point in retrying.
1591 $session = $this->request
->getSession();
1592 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1593 $this->logger
->debug( __METHOD__
. ': blacklisted in session {sessionid}', [
1594 'username' => $username,
1595 'sessionid' => $session->getId(),
1598 $user->loadFromId();
1599 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1600 if ( $reason instanceof StatusValue
) {
1601 return Status
::wrap( $reason );
1603 return Status
::newFatal( $reason );
1607 // Is the username creatable?
1608 if ( !User
::isCreatableName( $username ) ) {
1609 $this->logger
->debug( __METHOD__
. ': name "{username}" is not creatable', [
1610 'username' => $username,
1612 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname' );
1614 $user->loadFromId();
1615 return Status
::newFatal( 'noname' );
1618 // Is the IP user able to create accounts?
1620 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1621 $this->logger
->debug( __METHOD__
. ': IP lacks the ability to create or autocreate accounts', [
1622 'username' => $username,
1623 'ip' => $anon->getName(),
1625 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm' );
1626 $session->persist();
1628 $user->loadFromId();
1629 return Status
::newFatal( 'authmanager-autocreate-noperm' );
1632 // Avoid account creation races on double submissions
1633 $cache = \ObjectCache
::getLocalClusterInstance();
1634 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1636 $this->logger
->debug( __METHOD__
. ': Could not acquire account creation lock', [
1637 'user' => $username,
1640 $user->loadFromId();
1641 return Status
::newFatal( 'usernameinprogress' );
1644 // Denied by providers?
1646 'flags' => User
::READ_LATEST
,
1649 $providers = $this->getPreAuthenticationProviders() +
1650 $this->getPrimaryAuthenticationProviders() +
1651 $this->getSecondaryAuthenticationProviders();
1652 foreach ( $providers as $provider ) {
1653 $status = $provider->testUserForCreation( $user, $source, $options );
1654 if ( !$status->isGood() ) {
1655 $ret = Status
::wrap( $status );
1656 $this->logger
->debug( __METHOD__
. ': Provider denied creation of {username}: {reason}', [
1657 'username' => $username,
1658 'reason' => $ret->getWikiText( null, null, 'en' ),
1660 $session->set( 'AuthManager::AutoCreateBlacklist', $status );
1662 $user->loadFromId();
1667 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1668 if ( $cache->get( $backoffKey ) ) {
1669 $this->logger
->debug( __METHOD__
. ': {username} denied by prior creation attempt failures', [
1670 'username' => $username,
1673 $user->loadFromId();
1674 return Status
::newFatal( 'authmanager-autocreate-exception' );
1677 // Checks passed, create the user...
1678 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
1679 $this->logger
->info( __METHOD__
. ': creating new user ({username}) - from: {from}', [
1680 'username' => $username,
1684 // Ignore warnings about master connections/writes...hard to avoid here
1685 $trxProfiler = \Profiler
::instance()->getTransactionProfiler();
1686 $old = $trxProfiler->setSilenced( true );
1688 $status = $user->addToDatabase();
1689 if ( !$status->isOK() ) {
1690 // Double-check for a race condition (T70012). We make use of the fact that when
1691 // addToDatabase fails due to the user already existing, the user object gets loaded.
1692 if ( $user->getId() ) {
1693 $this->logger
->info( __METHOD__
. ': {username} already exists locally (race)', [
1694 'username' => $username,
1697 $this->setSessionDataForUser( $user );
1699 $status = Status
::newGood();
1700 $status->warning( 'userexists' );
1702 $this->logger
->error( __METHOD__
. ': {username} failed with message {msg}', [
1703 'username' => $username,
1704 'msg' => $status->getWikiText( null, null, 'en' )
1707 $user->loadFromId();
1711 } catch ( \Exception
$ex ) {
1712 $trxProfiler->setSilenced( $old );
1713 $this->logger
->error( __METHOD__
. ': {username} failed with exception {exception}', [
1714 'username' => $username,
1717 // Do not keep throwing errors for a while
1718 $cache->set( $backoffKey, 1, 600 );
1719 // Bubble up error; which should normally trigger DB rollbacks
1723 $this->setDefaultUserOptions( $user, false );
1725 // Inform the providers
1726 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1728 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1729 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
1730 $user->saveSettings();
1732 // Update user count
1733 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1734 // Watch user's userpage and talk page
1735 \DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
1736 $user->addWatch( $user->getUserPage(), User
::IGNORE_USER_RIGHTS
);
1740 if ( $this->config
->get( 'NewUserLog' ) ) {
1741 $logEntry = new \
ManualLogEntry( 'newusers', 'autocreate' );
1742 $logEntry->setPerformer( $user );
1743 $logEntry->setTarget( $user->getUserPage() );
1744 $logEntry->setComment( '' );
1745 $logEntry->setParameters( [
1746 '4::userid' => $user->getId(),
1748 $logEntry->insert();
1751 $trxProfiler->setSilenced( $old );
1754 $this->setSessionDataForUser( $user );
1757 return Status
::newGood();
1763 * @name Account linking
1768 * Determine whether accounts can be linked
1771 public function canLinkAccounts() {
1772 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1773 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
) {
1781 * Start an account linking flow
1783 * @param User $user User being linked
1784 * @param AuthenticationRequest[] $reqs
1785 * @param string $returnToUrl Url that REDIRECT responses should eventually
1787 * @return AuthenticationResponse
1789 public function beginAccountLink( User
$user, array $reqs, $returnToUrl ) {
1790 $session = $this->request
->getSession();
1791 $session->remove( 'AuthManager::accountLinkState' );
1793 if ( !$this->canLinkAccounts() ) {
1794 // Caller should have called canLinkAccounts()
1795 throw new \
LogicException( 'Account linking is not possible' );
1798 if ( $user->getId() === 0 ) {
1799 if ( !User
::isUsableName( $user->getName() ) ) {
1800 $msg = wfMessage( 'noname' );
1802 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1804 return AuthenticationResponse
::newFail( $msg );
1806 foreach ( $reqs as $req ) {
1807 $req->username
= $user->getName();
1808 $req->returnToUrl
= $returnToUrl;
1811 $this->removeAuthenticationSessionData( null );
1813 $providers = $this->getPreAuthenticationProviders();
1814 foreach ( $providers as $id => $provider ) {
1815 $status = $provider->testForAccountLink( $user );
1816 if ( !$status->isGood() ) {
1817 $this->logger
->debug( __METHOD__
. ": Account linking pre-check failed by $id", [
1818 'user' => $user->getName(),
1820 $ret = AuthenticationResponse
::newFail(
1821 Status
::wrap( $status )->getMessage()
1823 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1829 'username' => $user->getName(),
1830 'userid' => $user->getId(),
1831 'returnToUrl' => $returnToUrl,
1833 'continueRequests' => [],
1836 $providers = $this->getPrimaryAuthenticationProviders();
1837 foreach ( $providers as $id => $provider ) {
1838 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider
::TYPE_LINK
) {
1842 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1843 switch ( $res->status
) {
1844 case AuthenticationResponse
::PASS
;
1845 $this->logger
->info( "Account linked to {user} by $id", [
1846 'user' => $user->getName(),
1848 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1851 case AuthenticationResponse
::FAIL
;
1852 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1853 'user' => $user->getName(),
1855 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1858 case AuthenticationResponse
::ABSTAIN
;
1862 case AuthenticationResponse
::REDIRECT
;
1863 case AuthenticationResponse
::UI
;
1864 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1865 'user' => $user->getName(),
1867 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1868 $state['primary'] = $id;
1869 $state['continueRequests'] = $res->neededRequests
;
1870 $session->setSecret( 'AuthManager::accountLinkState', $state );
1871 $session->persist();
1874 // @codeCoverageIgnoreStart
1876 throw new \
DomainException(
1877 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1879 // @codeCoverageIgnoreEnd
1883 $this->logger
->debug( __METHOD__
. ': Account linking failed because no provider accepted', [
1884 'user' => $user->getName(),
1886 $ret = AuthenticationResponse
::newFail(
1887 wfMessage( 'authmanager-link-no-primary' )
1889 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1894 * Continue an account linking flow
1895 * @param AuthenticationRequest[] $reqs
1896 * @return AuthenticationResponse
1898 public function continueAccountLink( array $reqs ) {
1899 $session = $this->request
->getSession();
1901 if ( !$this->canLinkAccounts() ) {
1902 // Caller should have called canLinkAccounts()
1903 $session->remove( 'AuthManager::accountLinkState' );
1904 throw new \
LogicException( 'Account linking is not possible' );
1907 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1908 if ( !is_array( $state ) ) {
1909 return AuthenticationResponse
::newFail(
1910 wfMessage( 'authmanager-link-not-in-progress' )
1913 $state['continueRequests'] = [];
1915 // Step 0: Prepare and validate the input
1917 $user = User
::newFromName( $state['username'], 'usable' );
1918 if ( !is_object( $user ) ) {
1919 $session->remove( 'AuthManager::accountLinkState' );
1920 return AuthenticationResponse
::newFail( wfMessage( 'noname' ) );
1922 if ( $user->getId() != $state['userid'] ) {
1923 throw new \
UnexpectedValueException(
1924 "User \"{$state['username']}\" is valid, but " .
1925 "ID {$user->getId()} != {$state['userid']}!"
1929 foreach ( $reqs as $req ) {
1930 $req->username
= $state['username'];
1931 $req->returnToUrl
= $state['returnToUrl'];
1934 // Step 1: Call the primary again until it succeeds
1936 $provider = $this->getAuthenticationProvider( $state['primary'] );
1937 if ( !$provider instanceof PrimaryAuthenticationProvider
) {
1938 // Configuration changed? Force them to start over.
1939 // @codeCoverageIgnoreStart
1940 $ret = AuthenticationResponse
::newFail(
1941 wfMessage( 'authmanager-link-not-in-progress' )
1943 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1944 $session->remove( 'AuthManager::accountLinkState' );
1946 // @codeCoverageIgnoreEnd
1948 $id = $provider->getUniqueId();
1949 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1950 switch ( $res->status
) {
1951 case AuthenticationResponse
::PASS
;
1952 $this->logger
->info( "Account linked to {user} by $id", [
1953 'user' => $user->getName(),
1955 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1956 $session->remove( 'AuthManager::accountLinkState' );
1958 case AuthenticationResponse
::FAIL
;
1959 $this->logger
->debug( __METHOD__
. ": Account linking failed by $id", [
1960 'user' => $user->getName(),
1962 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1963 $session->remove( 'AuthManager::accountLinkState' );
1965 case AuthenticationResponse
::REDIRECT
;
1966 case AuthenticationResponse
::UI
;
1967 $this->logger
->debug( __METHOD__
. ": Account linking $res->status by $id", [
1968 'user' => $user->getName(),
1970 $this->fillRequests( $res->neededRequests
, self
::ACTION_LINK
, $user->getName() );
1971 $state['continueRequests'] = $res->neededRequests
;
1972 $session->setSecret( 'AuthManager::accountLinkState', $state );
1975 throw new \
DomainException(
1976 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1979 } catch ( \Exception
$ex ) {
1980 $session->remove( 'AuthManager::accountLinkState' );
1988 * @name Information methods
1993 * Return the applicable list of AuthenticationRequests
1995 * Possible values for $action:
1996 * - ACTION_LOGIN: Valid for passing to beginAuthentication
1997 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
1998 * - ACTION_CREATE: Valid for passing to beginAccountCreation
1999 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
2000 * - ACTION_LINK: Valid for passing to beginAccountLink
2001 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
2002 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
2003 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2004 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2006 * @param string $action One of the AuthManager::ACTION_* constants
2007 * @param User|null $user User being acted on, instead of the current user.
2008 * @return AuthenticationRequest[]
2010 public function getAuthenticationRequests( $action, User
$user = null ) {
2012 $providerAction = $action;
2014 // Figure out which providers to query
2015 switch ( $action ) {
2016 case self
::ACTION_LOGIN
:
2017 case self
::ACTION_CREATE
:
2018 $providers = $this->getPreAuthenticationProviders() +
2019 $this->getPrimaryAuthenticationProviders() +
2020 $this->getSecondaryAuthenticationProviders();
2023 case self
::ACTION_LOGIN_CONTINUE
:
2024 $state = $this->request
->getSession()->getSecret( 'AuthManager::authnState' );
2025 return is_array( $state ) ?
$state['continueRequests'] : [];
2027 case self
::ACTION_CREATE_CONTINUE
:
2028 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountCreationState' );
2029 return is_array( $state ) ?
$state['continueRequests'] : [];
2031 case self
::ACTION_LINK
:
2032 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2033 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
2037 case self
::ACTION_UNLINK
:
2038 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2039 return $p->accountCreationType() === PrimaryAuthenticationProvider
::TYPE_LINK
;
2042 // To providers, unlink and remove are identical.
2043 $providerAction = self
::ACTION_REMOVE
;
2046 case self
::ACTION_LINK_CONTINUE
:
2047 $state = $this->request
->getSession()->getSecret( 'AuthManager::accountLinkState' );
2048 return is_array( $state ) ?
$state['continueRequests'] : [];
2050 case self
::ACTION_CHANGE
:
2051 case self
::ACTION_REMOVE
:
2052 $providers = $this->getPrimaryAuthenticationProviders() +
2053 $this->getSecondaryAuthenticationProviders();
2056 // @codeCoverageIgnoreStart
2058 throw new \
DomainException( __METHOD__
. ": Invalid action \"$action\"" );
2060 // @codeCoverageIgnoreEnd
2062 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2066 * Internal request lookup for self::getAuthenticationRequests
2068 * @param string $providerAction Action to pass to providers
2069 * @param array $options Options to pass to providers
2070 * @param AuthenticationProvider[] $providers
2071 * @param User|null $user
2072 * @return AuthenticationRequest[]
2074 private function getAuthenticationRequestsInternal(
2075 $providerAction, array $options, array $providers, User
$user = null
2077 $user = $user ?
: \RequestContext
::getMain()->getUser();
2078 $options['username'] = $user->isAnon() ?
null : $user->getName();
2080 // Query them and merge results
2082 foreach ( $providers as $provider ) {
2083 $isPrimary = $provider instanceof PrimaryAuthenticationProvider
;
2084 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2085 $id = $req->getUniqueId();
2087 // If a required request if from a Primary, mark it as "primary-required" instead
2089 if ( $req->required
) {
2090 $req->required
= AuthenticationRequest
::PRIMARY_REQUIRED
;
2095 !isset( $reqs[$id] )
2096 ||
$req->required
=== AuthenticationRequest
::REQUIRED
2097 ||
$reqs[$id] === AuthenticationRequest
::OPTIONAL
2104 // AuthManager has its own req for some actions
2105 switch ( $providerAction ) {
2106 case self
::ACTION_LOGIN
:
2107 $reqs[] = new RememberMeAuthenticationRequest
;
2110 case self
::ACTION_CREATE
:
2111 $reqs[] = new UsernameAuthenticationRequest
;
2112 $reqs[] = new UserDataAuthenticationRequest
;
2113 if ( $options['username'] !== null ) {
2114 $reqs[] = new CreationReasonAuthenticationRequest
;
2115 $options['username'] = null; // Don't fill in the username below
2120 // Fill in reqs data
2121 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2123 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2124 if ( $providerAction === self
::ACTION_CHANGE ||
$providerAction === self
::ACTION_REMOVE
) {
2125 $reqs = array_filter( $reqs, function ( $req ) {
2126 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2130 return array_values( $reqs );
2134 * Set values in an array of requests
2135 * @param AuthenticationRequest[] &$reqs
2136 * @param string $action
2137 * @param string|null $username
2138 * @param bool $forceAction
2140 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2141 foreach ( $reqs as $req ) {
2142 if ( !$req->action ||
$forceAction ) {
2143 $req->action
= $action;
2145 if ( $req->username
=== null ) {
2146 $req->username
= $username;
2152 * Determine whether a username exists
2153 * @param string $username
2154 * @param int $flags Bitfield of User:READ_* constants
2157 public function userExists( $username, $flags = User
::READ_NORMAL
) {
2158 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2159 if ( $provider->testUserExists( $username, $flags ) ) {
2168 * Determine whether a user property should be allowed to be changed.
2170 * Supported properties are:
2175 * @param string $property
2178 public function allowsPropertyChange( $property ) {
2179 $providers = $this->getPrimaryAuthenticationProviders() +
2180 $this->getSecondaryAuthenticationProviders();
2181 foreach ( $providers as $provider ) {
2182 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2190 * Get a provider by ID
2191 * @note This is public so extensions can check whether their own provider
2192 * is installed and so they can read its configuration if necessary.
2193 * Other uses are not recommended.
2195 * @return AuthenticationProvider|null
2197 public function getAuthenticationProvider( $id ) {
2199 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2200 return $this->allAuthenticationProviders
[$id];
2203 // Slow version: instantiate each kind and check
2204 $providers = $this->getPrimaryAuthenticationProviders();
2205 if ( isset( $providers[$id] ) ) {
2206 return $providers[$id];
2208 $providers = $this->getSecondaryAuthenticationProviders();
2209 if ( isset( $providers[$id] ) ) {
2210 return $providers[$id];
2212 $providers = $this->getPreAuthenticationProviders();
2213 if ( isset( $providers[$id] ) ) {
2214 return $providers[$id];
2223 * @name Internal methods
2228 * Store authentication in the current session
2229 * @protected For use by AuthenticationProviders
2230 * @param string $key
2231 * @param mixed $data Must be serializable
2233 public function setAuthenticationSessionData( $key, $data ) {
2234 $session = $this->request
->getSession();
2235 $arr = $session->getSecret( 'authData' );
2236 if ( !is_array( $arr ) ) {
2240 $session->setSecret( 'authData', $arr );
2244 * Fetch authentication data from the current session
2245 * @protected For use by AuthenticationProviders
2246 * @param string $key
2247 * @param mixed $default
2250 public function getAuthenticationSessionData( $key, $default = null ) {
2251 $arr = $this->request
->getSession()->getSecret( 'authData' );
2252 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2260 * Remove authentication data
2261 * @protected For use by AuthenticationProviders
2262 * @param string|null $key If null, all data is removed
2264 public function removeAuthenticationSessionData( $key ) {
2265 $session = $this->request
->getSession();
2266 if ( $key === null ) {
2267 $session->remove( 'authData' );
2269 $arr = $session->getSecret( 'authData' );
2270 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2271 unset( $arr[$key] );
2272 $session->setSecret( 'authData', $arr );
2278 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2279 * @param string $class
2280 * @param array[] $specs
2281 * @return AuthenticationProvider[]
2283 protected function providerArrayFromSpecs( $class, array $specs ) {
2285 foreach ( $specs as &$spec ) {
2286 $spec = [ 'sort2' => $i++
] +
$spec +
[ 'sort' => 0 ];
2289 usort( $specs, function ( $a, $b ) {
2290 return ( (int)$a['sort'] ) - ( (int)$b['sort'] )
2291 ?
: $a['sort2'] - $b['sort2'];
2295 foreach ( $specs as $spec ) {
2296 $provider = ObjectFactory
::getObjectFromSpec( $spec );
2297 if ( !$provider instanceof $class ) {
2298 throw new \
RuntimeException(
2299 "Expected instance of $class, got " . get_class( $provider )
2302 $provider->setLogger( $this->logger
);
2303 $provider->setManager( $this );
2304 $provider->setConfig( $this->config
);
2305 $id = $provider->getUniqueId();
2306 if ( isset( $this->allAuthenticationProviders
[$id] ) ) {
2307 throw new \
RuntimeException(
2308 "Duplicate specifications for id $id (classes " .
2309 get_class( $provider ) . ' and ' .
2310 get_class( $this->allAuthenticationProviders
[$id] ) . ')'
2313 $this->allAuthenticationProviders
[$id] = $provider;
2314 $ret[$id] = $provider;
2320 * Get the configuration
2323 private function getConfiguration() {
2324 return $this->config
->get( 'AuthManagerConfig' ) ?
: $this->config
->get( 'AuthManagerAutoConfig' );
2328 * Get the list of PreAuthenticationProviders
2329 * @return PreAuthenticationProvider[]
2331 protected function getPreAuthenticationProviders() {
2332 if ( $this->preAuthenticationProviders
=== null ) {
2333 $conf = $this->getConfiguration();
2334 $this->preAuthenticationProviders
= $this->providerArrayFromSpecs(
2335 PreAuthenticationProvider
::class, $conf['preauth']
2338 return $this->preAuthenticationProviders
;
2342 * Get the list of PrimaryAuthenticationProviders
2343 * @return PrimaryAuthenticationProvider[]
2345 protected function getPrimaryAuthenticationProviders() {
2346 if ( $this->primaryAuthenticationProviders
=== null ) {
2347 $conf = $this->getConfiguration();
2348 $this->primaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2349 PrimaryAuthenticationProvider
::class, $conf['primaryauth']
2352 return $this->primaryAuthenticationProviders
;
2356 * Get the list of SecondaryAuthenticationProviders
2357 * @return SecondaryAuthenticationProvider[]
2359 protected function getSecondaryAuthenticationProviders() {
2360 if ( $this->secondaryAuthenticationProviders
=== null ) {
2361 $conf = $this->getConfiguration();
2362 $this->secondaryAuthenticationProviders
= $this->providerArrayFromSpecs(
2363 SecondaryAuthenticationProvider
::class, $conf['secondaryauth']
2366 return $this->secondaryAuthenticationProviders
;
2372 * @param bool|null $remember
2374 private function setSessionDataForUser( $user, $remember = null ) {
2375 $session = $this->request
->getSession();
2376 $delay = $session->delaySave();
2378 $session->resetId();
2379 $session->resetAllTokens();
2380 if ( $session->canSetUser() ) {
2381 $session->setUser( $user );
2383 if ( $remember !== null ) {
2384 $session->setRememberUser( $remember );
2386 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2387 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2388 $session->persist();
2390 \Wikimedia\ScopedCallback
::consume( $delay );
2392 \Hooks
::run( 'UserLoggedIn', [ $user ] );
2397 * @param bool $useContextLang Use 'uselang' to set the user's language
2399 private function setDefaultUserOptions( User
$user, $useContextLang ) {
2404 $lang = $useContextLang ? \RequestContext
::getMain()->getLanguage() : $wgContLang;
2405 $user->setOption( 'language', $lang->getPreferredVariant() );
2407 if ( $wgContLang->hasVariants() ) {
2408 $user->setOption( 'variant', $wgContLang->getPreferredVariant() );
2413 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2414 * @param string $method
2415 * @param array $args
2417 private function callMethodOnProviders( $which, $method, array $args ) {
2420 $providers +
= $this->getPreAuthenticationProviders();
2423 $providers +
= $this->getPrimaryAuthenticationProviders();
2426 $providers +
= $this->getSecondaryAuthenticationProviders();
2428 foreach ( $providers as $provider ) {
2429 call_user_func_array( [ $provider, $method ], $args );
2434 * Reset the internal caching for unit testing
2435 * @protected Unit tests only
2437 public static function resetCache() {
2438 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2439 // @codeCoverageIgnoreStart
2440 throw new \
MWException( __METHOD__
. ' may only be called from unit tests!' );
2441 // @codeCoverageIgnoreEnd
2444 self
::$instance = null;
2452 * For really cool vim folding this needs to be at the end:
2453 * vim: foldmarker=@{,@} foldmethod=marker