5use InvalidArgumentException;
28use UnexpectedValueException;
45 AuthManager::ACTION_LOGIN, AuthManager::ACTION_LOGIN_CONTINUE,
46 AuthManager::ACTION_CREATE, AuthManager::ACTION_CREATE_CONTINUE,
47 AuthManager::ACTION_LINK, AuthManager::ACTION_LINK_CONTINUE,
48 AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK,
85 array $requests, array $fieldInfo, array &$formDescriptor, $action
99 return $this->savedRequest ?: $this->
getContext()->getRequest();
112 protected function setRequest( array $data, $wasPosted =
null ) {
114 $this->isFakePostRequest = $wasPosted ===
true &&
$request->wasPosted() ===
false;
148 $key =
'AuthManagerSpecialPage:return:' . $this->
getName();
155 $authData = array_diff_key( $this->
getRequest()->getValues(),
156 $preservedParams, [
'title' => 1 ] );
157 $uniqueId = MWCryptRand::generateHex( 6 );
158 $preservedParams[
'authUniqueId'] = $uniqueId;
159 $key .=
':' . $uniqueId;
160 $authManager->setAuthenticationSessionData( $key, $authData );
165 } elseif ( $this->
getRequest()->getCheck(
'authUniqueId' ) ) {
166 $uniqueId = $this->
getRequest()->getVal(
'authUniqueId' );
167 $key .=
':' . $uniqueId;
168 $authData = $authManager->getAuthenticationSessionData( $key );
170 $authManager->removeAuthenticationSessionData( $key );
171 $this->isReturn =
true;
173 $this->setPostTransactionProfilerExpectations( __METHOD__ );
193 $key =
'AuthManagerSpecialPage:reauth:' . $this->
getName();
196 if ( $securityLevel ) {
197 $securityStatus = $authManager->securitySensitiveOperationStatus( $securityLevel );
198 if ( $securityStatus === AuthManager::SEC_REAUTH ) {
199 $queryParams = array_diff_key(
$request->getQueryValues(), [
'title' =>
true ] );
203 $uniqueId = MWCryptRand::generateHex( 6 );
204 $key .=
':' . $uniqueId;
206 $queryParams = [
'authUniqueId' => $uniqueId ] + $queryParams;
207 $authData = array_diff_key(
$request->getValues(),
208 $this->getPreservedParams(), [
'title' => 1 ] );
209 $authManager->setAuthenticationSessionData( $key, $authData );
214 $keepParams = [
'uselang',
'useskin',
'useformat',
'variant',
'debug',
'safemode' ];
217 $url = $title->getFullURL( [
218 'returnto' => $this->
getFullTitle()->getPrefixedDBkey(),
220 'force' => $securityLevel,
221 ] + array_intersect_key( $queryParams, array_fill_keys( $keepParams,
true ) ),
false,
PROTO_HTTPS );
227 if ( $securityStatus !== AuthManager::SEC_OK ) {
228 throw new ErrorPageError(
'cannotauth-not-allowed-title',
'cannotauth-not-allowed' );
231 $this->
getAuthManager()->securitySensitiveOperationDone( $securityLevel );
234 $uniqueId =
$request->getVal(
'authUniqueId' );
236 $key .=
':' . $uniqueId;
237 $authData = $authManager->getAuthenticationSessionData( $key );
239 $authManager->removeAuthenticationSessionData( $key );
241 $this->setPostTransactionProfilerExpectations( __METHOD__ );
248 private function setPostTransactionProfilerExpectations(
string $fname ) {
250 $trxProfiler = Profiler::instance()->getTransactionProfiler();
251 $trxProfiler->redefineExpectations( $trxLimits[
'POST'], $fname );
252 DeferredUpdates::addCallableUpdate(
static function () use ( $trxProfiler, $trxLimits, $fname ) {
253 $trxProfiler->redefineExpectations( $trxLimits[
'PostSend-POST'], $fname );
273 return array_key_exists( $defaultKey, static::$messages )
274 ? static::$messages[$defaultKey] : $defaultKey;
299 return $this->
getAuthManager()->getAuthenticationRequests( $action,
318 !$reset && $this->subPage ===
$subPage && $this->authAction
327 if ( !in_array( $this->authAction, static::$allowedActions,
true ) ) {
331 if ( in_array( $continueAction, static::$allowedActions,
true ) ) {
332 $this->authAction = $continueAction;
338 $this->authRequests = array_filter( $allReqs,
function ( $req ) {
348 return in_array( $this->authAction, [
349 AuthManager::ACTION_LOGIN_CONTINUE,
350 AuthManager::ACTION_CREATE_CONTINUE,
351 AuthManager::ACTION_LINK_CONTINUE,
362 case AuthManager::ACTION_LOGIN:
363 $action = AuthManager::ACTION_LOGIN_CONTINUE;
365 case AuthManager::ACTION_CREATE:
366 $action = AuthManager::ACTION_CREATE_CONTINUE;
368 case AuthManager::ACTION_LINK:
369 $action = AuthManager::ACTION_LINK_CONTINUE;
384 if ( !in_array( $action, static::$allowedActions,
true ) ) {
385 throw new InvalidArgumentException(
'invalid action: ' . $action );
397 case AuthManager::ACTION_LOGIN:
398 case AuthManager::ACTION_LOGIN_CONTINUE:
399 return $authManager->canAuthenticateNow();
400 case AuthManager::ACTION_CREATE:
401 case AuthManager::ACTION_CREATE_CONTINUE:
402 return $authManager->canCreateAccounts();
403 case AuthManager::ACTION_LINK:
404 case AuthManager::ACTION_LINK_CONTINUE:
405 return $authManager->canLinkAccounts();
406 case AuthManager::ACTION_CHANGE:
407 case AuthManager::ACTION_REMOVE:
408 case AuthManager::ACTION_UNLINK:
412 throw new InvalidArgumentException(
'invalid action: ' . $action );
423 if ( !in_array( $action, static::$allowedActions,
true ) ) {
424 throw new InvalidArgumentException(
'invalid action: ' . $action );
432 case AuthManager::ACTION_LOGIN:
433 return $authManager->beginAuthentication( $requests, $returnToUrl );
434 case AuthManager::ACTION_LOGIN_CONTINUE:
435 return $authManager->continueAuthentication( $requests );
436 case AuthManager::ACTION_CREATE:
437 return $authManager->beginAccountCreation( $this->
getAuthority(), $requests,
439 case AuthManager::ACTION_CREATE_CONTINUE:
440 return $authManager->continueAccountCreation( $requests );
441 case AuthManager::ACTION_LINK:
442 return $authManager->beginAccountLink( $this->
getUser(), $requests, $returnToUrl );
443 case AuthManager::ACTION_LINK_CONTINUE:
444 return $authManager->continueAccountLink( $requests );
445 case AuthManager::ACTION_CHANGE:
446 case AuthManager::ACTION_REMOVE:
447 case AuthManager::ACTION_UNLINK:
448 if ( count( $requests ) > 1 ) {
449 throw new InvalidArgumentException(
'only one auth request can be changed at a time' );
453 throw new InvalidArgumentException(
'no auth request' );
455 $req = reset( $requests );
456 $status = $authManager->allowsAuthenticationDataChange( $req );
457 $this->
getHookRunner()->onChangeAuthenticationDataAudit( $req, $status );
458 if ( !$status->isGood() ) {
459 return AuthenticationResponse::newFail( $status->getMessage() );
461 $authManager->changeAuthenticationData( $req );
462 return AuthenticationResponse::newPass();
465 throw new InvalidArgumentException(
'invalid action: ' . $action );
482 $form = $this->
getAuthForm( $this->authRequests, $this->authAction );
489 if ( $sessionToken->wasNew() && ( !$this->isFakePostRequest || $this->isReturn ) ) {
491 return Status::newFatal( $this->
messageKey(
'authform-newtoken' ) );
492 } elseif ( !$requestTokenValue ) {
493 return Status::newFatal( $this->
messageKey(
'authform-notoken' ) );
494 } elseif ( !$sessionToken->match( $requestTokenValue ) ) {
495 return Status::newFatal( $this->
messageKey(
'authform-wrongtoken' ) );
498 $form->prepareForm();
499 $status = $form->trySubmit();
503 if ( $status ===
true ) {
505 throw new UnexpectedValueException(
'HTMLForm::trySubmit() returned true' );
506 } elseif ( $status ===
false ) {
508 } elseif ( $status instanceof
Status ) {
510 } elseif ( $status instanceof StatusValue ) {
513 $status = Status::wrap( $status );
514 } elseif ( is_string( $status ) ) {
515 $status = Status::newFatal(
new RawMessage(
'$1', [ $status ] ) );
516 } elseif ( is_array( $status ) ) {
517 if ( is_string( reset( $status ) ) ) {
519 $status = Status::newFatal( ...$status );
520 } elseif ( is_array( reset( $status ) ) ) {
521 $ret = Status::newGood();
522 foreach ( $status as $message ) {
524 $ret->fatal( ...$message );
528 throw new UnexpectedValueException(
'invalid HTMLForm::trySubmit() return value: '
529 .
'first element of array is ' . get_debug_type( reset( $status ) ) );
534 throw new UnexpectedValueException(
'invalid HTMLForm::trySubmit() return type: '
535 . get_debug_type( $status ) );
538 if ( ( !$status || !$status->isOK() ) && $this->isReturn ) {
543 LoggerFactory::getInstance(
'authentication' )
544 ->warning(
'Validation error on return', [
'data' => $form->mFieldData,
545 'status' => $status->getWikiText(
false,
false,
'en' ) ] );
551 AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK
553 if ( in_array( $this->authAction, $changeActions,
true ) && $status && !$status->isOK() ) {
554 $this->
getHookRunner()->onChangeAuthenticationDataAudit( reset( $this->authRequests ), $status );
567 $requests = AuthenticationRequest::loadRequestsFromSubmission( $this->authRequests, $data );
571 return Status::newGood( $response );
596 if ( is_bool( $options ) ) {
597 wfDeprecated( __METHOD__ .
' boolean $options',
'1.43' );
598 $options = [
'withToken' => $options ];
602 'withToken' =>
false,
605 $params = $options[
'params'] ?? [];
606 if ( !$options[
'reset'] && $this->authAction !== $this->
getDefaultAction( $this->subPage ) ) {
609 if ( $options[
'withToken'] ) {
614 return $loginHelper->getPreservedParams( [
'reset' => $options[
'reset'],
'params' => $params ] );
625 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
630 return $formDescriptor;
642 if ( $context->getRequest() !== $this->getRequest() ) {
647 $form = HTMLForm::factory(
'ooui', $formDescriptor, $context );
650 $form->addHiddenField(
'authAction', $this->authAction );
661 if ( $status instanceof StatusValue ) {
662 $status = Status::wrap( $status );
664 $form = $this->
getAuthForm( $this->authRequests, $this->authAction );
665 $form->prepareForm()->displayForm( $status );
680 $customSubmitButtonPresent =
false;
686 foreach ( $requests as $req ) {
687 if ( $req->required === AuthenticationRequest::PRIMARY_REQUIRED ) {
689 $customSubmitButtonPresent =
true;
695 return !$customSubmitButtonPresent;
705 if ( $info[
'type'] ===
'button' ) {
719 foreach ( $formDescriptor as &$definition ) {
721 if ( array_key_exists(
'class', $definition ) ) {
722 $class = $definition[
'class'];
723 } elseif ( array_key_exists(
'type', $definition ) ) {
724 $class = HTMLForm::$typeMappings[$definition[
'type']];
726 if ( $class !== HTMLInfoField::class ) {
727 $definition[
'tabindex'] = $i;
739 return $this->
getRequest()->getSession()->getToken(
'AuthManagerSpecialPage:'
749 return 'wpAuthToken';
762 $formDescriptor = [];
763 foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
767 $requestSnapshot = serialize( $requests );
769 $this->
getHookRunner()->onAuthChangeFormFields( $requests, $fieldInfo,
770 $formDescriptor, $action );
771 if ( $requestSnapshot !== serialize( $requests ) ) {
772 LoggerFactory::getInstance(
'authentication' )->warning(
773 'AuthChangeFormFields hook changed auth requests' );
780 return $formDescriptor;
795 'name' => $fieldName,
798 if ( $type ===
'submit' && isset( $singleFieldInfo[
'label'] ) ) {
799 $descriptor[
'default'] = $singleFieldInfo[
'label']->plain();
800 } elseif ( $type !==
'submit' ) {
801 $descriptor += array_filter( [
803 'label-message' => self::getField( $singleFieldInfo,
'label' ),
806 if ( isset( $singleFieldInfo[
'options'] ) ) {
807 $descriptor[
'options'] = array_flip( array_map(
static function ( $message ) {
809 return $message->parse();
810 }, $singleFieldInfo[
'options'] ) );
813 if ( isset( $singleFieldInfo[
'value'] ) ) {
814 $descriptor[
'default'] = $singleFieldInfo[
'value'];
817 if ( empty( $singleFieldInfo[
'optional'] ) ) {
818 $descriptor[
'required'] =
true;
832 foreach ( $formDescriptor as &$field ) {
833 $field[
'__index'] = $i++;
836 uasort( $formDescriptor,
static function ( $first, $second ) {
838 ?: $first[
'__index'] <=> $second[
'__index'];
840 foreach ( $formDescriptor as &$field ) {
841 unset( $field[
'__index'] );
852 protected static function getField( array $array, $fieldName, $default =
null ) {
853 if ( array_key_exists( $fieldName, $array ) ) {
854 return $array[$fieldName];
870 'password' =>
'password',
871 'select' =>
'select',
872 'checkbox' =>
'check',
873 'multiselect' =>
'multiselect',
874 'button' =>
'submit',
875 'hidden' =>
'hidden',
878 if ( !array_key_exists( $type, $map ) ) {
879 throw new InvalidArgumentException(
'invalid field type: ' . $type );
897 array $fieldInfo, array $formDescriptor, array $defaultFormDescriptor
900 foreach ( $defaultFormDescriptor as $fieldName => $defaultField ) {
904 !isset( $fieldInfo[$fieldName] )
906 !isset( $defaultField[
'baseField'] )
907 || !isset( $fieldInfo[$defaultField[
'baseField']] )
910 !isset( $defaultField[
'type'] )
911 || !in_array( $defaultField[
'type'], [
'submit',
'info' ],
true )
914 $defaultFormDescriptor[$fieldName] =
null;
919 $requestField = $formDescriptor[$fieldName] ?? [];
921 isset( $defaultField[
'label'] )
922 || isset( $defaultField[
'label-message'] )
923 || isset( $defaultField[
'label-raw'] )
925 unset( $requestField[
'label'], $requestField[
'label-message'], $defaultField[
'label-raw'] );
928 $defaultFormDescriptor[$fieldName] += $requestField;
931 return array_filter( $defaultFormDescriptor + $formDescriptor );
937class_alias( AuthManagerSpecialPage::class,
'AuthManagerSpecialPage' );
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
An IContextSource implementation which will inherit context from another source but allow individual ...
An error page which can definitely be safely rendered using the OutputPage.
A class containing constants representing the names of configuration variables.
const TrxProfilerLimits
Name constant for the TrxProfilerLimits setting, for use with Config\get().
A special page subclass for authentication-related special pages.
AuthenticationRequest[] $authRequests
string $subPage
Subpage of the special page.
performAuthenticationStep( $action, array $requests)
getToken()
Returns the CSRF token.
bool $isReturn
True if the current request is a result of returning from a redirect flow.
static array $messages
Customized messages.
handleReturnBeforeExecute( $subPage)
Handle redirection from the /return subpage.
static mapFieldInfoTypeToFormDescriptorType( $type)
Maps AuthenticationRequest\getFieldInfo() types to HTMLForm types.
getAuthFormDescriptor( $requests, $action)
Generates a HTMLForm descriptor array from a set of authentication requests.
getAuthForm(array $requests, $action)
setRequest(array $data, $wasPosted=null)
Override the POST data, GET data from the real request is preserved.
static getField(array $array, $fieldName, $default=null)
Get an array value, or a default if it does not exist.
displayForm( $status)
Display the form.
getContinueAction( $action)
Gets the _CONTINUE version of an action.
static sortFormDescriptorFields(array &$formDescriptor)
Sort the fields of a form descriptor by their 'weight' property.
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Change the form descriptor that determines how a field will look in the authentication form.
static mapSingleFieldInfo( $singleFieldInfo, $fieldName)
Maps an authentication field configuration for a single field (as returned by AuthenticationRequest\g...
isContinued()
Returns true if this is not the first step of the authentication.
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button.
handleReauthBeforeExecute( $subPage)
Handle redirection when the user needs to (re)authenticate.
string $authAction
one of the AuthManager\ACTION_* constants.
messageKey( $defaultKey)
Return custom message key.
static string[] $allowedActions
The list of actions this special page deals with.
static mergeDefaultFormDescriptor(array $fieldInfo, array $formDescriptor, array $defaultFormDescriptor)
Apply defaults to a form descriptor, without creating non-existent fields.
isActionAllowed( $action)
Checks whether AuthManager is ready to perform the action.
beforeExecute( $subPage)
Gets called before execute.Return false to prevent calling execute() (since 1.27+)....
getRequestBlacklist()
Allows blacklisting certain request types.
trySubmit()
Attempts to do an authentication step with the submitted data.
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
getTokenName()
Returns the name of the CSRF token (under which it should be found in the POST or GET data).
addTabIndex(&$formDescriptor)
Adds a sequential tabindex starting from 1 to all form elements.
getPreservedParams( $options=[])
Returns URL query parameters which should be preserved between authentication requests.
fieldInfoToFormDescriptor(array $requests, array $fieldInfo, $action)
Turns a field info array into a form descriptor.
handleFormSubmit( $data)
Submit handler callback for HTMLForm.
bool $isFakePostRequest
Set when we're pretending that we got a POST request during redirect flows.
getDefaultAction( $subPage)
Get the default action for this special page if none is given via URL/POST data.
getAuthenticationRequests( $action, ?UserIdentity $user=null)
Get the list of AuthenticationRequests from the AuthManager.
hasOwnSubmitButton(AuthenticationRequest $req)
Checks whether the given AuthenticationRequest has its own submit button.
getRequest()
Get the WebRequest being used for this instance.WebRequest 1.18
WebRequest null $savedRequest
If set, will be used instead of the real request.
Parent class for all special pages.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
getUser()
Shortcut to get the User executing this instance.
getPageTitle( $subpage=false)
Get a self-referential title object.
getConfig()
Shortcut to get main config object.
getContext()
Gets the context this SpecialPage is executed in.
getOutput()
Get the OutputPage being used for this instance.
getAuthority()
Shortcut to get the Authority executing this instance.
getName()
Get the canonical, unlocalized name of this special page without namespace.
getFullTitle()
Return the full title, including $par.