Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / auth / AuthManager.php
blobe9a6edc224163f0a0d972353b88479104320ef9a
1 <?php
2 /**
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
20 * @file
21 * @ingroup Auth
24 namespace MediaWiki\Auth;
26 use Config;
27 use MediaWiki\MediaWikiServices;
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Status;
31 use StatusValue;
32 use User;
33 use WebRequest;
35 /**
36 * This serves as the entry point to the authentication system.
38 * In the future, it may also serve as the entry point to the authorization
39 * system.
41 * If you are looking at this because you are working on an extension that creates its own
42 * login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
43 * have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
44 * or the createaccount API. Trying to call this class directly will very likely end up in
45 * security vulnerabilities or broken UX in edge cases.
47 * If you are working on an extension that needs to integrate with the authentication system
48 * (e.g. by providing a new login method, or doing extra permission checks), you'll probably
49 * need to write an AuthenticationProvider.
51 * If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
52 * you are looking for. If you want to change user data, use User::changeAuthenticationData().
53 * Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
54 * create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
55 * responsibility to ensure that the user can authenticate somehow (see especially
56 * PrimaryAuthenticationProvider::autoCreatedAccount()).
57 * If you are writing code that is not associated with such a provider and needs to create accounts
58 * programmatically for real users, you should rethink your architecture. There is no good way to
59 * do that as such code has no knowledge of what authentication methods are enabled on the wiki and
60 * cannot provide any means for users to access the accounts it would create.
62 * The two main control flows when using this class are as follows:
63 * * Login, user creation or account linking code will call getAuthenticationRequests(), populate
64 * the requests with data (by using them to build a HTMLForm and have the user fill it, or by
65 * exposing a form specification via the API, so that the client can build it), and pass them to
66 * the appropriate begin* method. That will return either a success/failure response, or more
67 * requests to fill (either by building a form or by redirecting the user to some external
68 * provider which will send the data back), in which case they need to be submitted to the
69 * appropriate continue* method and that step has to be repeated until the response is a success
70 * or failure response. AuthManager will use the session to maintain internal state during the
71 * process.
72 * * Code doing an authentication data change will call getAuthenticationRequests(), select
73 * a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
74 * changeAuthenticationData(). If the data change is user-initiated, the whole process needs
75 * to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
76 * a non-OK status.
78 * @ingroup Auth
79 * @since 1.27
80 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
82 class AuthManager implements LoggerAwareInterface {
83 /** Log in with an existing (not necessarily local) user */
84 const ACTION_LOGIN = 'login';
85 /** Continue a login process that was interrupted by the need for user input or communication
86 * with an external provider */
87 const ACTION_LOGIN_CONTINUE = 'login-continue';
88 /** Create a new user */
89 const ACTION_CREATE = 'create';
90 /** Continue a user creation process that was interrupted by the need for user input or
91 * communication with an external provider */
92 const ACTION_CREATE_CONTINUE = 'create-continue';
93 /** Link an existing user to a third-party account */
94 const ACTION_LINK = 'link';
95 /** Continue a user linking process that was interrupted by the need for user input or
96 * communication with an external provider */
97 const ACTION_LINK_CONTINUE = 'link-continue';
98 /** Change a user's credentials */
99 const ACTION_CHANGE = 'change';
100 /** Remove a user's credentials */
101 const ACTION_REMOVE = 'remove';
102 /** Like ACTION_REMOVE but for linking providers only */
103 const ACTION_UNLINK = 'unlink';
105 /** Security-sensitive operations are ok. */
106 const SEC_OK = 'ok';
107 /** Security-sensitive operations should re-authenticate. */
108 const SEC_REAUTH = 'reauth';
109 /** Security-sensitive should not be performed. */
110 const SEC_FAIL = 'fail';
112 /** Auto-creation is due to SessionManager */
113 const AUTOCREATE_SOURCE_SESSION = \MediaWiki\Session\SessionManager::class;
115 /** @var AuthManager|null */
116 private static $instance = null;
118 /** @var WebRequest */
119 private $request;
121 /** @var Config */
122 private $config;
124 /** @var LoggerInterface */
125 private $logger;
127 /** @var AuthenticationProvider[] */
128 private $allAuthenticationProviders = [];
130 /** @var PreAuthenticationProvider[] */
131 private $preAuthenticationProviders = null;
133 /** @var PrimaryAuthenticationProvider[] */
134 private $primaryAuthenticationProviders = null;
136 /** @var SecondaryAuthenticationProvider[] */
137 private $secondaryAuthenticationProviders = null;
139 /** @var CreatedAccountAuthenticationRequest[] */
140 private $createdAccountAuthenticationRequests = [];
143 * Get the global AuthManager
144 * @return AuthManager
146 public static function singleton() {
147 if ( self::$instance === null ) {
148 self::$instance = new self(
149 \RequestContext::getMain()->getRequest(),
150 MediaWikiServices::getInstance()->getMainConfig()
153 return self::$instance;
157 * @param WebRequest $request
158 * @param Config $config
160 public function __construct( WebRequest $request, Config $config ) {
161 $this->request = $request;
162 $this->config = $config;
163 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' ) );
167 * @param LoggerInterface $logger
169 public function setLogger( LoggerInterface $logger ) {
170 $this->logger = $logger;
174 * @return WebRequest
176 public function getRequest() {
177 return $this->request;
181 * Force certain PrimaryAuthenticationProviders
182 * @deprecated For backwards compatibility only
183 * @param PrimaryAuthenticationProvider[] $providers
184 * @param string $why
186 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
187 $this->logger->warning( "Overriding AuthManager primary authn because $why" );
189 if ( $this->primaryAuthenticationProviders !== null ) {
190 $this->logger->warning(
191 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
194 $this->allAuthenticationProviders = array_diff_key(
195 $this->allAuthenticationProviders,
196 $this->primaryAuthenticationProviders
198 $session = $this->request->getSession();
199 $session->remove( 'AuthManager::authnState' );
200 $session->remove( 'AuthManager::accountCreationState' );
201 $session->remove( 'AuthManager::accountLinkState' );
202 $this->createdAccountAuthenticationRequests = [];
205 $this->primaryAuthenticationProviders = [];
206 foreach ( $providers as $provider ) {
207 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
208 throw new \RuntimeException(
209 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
210 get_class( $provider )
213 $provider->setLogger( $this->logger );
214 $provider->setManager( $this );
215 $provider->setConfig( $this->config );
216 $id = $provider->getUniqueId();
217 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
218 throw new \RuntimeException(
219 "Duplicate specifications for id $id (classes " .
220 get_class( $provider ) . ' and ' .
221 get_class( $this->allAuthenticationProviders[$id] ) . ')'
224 $this->allAuthenticationProviders[$id] = $provider;
225 $this->primaryAuthenticationProviders[$id] = $provider;
230 * Call a legacy AuthPlugin method, if necessary
231 * @codeCoverageIgnore
232 * @deprecated For backwards compatibility only, should be avoided in new code
233 * @param string $method AuthPlugin method to call
234 * @param array $params Parameters to pass
235 * @param mixed $return Return value if AuthPlugin wasn't called
236 * @return mixed Return value from the AuthPlugin method, or $return
238 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
239 global $wgAuth;
241 if ( $wgAuth && !$wgAuth instanceof AuthManagerAuthPlugin ) {
242 return call_user_func_array( [ $wgAuth, $method ], $params );
243 } else {
244 return $return;
249 * @name Authentication
250 * @{
254 * Indicate whether user authentication is possible
256 * It may not be if the session is provided by something like OAuth
257 * for which each individual request includes authentication data.
259 * @return bool
261 public function canAuthenticateNow() {
262 return $this->request->getSession()->canSetUser();
266 * Start an authentication flow
268 * In addition to the AuthenticationRequests returned by
269 * $this->getAuthenticationRequests(), a client might include a
270 * CreateFromLoginAuthenticationRequest from a previous login attempt to
271 * preserve state.
273 * Instead of the AuthenticationRequests returned by
274 * $this->getAuthenticationRequests(), a client might pass a
275 * CreatedAccountAuthenticationRequest from an account creation that just
276 * succeeded to log in to the just-created account.
278 * @param AuthenticationRequest[] $reqs
279 * @param string $returnToUrl Url that REDIRECT responses should eventually
280 * return to.
281 * @return AuthenticationResponse See self::continueAuthentication()
283 public function beginAuthentication( array $reqs, $returnToUrl ) {
284 $session = $this->request->getSession();
285 if ( !$session->canSetUser() ) {
286 // Caller should have called canAuthenticateNow()
287 $session->remove( 'AuthManager::authnState' );
288 throw new \LogicException( 'Authentication is not possible now' );
291 $guessUserName = null;
292 foreach ( $reqs as $req ) {
293 $req->returnToUrl = $returnToUrl;
294 // @codeCoverageIgnoreStart
295 if ( $req->username !== null && $req->username !== '' ) {
296 if ( $guessUserName === null ) {
297 $guessUserName = $req->username;
298 } elseif ( $guessUserName !== $req->username ) {
299 $guessUserName = null;
300 break;
303 // @codeCoverageIgnoreEnd
306 // Check for special-case login of a just-created account
307 $req = AuthenticationRequest::getRequestByClass(
308 $reqs, CreatedAccountAuthenticationRequest::class
310 if ( $req ) {
311 if ( !in_array( $req, $this->createdAccountAuthenticationRequests, true ) ) {
312 throw new \LogicException(
313 'CreatedAccountAuthenticationRequests are only valid on ' .
314 'the same AuthManager that created the account'
318 $user = User::newFromName( $req->username );
319 // @codeCoverageIgnoreStart
320 if ( !$user ) {
321 throw new \UnexpectedValueException(
322 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
324 } elseif ( $user->getId() != $req->id ) {
325 throw new \UnexpectedValueException(
326 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
329 // @codeCoverageIgnoreEnd
331 $this->logger->info( 'Logging in {user} after account creation', [
332 'user' => $user->getName(),
333 ] );
334 $ret = AuthenticationResponse::newPass( $user->getName() );
335 $this->setSessionDataForUser( $user );
336 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
337 $session->remove( 'AuthManager::authnState' );
338 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
339 return $ret;
342 $this->removeAuthenticationSessionData( null );
344 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
345 $status = $provider->testForAuthentication( $reqs );
346 if ( !$status->isGood() ) {
347 $this->logger->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
348 $ret = AuthenticationResponse::newFail(
349 Status::wrap( $status )->getMessage()
351 $this->callMethodOnProviders( 7, 'postAuthentication',
352 [ User::newFromName( $guessUserName ) ?: null, $ret ]
354 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName ] );
355 return $ret;
359 $state = [
360 'reqs' => $reqs,
361 'returnToUrl' => $returnToUrl,
362 'guessUserName' => $guessUserName,
363 'primary' => null,
364 'primaryResponse' => null,
365 'secondary' => [],
366 'maybeLink' => [],
367 'continueRequests' => [],
370 // Preserve state from a previous failed login
371 $req = AuthenticationRequest::getRequestByClass(
372 $reqs, CreateFromLoginAuthenticationRequest::class
374 if ( $req ) {
375 $state['maybeLink'] = $req->maybeLink;
378 $session = $this->request->getSession();
379 $session->setSecret( 'AuthManager::authnState', $state );
380 $session->persist();
382 return $this->continueAuthentication( $reqs );
386 * Continue an authentication flow
388 * Return values are interpreted as follows:
389 * - status FAIL: Authentication failed. If $response->createRequest is
390 * set, that may be passed to self::beginAuthentication() or to
391 * self::beginAccountCreation() to preserve state.
392 * - status REDIRECT: The client should be redirected to the contained URL,
393 * new AuthenticationRequests should be made (if any), then
394 * AuthManager::continueAuthentication() should be called.
395 * - status UI: The client should be presented with a user interface for
396 * the fields in the specified AuthenticationRequests, then new
397 * AuthenticationRequests should be made, then
398 * AuthManager::continueAuthentication() should be called.
399 * - status RESTART: The user logged in successfully with a third-party
400 * service, but the third-party credentials aren't attached to any local
401 * account. This could be treated as a UI or a FAIL.
402 * - status PASS: Authentication was successful.
404 * @param AuthenticationRequest[] $reqs
405 * @return AuthenticationResponse
407 public function continueAuthentication( array $reqs ) {
408 $session = $this->request->getSession();
409 try {
410 if ( !$session->canSetUser() ) {
411 // Caller should have called canAuthenticateNow()
412 // @codeCoverageIgnoreStart
413 throw new \LogicException( 'Authentication is not possible now' );
414 // @codeCoverageIgnoreEnd
417 $state = $session->getSecret( 'AuthManager::authnState' );
418 if ( !is_array( $state ) ) {
419 return AuthenticationResponse::newFail(
420 wfMessage( 'authmanager-authn-not-in-progress' )
423 $state['continueRequests'] = [];
425 $guessUserName = $state['guessUserName'];
427 foreach ( $reqs as $req ) {
428 $req->returnToUrl = $state['returnToUrl'];
431 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
433 if ( $state['primary'] === null ) {
434 // We haven't picked a PrimaryAuthenticationProvider yet
435 // @codeCoverageIgnoreStart
436 $guessUserName = null;
437 foreach ( $reqs as $req ) {
438 if ( $req->username !== null && $req->username !== '' ) {
439 if ( $guessUserName === null ) {
440 $guessUserName = $req->username;
441 } elseif ( $guessUserName !== $req->username ) {
442 $guessUserName = null;
443 break;
447 $state['guessUserName'] = $guessUserName;
448 // @codeCoverageIgnoreEnd
449 $state['reqs'] = $reqs;
451 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
452 $res = $provider->beginPrimaryAuthentication( $reqs );
453 switch ( $res->status ) {
454 case AuthenticationResponse::PASS;
455 $state['primary'] = $id;
456 $state['primaryResponse'] = $res;
457 $this->logger->debug( "Primary login with $id succeeded" );
458 break 2;
459 case AuthenticationResponse::FAIL;
460 $this->logger->debug( "Login failed in primary authentication by $id" );
461 if ( $res->createRequest || $state['maybeLink'] ) {
462 $res->createRequest = new CreateFromLoginAuthenticationRequest(
463 $res->createRequest, $state['maybeLink']
466 $this->callMethodOnProviders( 7, 'postAuthentication',
467 [ User::newFromName( $guessUserName ) ?: null, $res ]
469 $session->remove( 'AuthManager::authnState' );
470 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
471 return $res;
472 case AuthenticationResponse::ABSTAIN;
473 // Continue loop
474 break;
475 case AuthenticationResponse::REDIRECT;
476 case AuthenticationResponse::UI;
477 $this->logger->debug( "Primary login with $id returned $res->status" );
478 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
479 $state['primary'] = $id;
480 $state['continueRequests'] = $res->neededRequests;
481 $session->setSecret( 'AuthManager::authnState', $state );
482 return $res;
484 // @codeCoverageIgnoreStart
485 default:
486 throw new \DomainException(
487 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
489 // @codeCoverageIgnoreEnd
492 if ( $state['primary'] === null ) {
493 $this->logger->debug( 'Login failed in primary authentication because no provider accepted' );
494 $ret = AuthenticationResponse::newFail(
495 wfMessage( 'authmanager-authn-no-primary' )
497 $this->callMethodOnProviders( 7, 'postAuthentication',
498 [ User::newFromName( $guessUserName ) ?: null, $ret ]
500 $session->remove( 'AuthManager::authnState' );
501 return $ret;
503 } elseif ( $state['primaryResponse'] === null ) {
504 $provider = $this->getAuthenticationProvider( $state['primary'] );
505 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
506 // Configuration changed? Force them to start over.
507 // @codeCoverageIgnoreStart
508 $ret = AuthenticationResponse::newFail(
509 wfMessage( 'authmanager-authn-not-in-progress' )
511 $this->callMethodOnProviders( 7, 'postAuthentication',
512 [ User::newFromName( $guessUserName ) ?: null, $ret ]
514 $session->remove( 'AuthManager::authnState' );
515 return $ret;
516 // @codeCoverageIgnoreEnd
518 $id = $provider->getUniqueId();
519 $res = $provider->continuePrimaryAuthentication( $reqs );
520 switch ( $res->status ) {
521 case AuthenticationResponse::PASS;
522 $state['primaryResponse'] = $res;
523 $this->logger->debug( "Primary login with $id succeeded" );
524 break;
525 case AuthenticationResponse::FAIL;
526 $this->logger->debug( "Login failed in primary authentication by $id" );
527 if ( $res->createRequest || $state['maybeLink'] ) {
528 $res->createRequest = new CreateFromLoginAuthenticationRequest(
529 $res->createRequest, $state['maybeLink']
532 $this->callMethodOnProviders( 7, 'postAuthentication',
533 [ User::newFromName( $guessUserName ) ?: null, $res ]
535 $session->remove( 'AuthManager::authnState' );
536 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
537 return $res;
538 case AuthenticationResponse::REDIRECT;
539 case AuthenticationResponse::UI;
540 $this->logger->debug( "Primary login with $id returned $res->status" );
541 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
542 $state['continueRequests'] = $res->neededRequests;
543 $session->setSecret( 'AuthManager::authnState', $state );
544 return $res;
545 default:
546 throw new \DomainException(
547 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
552 $res = $state['primaryResponse'];
553 if ( $res->username === null ) {
554 $provider = $this->getAuthenticationProvider( $state['primary'] );
555 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
556 // Configuration changed? Force them to start over.
557 // @codeCoverageIgnoreStart
558 $ret = AuthenticationResponse::newFail(
559 wfMessage( 'authmanager-authn-not-in-progress' )
561 $this->callMethodOnProviders( 7, 'postAuthentication',
562 [ User::newFromName( $guessUserName ) ?: null, $ret ]
564 $session->remove( 'AuthManager::authnState' );
565 return $ret;
566 // @codeCoverageIgnoreEnd
569 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK &&
570 $res->linkRequest &&
571 // don't confuse the user with an incorrect message if linking is disabled
572 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider::class )
574 $state['maybeLink'][$res->linkRequest->getUniqueId()] = $res->linkRequest;
575 $msg = 'authmanager-authn-no-local-user-link';
576 } else {
577 $msg = 'authmanager-authn-no-local-user';
579 $this->logger->debug(
580 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
582 $ret = AuthenticationResponse::newRestart( wfMessage( $msg ) );
583 $ret->neededRequests = $this->getAuthenticationRequestsInternal(
584 self::ACTION_LOGIN,
586 $this->getPrimaryAuthenticationProviders() + $this->getSecondaryAuthenticationProviders()
588 if ( $res->createRequest || $state['maybeLink'] ) {
589 $ret->createRequest = new CreateFromLoginAuthenticationRequest(
590 $res->createRequest, $state['maybeLink']
592 $ret->neededRequests[] = $ret->createRequest;
594 $this->fillRequests( $ret->neededRequests, self::ACTION_LOGIN, null, true );
595 $session->setSecret( 'AuthManager::authnState', [
596 'reqs' => [], // Will be filled in later
597 'primary' => null,
598 'primaryResponse' => null,
599 'secondary' => [],
600 'continueRequests' => $ret->neededRequests,
601 ] + $state );
602 return $ret;
605 // Step 2: Primary authentication succeeded, create the User object
606 // (and add the user locally if necessary)
608 $user = User::newFromName( $res->username, 'usable' );
609 if ( !$user ) {
610 $provider = $this->getAuthenticationProvider( $state['primary'] );
611 throw new \DomainException(
612 get_class( $provider ) . " returned an invalid username: {$res->username}"
615 if ( $user->getId() === 0 ) {
616 // User doesn't exist locally. Create it.
617 $this->logger->info( 'Auto-creating {user} on login', [
618 'user' => $user->getName(),
619 ] );
620 $status = $this->autoCreateUser( $user, $state['primary'], false );
621 if ( !$status->isGood() ) {
622 $ret = AuthenticationResponse::newFail(
623 Status::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
625 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
626 $session->remove( 'AuthManager::authnState' );
627 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
628 return $ret;
632 // Step 3: Iterate over all the secondary authentication providers.
634 $beginReqs = $state['reqs'];
636 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
637 if ( !isset( $state['secondary'][$id] ) ) {
638 // This provider isn't started yet, so we pass it the set
639 // of reqs from beginAuthentication instead of whatever
640 // might have been used by a previous provider in line.
641 $func = 'beginSecondaryAuthentication';
642 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
643 } elseif ( !$state['secondary'][$id] ) {
644 $func = 'continueSecondaryAuthentication';
645 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
646 } else {
647 continue;
649 switch ( $res->status ) {
650 case AuthenticationResponse::PASS;
651 $this->logger->debug( "Secondary login with $id succeeded" );
652 // fall through
653 case AuthenticationResponse::ABSTAIN;
654 $state['secondary'][$id] = true;
655 break;
656 case AuthenticationResponse::FAIL;
657 $this->logger->debug( "Login failed in secondary authentication by $id" );
658 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
659 $session->remove( 'AuthManager::authnState' );
660 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName() ] );
661 return $res;
662 case AuthenticationResponse::REDIRECT;
663 case AuthenticationResponse::UI;
664 $this->logger->debug( "Secondary login with $id returned " . $res->status );
665 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $user->getName() );
666 $state['secondary'][$id] = false;
667 $state['continueRequests'] = $res->neededRequests;
668 $session->setSecret( 'AuthManager::authnState', $state );
669 return $res;
671 // @codeCoverageIgnoreStart
672 default:
673 throw new \DomainException(
674 get_class( $provider ) . "::{$func}() returned $res->status"
676 // @codeCoverageIgnoreEnd
680 // Step 4: Authentication complete! Set the user in the session and
681 // clean up.
683 $this->logger->info( 'Login for {user} succeeded', [
684 'user' => $user->getName(),
685 ] );
686 /** @var RememberMeAuthenticationRequest $req */
687 $req = AuthenticationRequest::getRequestByClass(
688 $beginReqs, RememberMeAuthenticationRequest::class
690 $this->setSessionDataForUser( $user, $req && $req->rememberMe );
691 $ret = AuthenticationResponse::newPass( $user->getName() );
692 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
693 $session->remove( 'AuthManager::authnState' );
694 $this->removeAuthenticationSessionData( null );
695 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
696 return $ret;
697 } catch ( \Exception $ex ) {
698 $session->remove( 'AuthManager::authnState' );
699 throw $ex;
704 * Whether security-sensitive operations should proceed.
706 * A "security-sensitive operation" is something like a password or email
707 * change, that would normally have a "reenter your password to confirm"
708 * box if we only supported password-based authentication.
710 * @param string $operation Operation being checked. This should be a
711 * message-key-like string such as 'change-password' or 'change-email'.
712 * @return string One of the SEC_* constants.
714 public function securitySensitiveOperationStatus( $operation ) {
715 $status = self::SEC_OK;
717 $this->logger->debug( __METHOD__ . ": Checking $operation" );
719 $session = $this->request->getSession();
720 $aId = $session->getUser()->getId();
721 if ( $aId === 0 ) {
722 // User isn't authenticated. DWIM?
723 $status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
724 $this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
725 return $status;
728 if ( $session->canSetUser() ) {
729 $id = $session->get( 'AuthManager:lastAuthId' );
730 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
731 if ( $id !== $aId || $last === null ) {
732 $timeSinceLogin = PHP_INT_MAX; // Forever ago
733 } else {
734 $timeSinceLogin = max( 0, time() - $last );
737 $thresholds = $this->config->get( 'ReauthenticateTime' );
738 if ( isset( $thresholds[$operation] ) ) {
739 $threshold = $thresholds[$operation];
740 } elseif ( isset( $thresholds['default'] ) ) {
741 $threshold = $thresholds['default'];
742 } else {
743 throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
746 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
747 $status = self::SEC_REAUTH;
749 } else {
750 $timeSinceLogin = -1;
752 $pass = $this->config->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
753 if ( isset( $pass[$operation] ) ) {
754 $status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
755 } elseif ( isset( $pass['default'] ) ) {
756 $status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
757 } else {
758 throw new \UnexpectedValueException(
759 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
764 \Hooks::run( 'SecuritySensitiveOperationStatus', [
765 &$status, $operation, $session, $timeSinceLogin
766 ] );
768 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
769 if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
770 $status = self::SEC_FAIL;
773 $this->logger->info( __METHOD__ . ": $operation is $status" );
775 return $status;
779 * Determine whether a username can authenticate
781 * This is mainly for internal purposes and only takes authentication data into account,
782 * not things like blocks that can change without the authentication system being aware.
784 * @param string $username MediaWiki username
785 * @return bool
787 public function userCanAuthenticate( $username ) {
788 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
789 if ( $provider->testUserCanAuthenticate( $username ) ) {
790 return true;
793 return false;
797 * Provide normalized versions of the username for security checks
799 * Since different providers can normalize the input in different ways,
800 * this returns an array of all the different ways the name might be
801 * normalized for authentication.
803 * The returned strings should not be revealed to the user, as that might
804 * leak private information (e.g. an email address might be normalized to a
805 * username).
807 * @param string $username
808 * @return string[]
810 public function normalizeUsername( $username ) {
811 $ret = [];
812 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
813 $normalized = $provider->providerNormalizeUsername( $username );
814 if ( $normalized !== null ) {
815 $ret[$normalized] = true;
818 return array_keys( $ret );
821 /**@}*/
824 * @name Authentication data changing
825 * @{
829 * Revoke any authentication credentials for a user
831 * After this, the user should no longer be able to log in.
833 * @param string $username
835 public function revokeAccessForUser( $username ) {
836 $this->logger->info( 'Revoking access for {user}', [
837 'user' => $username,
838 ] );
839 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
843 * Validate a change of authentication data (e.g. passwords)
844 * @param AuthenticationRequest $req
845 * @param bool $checkData If false, $req hasn't been loaded from the
846 * submission so checks on user-submitted fields should be skipped. $req->username is
847 * considered user-submitted for this purpose, even if it cannot be changed via
848 * $req->loadFromSubmission.
849 * @return Status
851 public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
852 $any = false;
853 $providers = $this->getPrimaryAuthenticationProviders() +
854 $this->getSecondaryAuthenticationProviders();
855 foreach ( $providers as $provider ) {
856 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
857 if ( !$status->isGood() ) {
858 return Status::wrap( $status );
860 $any = $any || $status->value !== 'ignored';
862 if ( !$any ) {
863 $status = Status::newGood( 'ignored' );
864 $status->warning( 'authmanager-change-not-supported' );
865 return $status;
867 return Status::newGood();
871 * Change authentication data (e.g. passwords)
873 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
874 * result in a successful login in the future.
876 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
877 * no longer result in a successful login.
879 * This method should only be called if allowsAuthenticationDataChange( $req, true )
880 * returned success.
882 * @param AuthenticationRequest $req
884 public function changeAuthenticationData( AuthenticationRequest $req ) {
885 $this->logger->info( 'Changing authentication data for {user} class {what}', [
886 'user' => is_string( $req->username ) ? $req->username : '<no name>',
887 'what' => get_class( $req ),
888 ] );
890 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
892 // When the main account's authentication data is changed, invalidate
893 // all BotPasswords too.
894 \BotPassword::invalidateAllPasswordsForUser( $req->username );
897 /**@}*/
900 * @name Account creation
901 * @{
905 * Determine whether accounts can be created
906 * @return bool
908 public function canCreateAccounts() {
909 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
910 switch ( $provider->accountCreationType() ) {
911 case PrimaryAuthenticationProvider::TYPE_CREATE:
912 case PrimaryAuthenticationProvider::TYPE_LINK:
913 return true;
916 return false;
920 * Determine whether a particular account can be created
921 * @param string $username MediaWiki username
922 * @param array $options
923 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
924 * - creating: (bool) For internal use only. Never specify this.
925 * @return Status
927 public function canCreateAccount( $username, $options = [] ) {
928 // Back compat
929 if ( is_int( $options ) ) {
930 $options = [ 'flags' => $options ];
932 $options += [
933 'flags' => User::READ_NORMAL,
934 'creating' => false,
936 $flags = $options['flags'];
938 if ( !$this->canCreateAccounts() ) {
939 return Status::newFatal( 'authmanager-create-disabled' );
942 if ( $this->userExists( $username, $flags ) ) {
943 return Status::newFatal( 'userexists' );
946 $user = User::newFromName( $username, 'creatable' );
947 if ( !is_object( $user ) ) {
948 return Status::newFatal( 'noname' );
949 } else {
950 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
951 if ( $user->getId() !== 0 ) {
952 return Status::newFatal( 'userexists' );
956 // Denied by providers?
957 $providers = $this->getPreAuthenticationProviders() +
958 $this->getPrimaryAuthenticationProviders() +
959 $this->getSecondaryAuthenticationProviders();
960 foreach ( $providers as $provider ) {
961 $status = $provider->testUserForCreation( $user, false, $options );
962 if ( !$status->isGood() ) {
963 return Status::wrap( $status );
967 return Status::newGood();
971 * Basic permissions checks on whether a user can create accounts
972 * @param User $creator User doing the account creation
973 * @return Status
975 public function checkAccountCreatePermissions( User $creator ) {
976 // Wiki is read-only?
977 if ( wfReadOnly() ) {
978 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
981 // This is awful, this permission check really shouldn't go through Title.
982 $permErrors = \SpecialPage::getTitleFor( 'CreateAccount' )
983 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
984 if ( $permErrors ) {
985 $status = Status::newGood();
986 foreach ( $permErrors as $args ) {
987 call_user_func_array( [ $status, 'fatal' ], $args );
989 return $status;
992 $block = $creator->isBlockedFromCreateAccount();
993 if ( $block ) {
994 $errorParams = [
995 $block->getTarget(),
996 $block->mReason ?: wfMessage( 'blockednoreason' )->text(),
997 $block->getByName()
1000 if ( $block->getType() === \Block::TYPE_RANGE ) {
1001 $errorMessage = 'cantcreateaccount-range-text';
1002 $errorParams[] = $this->getRequest()->getIP();
1003 } else {
1004 $errorMessage = 'cantcreateaccount-text';
1007 return Status::newFatal( wfMessage( $errorMessage, $errorParams ) );
1010 $ip = $this->getRequest()->getIP();
1011 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1012 return Status::newFatal( 'sorbs_create_account_reason' );
1015 return Status::newGood();
1019 * Start an account creation flow
1021 * In addition to the AuthenticationRequests returned by
1022 * $this->getAuthenticationRequests(), a client might include a
1023 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1024 * <code>
1025 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1026 * </code>
1027 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1028 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1029 * username set, that username must be used for all other requests.
1031 * @param User $creator User doing the account creation
1032 * @param AuthenticationRequest[] $reqs
1033 * @param string $returnToUrl Url that REDIRECT responses should eventually
1034 * return to.
1035 * @return AuthenticationResponse
1037 public function beginAccountCreation( User $creator, array $reqs, $returnToUrl ) {
1038 $session = $this->request->getSession();
1039 if ( !$this->canCreateAccounts() ) {
1040 // Caller should have called canCreateAccounts()
1041 $session->remove( 'AuthManager::accountCreationState' );
1042 throw new \LogicException( 'Account creation is not possible' );
1045 try {
1046 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
1047 } catch ( \UnexpectedValueException $ex ) {
1048 $username = null;
1050 if ( $username === null ) {
1051 $this->logger->debug( __METHOD__ . ': No username provided' );
1052 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1055 // Permissions check
1056 $status = $this->checkAccountCreatePermissions( $creator );
1057 if ( !$status->isGood() ) {
1058 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1059 'user' => $username,
1060 'creator' => $creator->getName(),
1061 'reason' => $status->getWikiText( null, null, 'en' )
1062 ] );
1063 return AuthenticationResponse::newFail( $status->getMessage() );
1066 $status = $this->canCreateAccount(
1067 $username, [ 'flags' => User::READ_LOCKING, 'creating' => true ]
1069 if ( !$status->isGood() ) {
1070 $this->logger->debug( __METHOD__ . ': {user} cannot be created: {reason}', [
1071 'user' => $username,
1072 'creator' => $creator->getName(),
1073 'reason' => $status->getWikiText( null, null, 'en' )
1074 ] );
1075 return AuthenticationResponse::newFail( $status->getMessage() );
1078 $user = User::newFromName( $username, 'creatable' );
1079 foreach ( $reqs as $req ) {
1080 $req->username = $username;
1081 $req->returnToUrl = $returnToUrl;
1082 if ( $req instanceof UserDataAuthenticationRequest ) {
1083 $status = $req->populateUser( $user );
1084 if ( !$status->isGood() ) {
1085 $status = Status::wrap( $status );
1086 $session->remove( 'AuthManager::accountCreationState' );
1087 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1088 'user' => $user->getName(),
1089 'creator' => $creator->getName(),
1090 'reason' => $status->getWikiText( null, null, 'en' ),
1091 ] );
1092 return AuthenticationResponse::newFail( $status->getMessage() );
1097 $this->removeAuthenticationSessionData( null );
1099 $state = [
1100 'username' => $username,
1101 'userid' => 0,
1102 'creatorid' => $creator->getId(),
1103 'creatorname' => $creator->getName(),
1104 'reqs' => $reqs,
1105 'returnToUrl' => $returnToUrl,
1106 'primary' => null,
1107 'primaryResponse' => null,
1108 'secondary' => [],
1109 'continueRequests' => [],
1110 'maybeLink' => [],
1111 'ranPreTests' => false,
1114 // Special case: converting a login to an account creation
1115 $req = AuthenticationRequest::getRequestByClass(
1116 $reqs, CreateFromLoginAuthenticationRequest::class
1118 if ( $req ) {
1119 $state['maybeLink'] = $req->maybeLink;
1121 if ( $req->createRequest ) {
1122 $reqs[] = $req->createRequest;
1123 $state['reqs'][] = $req->createRequest;
1127 $session->setSecret( 'AuthManager::accountCreationState', $state );
1128 $session->persist();
1130 return $this->continueAccountCreation( $reqs );
1134 * Continue an account creation flow
1135 * @param AuthenticationRequest[] $reqs
1136 * @return AuthenticationResponse
1138 public function continueAccountCreation( array $reqs ) {
1139 $session = $this->request->getSession();
1140 try {
1141 if ( !$this->canCreateAccounts() ) {
1142 // Caller should have called canCreateAccounts()
1143 $session->remove( 'AuthManager::accountCreationState' );
1144 throw new \LogicException( 'Account creation is not possible' );
1147 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1148 if ( !is_array( $state ) ) {
1149 return AuthenticationResponse::newFail(
1150 wfMessage( 'authmanager-create-not-in-progress' )
1153 $state['continueRequests'] = [];
1155 // Step 0: Prepare and validate the input
1157 $user = User::newFromName( $state['username'], 'creatable' );
1158 if ( !is_object( $user ) ) {
1159 $session->remove( 'AuthManager::accountCreationState' );
1160 $this->logger->debug( __METHOD__ . ': Invalid username', [
1161 'user' => $state['username'],
1162 ] );
1163 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1166 if ( $state['creatorid'] ) {
1167 $creator = User::newFromId( $state['creatorid'] );
1168 } else {
1169 $creator = new User;
1170 $creator->setName( $state['creatorname'] );
1173 // Avoid account creation races on double submissions
1174 $cache = \ObjectCache::getLocalClusterInstance();
1175 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1176 if ( !$lock ) {
1177 // Don't clear AuthManager::accountCreationState for this code
1178 // path because the process that won the race owns it.
1179 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1180 'user' => $user->getName(),
1181 'creator' => $creator->getName(),
1182 ] );
1183 return AuthenticationResponse::newFail( wfMessage( 'usernameinprogress' ) );
1186 // Permissions check
1187 $status = $this->checkAccountCreatePermissions( $creator );
1188 if ( !$status->isGood() ) {
1189 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1190 'user' => $user->getName(),
1191 'creator' => $creator->getName(),
1192 'reason' => $status->getWikiText( null, null, 'en' )
1193 ] );
1194 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1195 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1196 $session->remove( 'AuthManager::accountCreationState' );
1197 return $ret;
1200 // Load from master for existence check
1201 $user->load( User::READ_LOCKING );
1203 if ( $state['userid'] === 0 ) {
1204 if ( $user->getId() != 0 ) {
1205 $this->logger->debug( __METHOD__ . ': User exists locally', [
1206 'user' => $user->getName(),
1207 'creator' => $creator->getName(),
1208 ] );
1209 $ret = AuthenticationResponse::newFail( wfMessage( 'userexists' ) );
1210 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1211 $session->remove( 'AuthManager::accountCreationState' );
1212 return $ret;
1214 } else {
1215 if ( $user->getId() == 0 ) {
1216 $this->logger->debug( __METHOD__ . ': User does not exist locally when it should', [
1217 'user' => $user->getName(),
1218 'creator' => $creator->getName(),
1219 'expected_id' => $state['userid'],
1220 ] );
1221 throw new \UnexpectedValueException(
1222 "User \"{$state['username']}\" should exist now, but doesn't!"
1225 if ( $user->getId() != $state['userid'] ) {
1226 $this->logger->debug( __METHOD__ . ': User ID/name mismatch', [
1227 'user' => $user->getName(),
1228 'creator' => $creator->getName(),
1229 'expected_id' => $state['userid'],
1230 'actual_id' => $user->getId(),
1231 ] );
1232 throw new \UnexpectedValueException(
1233 "User \"{$state['username']}\" exists, but " .
1234 "ID {$user->getId()} != {$state['userid']}!"
1238 foreach ( $state['reqs'] as $req ) {
1239 if ( $req instanceof UserDataAuthenticationRequest ) {
1240 $status = $req->populateUser( $user );
1241 if ( !$status->isGood() ) {
1242 // This should never happen...
1243 $status = Status::wrap( $status );
1244 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1245 'user' => $user->getName(),
1246 'creator' => $creator->getName(),
1247 'reason' => $status->getWikiText( null, null, 'en' ),
1248 ] );
1249 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1250 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1251 $session->remove( 'AuthManager::accountCreationState' );
1252 return $ret;
1257 foreach ( $reqs as $req ) {
1258 $req->returnToUrl = $state['returnToUrl'];
1259 $req->username = $state['username'];
1262 // Run pre-creation tests, if we haven't already
1263 if ( !$state['ranPreTests'] ) {
1264 $providers = $this->getPreAuthenticationProviders() +
1265 $this->getPrimaryAuthenticationProviders() +
1266 $this->getSecondaryAuthenticationProviders();
1267 foreach ( $providers as $id => $provider ) {
1268 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1269 if ( !$status->isGood() ) {
1270 $this->logger->debug( __METHOD__ . ": Fail in pre-authentication by $id", [
1271 'user' => $user->getName(),
1272 'creator' => $creator->getName(),
1273 ] );
1274 $ret = AuthenticationResponse::newFail(
1275 Status::wrap( $status )->getMessage()
1277 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1278 $session->remove( 'AuthManager::accountCreationState' );
1279 return $ret;
1283 $state['ranPreTests'] = true;
1286 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1288 if ( $state['primary'] === null ) {
1289 // We haven't picked a PrimaryAuthenticationProvider yet
1290 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1291 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_NONE ) {
1292 continue;
1294 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1295 switch ( $res->status ) {
1296 case AuthenticationResponse::PASS;
1297 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1298 'user' => $user->getName(),
1299 'creator' => $creator->getName(),
1300 ] );
1301 $state['primary'] = $id;
1302 $state['primaryResponse'] = $res;
1303 break 2;
1304 case AuthenticationResponse::FAIL;
1305 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1306 'user' => $user->getName(),
1307 'creator' => $creator->getName(),
1308 ] );
1309 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1310 $session->remove( 'AuthManager::accountCreationState' );
1311 return $res;
1312 case AuthenticationResponse::ABSTAIN;
1313 // Continue loop
1314 break;
1315 case AuthenticationResponse::REDIRECT;
1316 case AuthenticationResponse::UI;
1317 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1318 'user' => $user->getName(),
1319 'creator' => $creator->getName(),
1320 ] );
1321 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1322 $state['primary'] = $id;
1323 $state['continueRequests'] = $res->neededRequests;
1324 $session->setSecret( 'AuthManager::accountCreationState', $state );
1325 return $res;
1327 // @codeCoverageIgnoreStart
1328 default:
1329 throw new \DomainException(
1330 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1332 // @codeCoverageIgnoreEnd
1335 if ( $state['primary'] === null ) {
1336 $this->logger->debug( __METHOD__ . ': Primary creation failed because no provider accepted', [
1337 'user' => $user->getName(),
1338 'creator' => $creator->getName(),
1339 ] );
1340 $ret = AuthenticationResponse::newFail(
1341 wfMessage( 'authmanager-create-no-primary' )
1343 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1344 $session->remove( 'AuthManager::accountCreationState' );
1345 return $ret;
1347 } elseif ( $state['primaryResponse'] === null ) {
1348 $provider = $this->getAuthenticationProvider( $state['primary'] );
1349 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1350 // Configuration changed? Force them to start over.
1351 // @codeCoverageIgnoreStart
1352 $ret = AuthenticationResponse::newFail(
1353 wfMessage( 'authmanager-create-not-in-progress' )
1355 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1356 $session->remove( 'AuthManager::accountCreationState' );
1357 return $ret;
1358 // @codeCoverageIgnoreEnd
1360 $id = $provider->getUniqueId();
1361 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1362 switch ( $res->status ) {
1363 case AuthenticationResponse::PASS;
1364 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1365 'user' => $user->getName(),
1366 'creator' => $creator->getName(),
1367 ] );
1368 $state['primaryResponse'] = $res;
1369 break;
1370 case AuthenticationResponse::FAIL;
1371 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1372 'user' => $user->getName(),
1373 'creator' => $creator->getName(),
1374 ] );
1375 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1376 $session->remove( 'AuthManager::accountCreationState' );
1377 return $res;
1378 case AuthenticationResponse::REDIRECT;
1379 case AuthenticationResponse::UI;
1380 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1381 'user' => $user->getName(),
1382 'creator' => $creator->getName(),
1383 ] );
1384 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1385 $state['continueRequests'] = $res->neededRequests;
1386 $session->setSecret( 'AuthManager::accountCreationState', $state );
1387 return $res;
1388 default:
1389 throw new \DomainException(
1390 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1395 // Step 2: Primary authentication succeeded, create the User object
1396 // and add the user locally.
1398 if ( $state['userid'] === 0 ) {
1399 $this->logger->info( 'Creating user {user} during account creation', [
1400 'user' => $user->getName(),
1401 'creator' => $creator->getName(),
1402 ] );
1403 $status = $user->addToDatabase();
1404 if ( !$status->isOK() ) {
1405 // @codeCoverageIgnoreStart
1406 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1407 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1408 $session->remove( 'AuthManager::accountCreationState' );
1409 return $ret;
1410 // @codeCoverageIgnoreEnd
1412 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1413 \Hooks::run( 'LocalUserCreated', [ $user, false ] );
1414 $user->saveSettings();
1415 $state['userid'] = $user->getId();
1417 // Update user count
1418 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1420 // Watch user's userpage and talk page
1421 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1423 // Inform the provider
1424 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1426 // Log the creation
1427 if ( $this->config->get( 'NewUserLog' ) ) {
1428 $isAnon = $creator->isAnon();
1429 $logEntry = new \ManualLogEntry(
1430 'newusers',
1431 $logSubtype ?: ( $isAnon ? 'create' : 'create2' )
1433 $logEntry->setPerformer( $isAnon ? $user : $creator );
1434 $logEntry->setTarget( $user->getUserPage() );
1435 /** @var CreationReasonAuthenticationRequest $req */
1436 $req = AuthenticationRequest::getRequestByClass(
1437 $state['reqs'], CreationReasonAuthenticationRequest::class
1439 $logEntry->setComment( $req ? $req->reason : '' );
1440 $logEntry->setParameters( [
1441 '4::userid' => $user->getId(),
1442 ] );
1443 $logid = $logEntry->insert();
1444 $logEntry->publish( $logid );
1448 // Step 3: Iterate over all the secondary authentication providers.
1450 $beginReqs = $state['reqs'];
1452 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1453 if ( !isset( $state['secondary'][$id] ) ) {
1454 // This provider isn't started yet, so we pass it the set
1455 // of reqs from beginAuthentication instead of whatever
1456 // might have been used by a previous provider in line.
1457 $func = 'beginSecondaryAccountCreation';
1458 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1459 } elseif ( !$state['secondary'][$id] ) {
1460 $func = 'continueSecondaryAccountCreation';
1461 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1462 } else {
1463 continue;
1465 switch ( $res->status ) {
1466 case AuthenticationResponse::PASS;
1467 $this->logger->debug( __METHOD__ . ": Secondary creation passed by $id", [
1468 'user' => $user->getName(),
1469 'creator' => $creator->getName(),
1470 ] );
1471 // fall through
1472 case AuthenticationResponse::ABSTAIN;
1473 $state['secondary'][$id] = true;
1474 break;
1475 case AuthenticationResponse::REDIRECT;
1476 case AuthenticationResponse::UI;
1477 $this->logger->debug( __METHOD__ . ": Secondary creation $res->status by $id", [
1478 'user' => $user->getName(),
1479 'creator' => $creator->getName(),
1480 ] );
1481 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1482 $state['secondary'][$id] = false;
1483 $state['continueRequests'] = $res->neededRequests;
1484 $session->setSecret( 'AuthManager::accountCreationState', $state );
1485 return $res;
1486 case AuthenticationResponse::FAIL;
1487 throw new \DomainException(
1488 get_class( $provider ) . "::{$func}() returned $res->status." .
1489 ' Secondary providers are not allowed to fail account creation, that' .
1490 ' should have been done via testForAccountCreation().'
1492 // @codeCoverageIgnoreStart
1493 default:
1494 throw new \DomainException(
1495 get_class( $provider ) . "::{$func}() returned $res->status"
1497 // @codeCoverageIgnoreEnd
1501 $id = $user->getId();
1502 $name = $user->getName();
1503 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1504 $ret = AuthenticationResponse::newPass( $name );
1505 $ret->loginRequest = $req;
1506 $this->createdAccountAuthenticationRequests[] = $req;
1508 $this->logger->info( __METHOD__ . ': Account creation succeeded for {user}', [
1509 'user' => $user->getName(),
1510 'creator' => $creator->getName(),
1511 ] );
1513 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1514 $session->remove( 'AuthManager::accountCreationState' );
1515 $this->removeAuthenticationSessionData( null );
1516 return $ret;
1517 } catch ( \Exception $ex ) {
1518 $session->remove( 'AuthManager::accountCreationState' );
1519 throw $ex;
1524 * Auto-create an account, and log into that account
1526 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1527 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1528 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1529 * the username of a non-existing user from provideSessionInfo(). Calling this method
1530 * explicitly (e.g. from a maintenance script) is also fine.
1532 * @param User $user User to auto-create
1533 * @param string $source What caused the auto-creation? This must be the ID
1534 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1535 * @param bool $login Whether to also log the user in
1536 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1538 public function autoCreateUser( User $user, $source, $login = true ) {
1539 if ( $source !== self::AUTOCREATE_SOURCE_SESSION &&
1540 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1542 throw new \InvalidArgumentException( "Unknown auto-creation source: $source" );
1545 $username = $user->getName();
1547 // Try the local user from the replica DB
1548 $localId = User::idFromName( $username );
1549 $flags = User::READ_NORMAL;
1551 // Fetch the user ID from the master, so that we don't try to create the user
1552 // when they already exist, due to replication lag
1553 // @codeCoverageIgnoreStart
1554 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
1555 $localId = User::idFromName( $username, User::READ_LATEST );
1556 $flags = User::READ_LATEST;
1558 // @codeCoverageIgnoreEnd
1560 if ( $localId ) {
1561 $this->logger->debug( __METHOD__ . ': {username} already exists locally', [
1562 'username' => $username,
1563 ] );
1564 $user->setId( $localId );
1565 $user->loadFromId( $flags );
1566 if ( $login ) {
1567 $this->setSessionDataForUser( $user );
1569 $status = Status::newGood();
1570 $status->warning( 'userexists' );
1571 return $status;
1574 // Wiki is read-only?
1575 if ( wfReadOnly() ) {
1576 $this->logger->debug( __METHOD__ . ': denied by wfReadOnly(): {reason}', [
1577 'username' => $username,
1578 'reason' => wfReadOnlyReason(),
1579 ] );
1580 $user->setId( 0 );
1581 $user->loadFromId();
1582 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
1585 // Check the session, if we tried to create this user already there's
1586 // no point in retrying.
1587 $session = $this->request->getSession();
1588 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1589 $this->logger->debug( __METHOD__ . ': blacklisted in session {sessionid}', [
1590 'username' => $username,
1591 'sessionid' => $session->getId(),
1592 ] );
1593 $user->setId( 0 );
1594 $user->loadFromId();
1595 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1596 if ( $reason instanceof StatusValue ) {
1597 return Status::wrap( $reason );
1598 } else {
1599 return Status::newFatal( $reason );
1603 // Is the username creatable?
1604 if ( !User::isCreatableName( $username ) ) {
1605 $this->logger->debug( __METHOD__ . ': name "{username}" is not creatable', [
1606 'username' => $username,
1607 ] );
1608 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname' );
1609 $user->setId( 0 );
1610 $user->loadFromId();
1611 return Status::newFatal( 'noname' );
1614 // Is the IP user able to create accounts?
1615 $anon = new User;
1616 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1617 $this->logger->debug( __METHOD__ . ': IP lacks the ability to create or autocreate accounts', [
1618 'username' => $username,
1619 'ip' => $anon->getName(),
1620 ] );
1621 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm' );
1622 $session->persist();
1623 $user->setId( 0 );
1624 $user->loadFromId();
1625 return Status::newFatal( 'authmanager-autocreate-noperm' );
1628 // Avoid account creation races on double submissions
1629 $cache = \ObjectCache::getLocalClusterInstance();
1630 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1631 if ( !$lock ) {
1632 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1633 'user' => $username,
1634 ] );
1635 $user->setId( 0 );
1636 $user->loadFromId();
1637 return Status::newFatal( 'usernameinprogress' );
1640 // Denied by providers?
1641 $options = [
1642 'flags' => User::READ_LATEST,
1643 'creating' => true,
1645 $providers = $this->getPreAuthenticationProviders() +
1646 $this->getPrimaryAuthenticationProviders() +
1647 $this->getSecondaryAuthenticationProviders();
1648 foreach ( $providers as $provider ) {
1649 $status = $provider->testUserForCreation( $user, $source, $options );
1650 if ( !$status->isGood() ) {
1651 $ret = Status::wrap( $status );
1652 $this->logger->debug( __METHOD__ . ': Provider denied creation of {username}: {reason}', [
1653 'username' => $username,
1654 'reason' => $ret->getWikiText( null, null, 'en' ),
1655 ] );
1656 $session->set( 'AuthManager::AutoCreateBlacklist', $status );
1657 $user->setId( 0 );
1658 $user->loadFromId();
1659 return $ret;
1663 $backoffKey = wfMemcKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1664 if ( $cache->get( $backoffKey ) ) {
1665 $this->logger->debug( __METHOD__ . ': {username} denied by prior creation attempt failures', [
1666 'username' => $username,
1667 ] );
1668 $user->setId( 0 );
1669 $user->loadFromId();
1670 return Status::newFatal( 'authmanager-autocreate-exception' );
1673 // Checks passed, create the user...
1674 $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI';
1675 $this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [
1676 'username' => $username,
1677 'from' => $from,
1678 ] );
1680 // Ignore warnings about master connections/writes...hard to avoid here
1681 $trxProfiler = \Profiler::instance()->getTransactionProfiler();
1682 $old = $trxProfiler->setSilenced( true );
1683 try {
1684 $status = $user->addToDatabase();
1685 if ( !$status->isOK() ) {
1686 // Double-check for a race condition (T70012). We make use of the fact that when
1687 // addToDatabase fails due to the user already existing, the user object gets loaded.
1688 if ( $user->getId() ) {
1689 $this->logger->info( __METHOD__ . ': {username} already exists locally (race)', [
1690 'username' => $username,
1691 ] );
1692 if ( $login ) {
1693 $this->setSessionDataForUser( $user );
1695 $status = Status::newGood();
1696 $status->warning( 'userexists' );
1697 } else {
1698 $this->logger->error( __METHOD__ . ': {username} failed with message {msg}', [
1699 'username' => $username,
1700 'msg' => $status->getWikiText( null, null, 'en' )
1701 ] );
1702 $user->setId( 0 );
1703 $user->loadFromId();
1705 return $status;
1707 } catch ( \Exception $ex ) {
1708 $trxProfiler->setSilenced( $old );
1709 $this->logger->error( __METHOD__ . ': {username} failed with exception {exception}', [
1710 'username' => $username,
1711 'exception' => $ex,
1712 ] );
1713 // Do not keep throwing errors for a while
1714 $cache->set( $backoffKey, 1, 600 );
1715 // Bubble up error; which should normally trigger DB rollbacks
1716 throw $ex;
1719 $this->setDefaultUserOptions( $user, false );
1721 // Inform the providers
1722 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1724 \Hooks::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1725 \Hooks::run( 'LocalUserCreated', [ $user, true ] );
1726 $user->saveSettings();
1728 // Update user count
1729 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
1730 // Watch user's userpage and talk page
1731 \DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1732 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1733 } );
1735 // Log the creation
1736 if ( $this->config->get( 'NewUserLog' ) ) {
1737 $logEntry = new \ManualLogEntry( 'newusers', 'autocreate' );
1738 $logEntry->setPerformer( $user );
1739 $logEntry->setTarget( $user->getUserPage() );
1740 $logEntry->setComment( '' );
1741 $logEntry->setParameters( [
1742 '4::userid' => $user->getId(),
1743 ] );
1744 $logEntry->insert();
1747 $trxProfiler->setSilenced( $old );
1749 if ( $login ) {
1750 $this->setSessionDataForUser( $user );
1753 return Status::newGood();
1756 /**@}*/
1759 * @name Account linking
1760 * @{
1764 * Determine whether accounts can be linked
1765 * @return bool
1767 public function canLinkAccounts() {
1768 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1769 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
1770 return true;
1773 return false;
1777 * Start an account linking flow
1779 * @param User $user User being linked
1780 * @param AuthenticationRequest[] $reqs
1781 * @param string $returnToUrl Url that REDIRECT responses should eventually
1782 * return to.
1783 * @return AuthenticationResponse
1785 public function beginAccountLink( User $user, array $reqs, $returnToUrl ) {
1786 $session = $this->request->getSession();
1787 $session->remove( 'AuthManager::accountLinkState' );
1789 if ( !$this->canLinkAccounts() ) {
1790 // Caller should have called canLinkAccounts()
1791 throw new \LogicException( 'Account linking is not possible' );
1794 if ( $user->getId() === 0 ) {
1795 if ( !User::isUsableName( $user->getName() ) ) {
1796 $msg = wfMessage( 'noname' );
1797 } else {
1798 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1800 return AuthenticationResponse::newFail( $msg );
1802 foreach ( $reqs as $req ) {
1803 $req->username = $user->getName();
1804 $req->returnToUrl = $returnToUrl;
1807 $this->removeAuthenticationSessionData( null );
1809 $providers = $this->getPreAuthenticationProviders();
1810 foreach ( $providers as $id => $provider ) {
1811 $status = $provider->testForAccountLink( $user );
1812 if ( !$status->isGood() ) {
1813 $this->logger->debug( __METHOD__ . ": Account linking pre-check failed by $id", [
1814 'user' => $user->getName(),
1815 ] );
1816 $ret = AuthenticationResponse::newFail(
1817 Status::wrap( $status )->getMessage()
1819 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1820 return $ret;
1824 $state = [
1825 'username' => $user->getName(),
1826 'userid' => $user->getId(),
1827 'returnToUrl' => $returnToUrl,
1828 'primary' => null,
1829 'continueRequests' => [],
1832 $providers = $this->getPrimaryAuthenticationProviders();
1833 foreach ( $providers as $id => $provider ) {
1834 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider::TYPE_LINK ) {
1835 continue;
1838 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1839 switch ( $res->status ) {
1840 case AuthenticationResponse::PASS;
1841 $this->logger->info( "Account linked to {user} by $id", [
1842 'user' => $user->getName(),
1843 ] );
1844 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1845 return $res;
1847 case AuthenticationResponse::FAIL;
1848 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1849 'user' => $user->getName(),
1850 ] );
1851 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1852 return $res;
1854 case AuthenticationResponse::ABSTAIN;
1855 // Continue loop
1856 break;
1858 case AuthenticationResponse::REDIRECT;
1859 case AuthenticationResponse::UI;
1860 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1861 'user' => $user->getName(),
1862 ] );
1863 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1864 $state['primary'] = $id;
1865 $state['continueRequests'] = $res->neededRequests;
1866 $session->setSecret( 'AuthManager::accountLinkState', $state );
1867 $session->persist();
1868 return $res;
1870 // @codeCoverageIgnoreStart
1871 default:
1872 throw new \DomainException(
1873 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1875 // @codeCoverageIgnoreEnd
1879 $this->logger->debug( __METHOD__ . ': Account linking failed because no provider accepted', [
1880 'user' => $user->getName(),
1881 ] );
1882 $ret = AuthenticationResponse::newFail(
1883 wfMessage( 'authmanager-link-no-primary' )
1885 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1886 return $ret;
1890 * Continue an account linking flow
1891 * @param AuthenticationRequest[] $reqs
1892 * @return AuthenticationResponse
1894 public function continueAccountLink( array $reqs ) {
1895 $session = $this->request->getSession();
1896 try {
1897 if ( !$this->canLinkAccounts() ) {
1898 // Caller should have called canLinkAccounts()
1899 $session->remove( 'AuthManager::accountLinkState' );
1900 throw new \LogicException( 'Account linking is not possible' );
1903 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1904 if ( !is_array( $state ) ) {
1905 return AuthenticationResponse::newFail(
1906 wfMessage( 'authmanager-link-not-in-progress' )
1909 $state['continueRequests'] = [];
1911 // Step 0: Prepare and validate the input
1913 $user = User::newFromName( $state['username'], 'usable' );
1914 if ( !is_object( $user ) ) {
1915 $session->remove( 'AuthManager::accountLinkState' );
1916 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1918 if ( $user->getId() != $state['userid'] ) {
1919 throw new \UnexpectedValueException(
1920 "User \"{$state['username']}\" is valid, but " .
1921 "ID {$user->getId()} != {$state['userid']}!"
1925 foreach ( $reqs as $req ) {
1926 $req->username = $state['username'];
1927 $req->returnToUrl = $state['returnToUrl'];
1930 // Step 1: Call the primary again until it succeeds
1932 $provider = $this->getAuthenticationProvider( $state['primary'] );
1933 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1934 // Configuration changed? Force them to start over.
1935 // @codeCoverageIgnoreStart
1936 $ret = AuthenticationResponse::newFail(
1937 wfMessage( 'authmanager-link-not-in-progress' )
1939 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1940 $session->remove( 'AuthManager::accountLinkState' );
1941 return $ret;
1942 // @codeCoverageIgnoreEnd
1944 $id = $provider->getUniqueId();
1945 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1946 switch ( $res->status ) {
1947 case AuthenticationResponse::PASS;
1948 $this->logger->info( "Account linked to {user} by $id", [
1949 'user' => $user->getName(),
1950 ] );
1951 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1952 $session->remove( 'AuthManager::accountLinkState' );
1953 return $res;
1954 case AuthenticationResponse::FAIL;
1955 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1956 'user' => $user->getName(),
1957 ] );
1958 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1959 $session->remove( 'AuthManager::accountLinkState' );
1960 return $res;
1961 case AuthenticationResponse::REDIRECT;
1962 case AuthenticationResponse::UI;
1963 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1964 'user' => $user->getName(),
1965 ] );
1966 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1967 $state['continueRequests'] = $res->neededRequests;
1968 $session->setSecret( 'AuthManager::accountLinkState', $state );
1969 return $res;
1970 default:
1971 throw new \DomainException(
1972 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1975 } catch ( \Exception $ex ) {
1976 $session->remove( 'AuthManager::accountLinkState' );
1977 throw $ex;
1981 /**@}*/
1984 * @name Information methods
1985 * @{
1989 * Return the applicable list of AuthenticationRequests
1991 * Possible values for $action:
1992 * - ACTION_LOGIN: Valid for passing to beginAuthentication
1993 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
1994 * - ACTION_CREATE: Valid for passing to beginAccountCreation
1995 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
1996 * - ACTION_LINK: Valid for passing to beginAccountLink
1997 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
1998 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
1999 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2000 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2002 * @param string $action One of the AuthManager::ACTION_* constants
2003 * @param User|null $user User being acted on, instead of the current user.
2004 * @return AuthenticationRequest[]
2006 public function getAuthenticationRequests( $action, User $user = null ) {
2007 $options = [];
2008 $providerAction = $action;
2010 // Figure out which providers to query
2011 switch ( $action ) {
2012 case self::ACTION_LOGIN:
2013 case self::ACTION_CREATE:
2014 $providers = $this->getPreAuthenticationProviders() +
2015 $this->getPrimaryAuthenticationProviders() +
2016 $this->getSecondaryAuthenticationProviders();
2017 break;
2019 case self::ACTION_LOGIN_CONTINUE:
2020 $state = $this->request->getSession()->getSecret( 'AuthManager::authnState' );
2021 return is_array( $state ) ? $state['continueRequests'] : [];
2023 case self::ACTION_CREATE_CONTINUE:
2024 $state = $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' );
2025 return is_array( $state ) ? $state['continueRequests'] : [];
2027 case self::ACTION_LINK:
2028 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2029 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2030 } );
2031 break;
2033 case self::ACTION_UNLINK:
2034 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2035 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2036 } );
2038 // To providers, unlink and remove are identical.
2039 $providerAction = self::ACTION_REMOVE;
2040 break;
2042 case self::ACTION_LINK_CONTINUE:
2043 $state = $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' );
2044 return is_array( $state ) ? $state['continueRequests'] : [];
2046 case self::ACTION_CHANGE:
2047 case self::ACTION_REMOVE:
2048 $providers = $this->getPrimaryAuthenticationProviders() +
2049 $this->getSecondaryAuthenticationProviders();
2050 break;
2052 // @codeCoverageIgnoreStart
2053 default:
2054 throw new \DomainException( __METHOD__ . ": Invalid action \"$action\"" );
2056 // @codeCoverageIgnoreEnd
2058 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2062 * Internal request lookup for self::getAuthenticationRequests
2064 * @param string $providerAction Action to pass to providers
2065 * @param array $options Options to pass to providers
2066 * @param AuthenticationProvider[] $providers
2067 * @param User|null $user
2068 * @return AuthenticationRequest[]
2070 private function getAuthenticationRequestsInternal(
2071 $providerAction, array $options, array $providers, User $user = null
2073 $user = $user ?: \RequestContext::getMain()->getUser();
2074 $options['username'] = $user->isAnon() ? null : $user->getName();
2076 // Query them and merge results
2077 $reqs = [];
2078 foreach ( $providers as $provider ) {
2079 $isPrimary = $provider instanceof PrimaryAuthenticationProvider;
2080 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2081 $id = $req->getUniqueId();
2083 // If a required request if from a Primary, mark it as "primary-required" instead
2084 if ( $isPrimary ) {
2085 if ( $req->required ) {
2086 $req->required = AuthenticationRequest::PRIMARY_REQUIRED;
2090 if (
2091 !isset( $reqs[$id] )
2092 || $req->required === AuthenticationRequest::REQUIRED
2093 || $reqs[$id] === AuthenticationRequest::OPTIONAL
2095 $reqs[$id] = $req;
2100 // AuthManager has its own req for some actions
2101 switch ( $providerAction ) {
2102 case self::ACTION_LOGIN:
2103 $reqs[] = new RememberMeAuthenticationRequest;
2104 break;
2106 case self::ACTION_CREATE:
2107 $reqs[] = new UsernameAuthenticationRequest;
2108 $reqs[] = new UserDataAuthenticationRequest;
2109 if ( $options['username'] !== null ) {
2110 $reqs[] = new CreationReasonAuthenticationRequest;
2111 $options['username'] = null; // Don't fill in the username below
2113 break;
2116 // Fill in reqs data
2117 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2119 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2120 if ( $providerAction === self::ACTION_CHANGE || $providerAction === self::ACTION_REMOVE ) {
2121 $reqs = array_filter( $reqs, function ( $req ) {
2122 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2123 } );
2126 return array_values( $reqs );
2130 * Set values in an array of requests
2131 * @param AuthenticationRequest[] &$reqs
2132 * @param string $action
2133 * @param string|null $username
2134 * @param boolean $forceAction
2136 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2137 foreach ( $reqs as $req ) {
2138 if ( !$req->action || $forceAction ) {
2139 $req->action = $action;
2141 if ( $req->username === null ) {
2142 $req->username = $username;
2148 * Determine whether a username exists
2149 * @param string $username
2150 * @param int $flags Bitfield of User:READ_* constants
2151 * @return bool
2153 public function userExists( $username, $flags = User::READ_NORMAL ) {
2154 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2155 if ( $provider->testUserExists( $username, $flags ) ) {
2156 return true;
2160 return false;
2164 * Determine whether a user property should be allowed to be changed.
2166 * Supported properties are:
2167 * - emailaddress
2168 * - realname
2169 * - nickname
2171 * @param string $property
2172 * @return bool
2174 public function allowsPropertyChange( $property ) {
2175 $providers = $this->getPrimaryAuthenticationProviders() +
2176 $this->getSecondaryAuthenticationProviders();
2177 foreach ( $providers as $provider ) {
2178 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2179 return false;
2182 return true;
2186 * Get a provider by ID
2187 * @note This is public so extensions can check whether their own provider
2188 * is installed and so they can read its configuration if necessary.
2189 * Other uses are not recommended.
2190 * @param string $id
2191 * @return AuthenticationProvider|null
2193 public function getAuthenticationProvider( $id ) {
2194 // Fast version
2195 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2196 return $this->allAuthenticationProviders[$id];
2199 // Slow version: instantiate each kind and check
2200 $providers = $this->getPrimaryAuthenticationProviders();
2201 if ( isset( $providers[$id] ) ) {
2202 return $providers[$id];
2204 $providers = $this->getSecondaryAuthenticationProviders();
2205 if ( isset( $providers[$id] ) ) {
2206 return $providers[$id];
2208 $providers = $this->getPreAuthenticationProviders();
2209 if ( isset( $providers[$id] ) ) {
2210 return $providers[$id];
2213 return null;
2216 /**@}*/
2219 * @name Internal methods
2220 * @{
2224 * Store authentication in the current session
2225 * @protected For use by AuthenticationProviders
2226 * @param string $key
2227 * @param mixed $data Must be serializable
2229 public function setAuthenticationSessionData( $key, $data ) {
2230 $session = $this->request->getSession();
2231 $arr = $session->getSecret( 'authData' );
2232 if ( !is_array( $arr ) ) {
2233 $arr = [];
2235 $arr[$key] = $data;
2236 $session->setSecret( 'authData', $arr );
2240 * Fetch authentication data from the current session
2241 * @protected For use by AuthenticationProviders
2242 * @param string $key
2243 * @param mixed $default
2244 * @return mixed
2246 public function getAuthenticationSessionData( $key, $default = null ) {
2247 $arr = $this->request->getSession()->getSecret( 'authData' );
2248 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2249 return $arr[$key];
2250 } else {
2251 return $default;
2256 * Remove authentication data
2257 * @protected For use by AuthenticationProviders
2258 * @param string|null $key If null, all data is removed
2260 public function removeAuthenticationSessionData( $key ) {
2261 $session = $this->request->getSession();
2262 if ( $key === null ) {
2263 $session->remove( 'authData' );
2264 } else {
2265 $arr = $session->getSecret( 'authData' );
2266 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2267 unset( $arr[$key] );
2268 $session->setSecret( 'authData', $arr );
2274 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2275 * @param string $class
2276 * @param array[] $specs
2277 * @return AuthenticationProvider[]
2279 protected function providerArrayFromSpecs( $class, array $specs ) {
2280 $i = 0;
2281 foreach ( $specs as &$spec ) {
2282 $spec = [ 'sort2' => $i++ ] + $spec + [ 'sort' => 0 ];
2284 unset( $spec );
2285 usort( $specs, function ( $a, $b ) {
2286 return ( (int)$a['sort'] ) - ( (int)$b['sort'] )
2287 ?: $a['sort2'] - $b['sort2'];
2288 } );
2290 $ret = [];
2291 foreach ( $specs as $spec ) {
2292 $provider = \ObjectFactory::getObjectFromSpec( $spec );
2293 if ( !$provider instanceof $class ) {
2294 throw new \RuntimeException(
2295 "Expected instance of $class, got " . get_class( $provider )
2298 $provider->setLogger( $this->logger );
2299 $provider->setManager( $this );
2300 $provider->setConfig( $this->config );
2301 $id = $provider->getUniqueId();
2302 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2303 throw new \RuntimeException(
2304 "Duplicate specifications for id $id (classes " .
2305 get_class( $provider ) . ' and ' .
2306 get_class( $this->allAuthenticationProviders[$id] ) . ')'
2309 $this->allAuthenticationProviders[$id] = $provider;
2310 $ret[$id] = $provider;
2312 return $ret;
2316 * Get the configuration
2317 * @return array
2319 private function getConfiguration() {
2320 return $this->config->get( 'AuthManagerConfig' ) ?: $this->config->get( 'AuthManagerAutoConfig' );
2324 * Get the list of PreAuthenticationProviders
2325 * @return PreAuthenticationProvider[]
2327 protected function getPreAuthenticationProviders() {
2328 if ( $this->preAuthenticationProviders === null ) {
2329 $conf = $this->getConfiguration();
2330 $this->preAuthenticationProviders = $this->providerArrayFromSpecs(
2331 PreAuthenticationProvider::class, $conf['preauth']
2334 return $this->preAuthenticationProviders;
2338 * Get the list of PrimaryAuthenticationProviders
2339 * @return PrimaryAuthenticationProvider[]
2341 protected function getPrimaryAuthenticationProviders() {
2342 if ( $this->primaryAuthenticationProviders === null ) {
2343 $conf = $this->getConfiguration();
2344 $this->primaryAuthenticationProviders = $this->providerArrayFromSpecs(
2345 PrimaryAuthenticationProvider::class, $conf['primaryauth']
2348 return $this->primaryAuthenticationProviders;
2352 * Get the list of SecondaryAuthenticationProviders
2353 * @return SecondaryAuthenticationProvider[]
2355 protected function getSecondaryAuthenticationProviders() {
2356 if ( $this->secondaryAuthenticationProviders === null ) {
2357 $conf = $this->getConfiguration();
2358 $this->secondaryAuthenticationProviders = $this->providerArrayFromSpecs(
2359 SecondaryAuthenticationProvider::class, $conf['secondaryauth']
2362 return $this->secondaryAuthenticationProviders;
2366 * Log the user in
2367 * @param User $user
2368 * @param bool|null $remember
2370 private function setSessionDataForUser( $user, $remember = null ) {
2371 $session = $this->request->getSession();
2372 $delay = $session->delaySave();
2374 $session->resetId();
2375 $session->resetAllTokens();
2376 if ( $session->canSetUser() ) {
2377 $session->setUser( $user );
2379 if ( $remember !== null ) {
2380 $session->setRememberUser( $remember );
2382 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2383 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2384 $session->persist();
2386 \Wikimedia\ScopedCallback::consume( $delay );
2388 \Hooks::run( 'UserLoggedIn', [ $user ] );
2392 * @param User $user
2393 * @param bool $useContextLang Use 'uselang' to set the user's language
2395 private function setDefaultUserOptions( User $user, $useContextLang ) {
2396 global $wgContLang;
2398 $user->setToken();
2400 $lang = $useContextLang ? \RequestContext::getMain()->getLanguage() : $wgContLang;
2401 $user->setOption( 'language', $lang->getPreferredVariant() );
2403 if ( $wgContLang->hasVariants() ) {
2404 $user->setOption( 'variant', $wgContLang->getPreferredVariant() );
2409 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2410 * @param string $method
2411 * @param array $args
2413 private function callMethodOnProviders( $which, $method, array $args ) {
2414 $providers = [];
2415 if ( $which & 1 ) {
2416 $providers += $this->getPreAuthenticationProviders();
2418 if ( $which & 2 ) {
2419 $providers += $this->getPrimaryAuthenticationProviders();
2421 if ( $which & 4 ) {
2422 $providers += $this->getSecondaryAuthenticationProviders();
2424 foreach ( $providers as $provider ) {
2425 call_user_func_array( [ $provider, $method ], $args );
2430 * Reset the internal caching for unit testing
2431 * @protected Unit tests only
2433 public static function resetCache() {
2434 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2435 // @codeCoverageIgnoreStart
2436 throw new \MWException( __METHOD__ . ' may only be called from unit tests!' );
2437 // @codeCoverageIgnoreEnd
2440 self::$instance = null;
2443 /**@}*/
2448 * For really cool vim folding this needs to be at the end:
2449 * vim: foldmarker=@{,@} foldmethod=marker