Merge "Perform a permission check on the title when changing the page language"
[lhc/web/wiklou.git] / includes / specialpage / AuthManagerSpecialPage.php
1 <?php
2
3 use MediaWiki\Auth\AuthenticationRequest;
4 use MediaWiki\Auth\AuthenticationResponse;
5 use MediaWiki\Auth\AuthManager;
6 use MediaWiki\Logger\LoggerFactory;
7 use MediaWiki\Session\Token;
8
9 /**
10 * A special page subclass for authentication-related special pages. It generates a form from
11 * a set of AuthenticationRequest objects, submits the result to AuthManager and
12 * partially handles the response.
13 */
14 abstract class AuthManagerSpecialPage extends SpecialPage {
15 /** @var string[] The list of actions this special page deals with. Subclasses should override
16 * this. */
17 protected static $allowedActions = [
18 AuthManager::ACTION_LOGIN, AuthManager::ACTION_LOGIN_CONTINUE,
19 AuthManager::ACTION_CREATE, AuthManager::ACTION_CREATE_CONTINUE,
20 AuthManager::ACTION_LINK, AuthManager::ACTION_LINK_CONTINUE,
21 AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK,
22 ];
23
24 /** @var array Customized messages */
25 protected static $messages = [];
26
27 /** @var string one of the AuthManager::ACTION_* constants. */
28 protected $authAction;
29
30 /** @var AuthenticationRequest[] */
31 protected $authRequests;
32
33 /** @var string Subpage of the special page. */
34 protected $subPage;
35
36 /** @var bool True if the current request is a result of returning from a redirect flow. */
37 protected $isReturn;
38
39 /** @var WebRequest|null If set, will be used instead of the real request. Used for redirection. */
40 protected $savedRequest;
41
42 /**
43 * Change the form descriptor that determines how a field will look in the authentication form.
44 * Called from fieldInfoToFormDescriptor().
45 * @param AuthenticationRequest[] $requests
46 * @param array $fieldInfo Field information array (union of all
47 * AuthenticationRequest::getFieldInfo() responses).
48 * @param array &$formDescriptor HTMLForm descriptor. The special key 'weight' can be set to
49 * change the order of the fields.
50 * @param string $action Authentication type (one of the AuthManager::ACTION_* constants)
51 * @return bool
52 */
53 public function onAuthChangeFormFields(
54 array $requests, array $fieldInfo, array &$formDescriptor, $action
55 ) {
56 return true;
57 }
58
59 protected function getLoginSecurityLevel() {
60 return $this->getName();
61 }
62
63 public function getRequest() {
64 return $this->savedRequest ?: $this->getContext()->getRequest();
65 }
66
67 /**
68 * Override the POST data, GET data from the real request is preserved.
69 *
70 * Used to preserve POST data over a HTTP redirect.
71 *
72 * @param array $data
73 * @param bool $wasPosted
74 */
75 protected function setRequest( array $data, $wasPosted = null ) {
76 $request = $this->getContext()->getRequest();
77 if ( $wasPosted === null ) {
78 $wasPosted = $request->wasPosted();
79 }
80 $this->savedRequest = new DerivativeRequest( $request, $data + $request->getQueryValues(),
81 $wasPosted );
82 }
83
84 protected function beforeExecute( $subPage ) {
85 $this->getOutput()->disallowUserJs();
86
87 return $this->handleReturnBeforeExecute( $subPage )
88 && $this->handleReauthBeforeExecute( $subPage );
89 }
90
91 /**
92 * Handle redirection from the /return subpage.
93 *
94 * This is used in the redirect flow where we need
95 * to be able to process data that was sent via a GET request. We set the /return subpage as
96 * the reentry point so we know we need to treat GET as POST, but we don't want to handle all
97 * future GETs as POSTs so we need to normalize the URL. (Also we don't want to show any
98 * received parameters around in the URL; they are ugly and might be sensitive.)
99 *
100 * Thus when on the /return subpage, we stash the request data in the session, redirect, then
101 * use the session to detect that we have been redirected, recover the data and replace the
102 * real WebRequest with a fake one that contains the saved data.
103 *
104 * @param string $subPage
105 * @return bool False if execution should be stopped.
106 */
107 protected function handleReturnBeforeExecute( $subPage ) {
108 $authManager = AuthManager::singleton();
109 $key = 'AuthManagerSpecialPage:return:' . $this->getName();
110
111 if ( $subPage === 'return' ) {
112 $this->loadAuth( $subPage );
113 $preservedParams = $this->getPreservedParams( false );
114
115 // FIXME save POST values only from request
116 $authData = array_diff_key( $this->getRequest()->getValues(),
117 $preservedParams, [ 'title' => 1 ] );
118 $authManager->setAuthenticationSessionData( $key, $authData );
119
120 $url = $this->getPageTitle()->getFullURL( $preservedParams, false, PROTO_HTTPS );
121 $this->getOutput()->redirect( $url );
122 return false;
123 }
124
125 $authData = $authManager->getAuthenticationSessionData( $key );
126 if ( $authData ) {
127 $authManager->removeAuthenticationSessionData( $key );
128 $this->isReturn = true;
129 $this->setRequest( $authData, true );
130 }
131
132 return true;
133 }
134
135 /**
136 * Handle redirection when the user needs to (re)authenticate.
137 *
138 * Send the user to the login form if needed; in case the request was a POST, stash in the
139 * session and simulate it once the user gets back.
140 *
141 * @param string $subPage
142 * @return bool False if execution should be stopped.
143 * @throws ErrorPageError When the user is not allowed to use this page.
144 */
145 protected function handleReauthBeforeExecute( $subPage ) {
146 $authManager = AuthManager::singleton();
147 $request = $this->getRequest();
148 $key = 'AuthManagerSpecialPage:reauth:' . $this->getName();
149
150 $securityLevel = $this->getLoginSecurityLevel();
151 if ( $securityLevel ) {
152 $securityStatus = AuthManager::singleton()
153 ->securitySensitiveOperationStatus( $securityLevel );
154 if ( $securityStatus === AuthManager::SEC_REAUTH ) {
155 $queryParams = array_diff_key( $request->getQueryValues(), [ 'title' => true ] );
156
157 if ( $request->wasPosted() ) {
158 // unique ID in case the same special page is open in multiple browser tabs
159 $uniqueId = MWCryptRand::generateHex( 6 );
160 $key = $key . ':' . $uniqueId;
161
162 $queryParams = [ 'authUniqueId' => $uniqueId ] + $queryParams;
163 $authData = array_diff_key( $request->getValues(),
164 $this->getPreservedParams( false ), [ 'title' => 1 ] );
165 $authManager->setAuthenticationSessionData( $key, $authData );
166 }
167
168 $title = SpecialPage::getTitleFor( 'Userlogin' );
169 $url = $title->getFullURL( [
170 'returnto' => $this->getFullTitle()->getPrefixedDBkey(),
171 'returntoquery' => wfArrayToCgi( $queryParams ),
172 'force' => $securityLevel,
173 ], false, PROTO_HTTPS );
174
175 $this->getOutput()->redirect( $url );
176 return false;
177 } elseif ( $securityStatus !== AuthManager::SEC_OK ) {
178 throw new ErrorPageError( 'cannotauth-not-allowed-title', 'cannotauth-not-allowed' );
179 }
180 }
181
182 $uniqueId = $request->getVal( 'authUniqueId' );
183 if ( $uniqueId ) {
184 $key = $key . ':' . $uniqueId;
185 $authData = $authManager->getAuthenticationSessionData( $key );
186 if ( $authData ) {
187 $authManager->removeAuthenticationSessionData( $key );
188 $this->setRequest( $authData, true );
189 }
190 }
191
192 return true;
193 }
194
195 /**
196 * Get the default action for this special page, if none is given via URL/POST data.
197 * Subclasses should override this (or override loadAuth() so this is never called).
198 * @param string $subPage Subpage of the special page.
199 * @return string an AuthManager::ACTION_* constant.
200 */
201 abstract protected function getDefaultAction( $subPage );
202
203 /**
204 * Return custom message key.
205 * Allows subclasses to customize messages.
206 * @param string $defaultKey
207 * @return string
208 */
209 protected function messageKey( $defaultKey ) {
210 return array_key_exists( $defaultKey, static::$messages )
211 ? static::$messages[$defaultKey] : $defaultKey;
212 }
213
214 /**
215 * Allows blacklisting certain request types.
216 * @return array A list of AuthenticationRequest subclass names
217 */
218 protected function getRequestBlacklist() {
219 return [];
220 }
221
222 /**
223 * Load or initialize $authAction, $authRequests and $subPage.
224 * Subclasses should call this from execute() or otherwise ensure the variables are initialized.
225 * @param string $subPage Subpage of the special page.
226 * @param string $authAction Override auth action specified in request (this is useful
227 * when the form needs to be changed from <action> to <action>_CONTINUE after a successful
228 * authentication step)
229 * @param bool $reset Regenerate the requests even if a cached version is available
230 */
231 protected function loadAuth( $subPage, $authAction = null, $reset = false ) {
232 // Do not load if already loaded, to cut down on the number of getAuthenticationRequests
233 // calls. This is important for requests which have hidden information so any
234 // getAuthenticationRequests call would mean putting data into some cache.
235 if (
236 !$reset && $this->subPage === $subPage && $this->authAction
237 && ( !$authAction || $authAction === $this->authAction )
238 ) {
239 return;
240 }
241
242 $request = $this->getRequest();
243 $this->subPage = $subPage;
244 $this->authAction = $authAction ?: $request->getText( 'authAction' );
245 if ( !in_array( $this->authAction, static::$allowedActions, true ) ) {
246 $this->authAction = $this->getDefaultAction( $subPage );
247 if ( $request->wasPosted() ) {
248 $continueAction = $this->getContinueAction( $this->authAction );
249 if ( in_array( $continueAction, static::$allowedActions, true ) ) {
250 $this->authAction = $continueAction;
251 }
252 }
253 }
254
255 $allReqs = AuthManager::singleton()->getAuthenticationRequests(
256 $this->authAction, $this->getUser() );
257 $this->authRequests = array_filter( $allReqs, function ( $req ) use ( $subPage ) {
258 return !in_array( get_class( $req ), $this->getRequestBlacklist(), true );
259 } );
260 }
261
262 /**
263 * Returns true if this is not the first step of the authentication.
264 * @return bool
265 */
266 protected function isContinued() {
267 return in_array( $this->authAction, [
268 AuthManager::ACTION_LOGIN_CONTINUE,
269 AuthManager::ACTION_CREATE_CONTINUE,
270 AuthManager::ACTION_LINK_CONTINUE,
271 ], true );
272 }
273
274 /**
275 * Gets the _CONTINUE version of an action.
276 * @param string $action An AuthManager::ACTION_* constant.
277 * @return string An AuthManager::ACTION_*_CONTINUE constant.
278 */
279 protected function getContinueAction( $action ) {
280 switch ( $action ) {
281 case AuthManager::ACTION_LOGIN:
282 $action = AuthManager::ACTION_LOGIN_CONTINUE;
283 break;
284 case AuthManager::ACTION_CREATE:
285 $action = AuthManager::ACTION_CREATE_CONTINUE;
286 break;
287 case AuthManager::ACTION_LINK:
288 $action = AuthManager::ACTION_LINK_CONTINUE;
289 break;
290 }
291 return $action;
292 }
293
294 /**
295 * Checks whether AuthManager is ready to perform the action.
296 * ACTION_CHANGE needs special verification (AuthManager::allowsAuthenticationData*) which is
297 * the caller's responsibility.
298 * @param string $action One of the AuthManager::ACTION_* constants in static::$allowedActions
299 * @return bool
300 * @throws LogicException if $action is invalid
301 */
302 protected function isActionAllowed( $action ) {
303 $authManager = AuthManager::singleton();
304 if ( !in_array( $action, static::$allowedActions, true ) ) {
305 throw new InvalidArgumentException( 'invalid action: ' . $action );
306 }
307
308 // calling getAuthenticationRequests can be expensive, avoid if possible
309 $requests = ( $action === $this->authAction ) ? $this->authRequests
310 : $authManager->getAuthenticationRequests( $action );
311 if ( !$requests ) {
312 // no provider supports this action in the current state
313 return false;
314 }
315
316 switch ( $action ) {
317 case AuthManager::ACTION_LOGIN:
318 case AuthManager::ACTION_LOGIN_CONTINUE:
319 return $authManager->canAuthenticateNow();
320 case AuthManager::ACTION_CREATE:
321 case AuthManager::ACTION_CREATE_CONTINUE:
322 return $authManager->canCreateAccounts();
323 case AuthManager::ACTION_LINK:
324 case AuthManager::ACTION_LINK_CONTINUE:
325 return $authManager->canLinkAccounts();
326 case AuthManager::ACTION_CHANGE:
327 case AuthManager::ACTION_REMOVE:
328 case AuthManager::ACTION_UNLINK:
329 return true;
330 default:
331 // should never reach here but makes static code analyzers happy
332 throw new InvalidArgumentException( 'invalid action: ' . $action );
333 }
334 }
335
336 /**
337 * @param string $action One of the AuthManager::ACTION_* constants
338 * @param AuthenticationRequest[] $requests
339 * @return AuthenticationResponse
340 * @throws LogicException if $action is invalid
341 */
342 protected function performAuthenticationStep( $action, array $requests ) {
343 if ( !in_array( $action, static::$allowedActions, true ) ) {
344 throw new InvalidArgumentException( 'invalid action: ' . $action );
345 }
346
347 $authManager = AuthManager::singleton();
348 $returnToUrl = $this->getPageTitle( 'return' )
349 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
350
351 switch ( $action ) {
352 case AuthManager::ACTION_LOGIN:
353 return $authManager->beginAuthentication( $requests, $returnToUrl );
354 case AuthManager::ACTION_LOGIN_CONTINUE:
355 return $authManager->continueAuthentication( $requests );
356 case AuthManager::ACTION_CREATE:
357 return $authManager->beginAccountCreation( $this->getUser(), $requests,
358 $returnToUrl );
359 case AuthManager::ACTION_CREATE_CONTINUE:
360 return $authManager->continueAccountCreation( $requests );
361 case AuthManager::ACTION_LINK:
362 return $authManager->beginAccountLink( $this->getUser(), $requests, $returnToUrl );
363 case AuthManager::ACTION_LINK_CONTINUE:
364 return $authManager->continueAccountLink( $requests );
365 case AuthManager::ACTION_CHANGE:
366 case AuthManager::ACTION_REMOVE:
367 case AuthManager::ACTION_UNLINK:
368 if ( count( $requests ) > 1 ) {
369 throw new InvalidArgumentException( 'only one auth request can be changed at a time' );
370 } elseif ( !$requests ) {
371 throw new InvalidArgumentException( 'no auth request' );
372 }
373 $req = reset( $requests );
374 $status = $authManager->allowsAuthenticationDataChange( $req );
375 Hooks::run( 'ChangeAuthenticationDataAudit', [ $req, $status ] );
376 if ( !$status->isGood() ) {
377 return AuthenticationResponse::newFail( $status->getMessage() );
378 }
379 $authManager->changeAuthenticationData( $req );
380 return AuthenticationResponse::newPass();
381 default:
382 // should never reach here but makes static code analyzers happy
383 throw new InvalidArgumentException( 'invalid action: ' . $action );
384 }
385 }
386
387 /**
388 * Attempts to do an authentication step with the submitted data.
389 * Subclasses should probably call this from execute().
390 * @return false|Status
391 * - false if there was no submit at all
392 * - a good Status wrapping an AuthenticationResponse if the form submit was successful.
393 * This does not necessarily mean that the authentication itself was successful; see the
394 * response for that.
395 * - a bad Status for form errors.
396 */
397 protected function trySubmit() {
398 $status = false;
399
400 $form = $this->getAuthForm( $this->authRequests, $this->authAction );
401 $form->setSubmitCallback( [ $this, 'handleFormSubmit' ] );
402
403 if ( $this->getRequest()->wasPosted() ) {
404 // handle tokens manually; $form->tryAuthorizedSubmit only works for logged-in users
405 $requestTokenValue = $this->getRequest()->getVal( $this->getTokenName() );
406 $sessionToken = $this->getToken();
407 if ( $sessionToken->wasNew() ) {
408 return Status::newFatal( $this->messageKey( 'authform-newtoken' ) );
409 } elseif ( !$requestTokenValue ) {
410 return Status::newFatal( $this->messageKey( 'authform-notoken' ) );
411 } elseif ( !$sessionToken->match( $requestTokenValue ) ) {
412 return Status::newFatal( $this->messageKey( 'authform-wrongtoken' ) );
413 }
414
415 $form->prepareForm();
416 $status = $form->trySubmit();
417
418 // HTMLForm submit return values are a mess; let's ensure it is false or a Status
419 // FIXME this probably should be in HTMLForm
420 if ( $status === true ) {
421 // not supposed to happen since our submit handler should always return a Status
422 throw new UnexpectedValueException( 'HTMLForm::trySubmit() returned true' );
423 } elseif ( $status === false ) {
424 // form was not submitted; nothing to do
425 } elseif ( $status instanceof Status ) {
426 // already handled by the form; nothing to do
427 } elseif ( $status instanceof StatusValue ) {
428 // in theory not an allowed return type but nothing stops the submit handler from
429 // accidentally returning it so best check and fix
430 $status = Status::wrap( $status );
431 } elseif ( is_string( $status ) ) {
432 $status = Status::newFatal( new RawMessage( '$1', $status ) );
433 } elseif ( is_array( $status ) ) {
434 if ( is_string( reset( $status ) ) ) {
435 $status = call_user_func_array( 'Status::newFatal', $status );
436 } elseif ( is_array( reset( $status ) ) ) {
437 $status = Status::newGood();
438 foreach ( $status as $message ) {
439 call_user_func_array( [ $status, 'fatal' ], $message );
440 }
441 } else {
442 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return value: '
443 . 'first element of array is ' . gettype( reset( $status ) ) );
444 }
445 } else {
446 // not supposed to happen but HTMLForm does not actually verify the return type
447 // from the submit callback; better safe then sorry
448 throw new UnexpectedValueException( 'invalid HTMLForm::trySubmit() return type: '
449 . gettype( $status ) );
450 }
451
452 if ( ( !$status || !$status->isOK() ) && $this->isReturn ) {
453 // This is awkward. There was a form validation error, which means the data was not
454 // passed to AuthManager. Normally we would display the form with an error message,
455 // but for the data we received via the redirect flow that would not be helpful at all.
456 // Let's just submit the data to AuthManager directly instead.
457 LoggerFactory::getInstance( 'authentication' )
458 ->warning( 'Validation error on return', [ 'data' => $form->mFieldData,
459 'status' => $status->getWikiText() ] );
460 $status = $this->handleFormSubmit( $form->mFieldData );
461 }
462 }
463
464 $changeActions = [
465 AuthManager::ACTION_CHANGE, AuthManager::ACTION_REMOVE, AuthManager::ACTION_UNLINK
466 ];
467 if ( in_array( $this->authAction, $changeActions, true ) && $status && !$status->isOK() ) {
468 Hooks::run( 'ChangeAuthenticationDataAudit', [ reset( $this->authRequests ), $status ] );
469 }
470
471 return $status;
472 }
473
474 /**
475 * Submit handler callback for HTMLForm
476 * @private
477 * @param array $data Submitted data
478 * @return Status
479 */
480 public function handleFormSubmit( $data ) {
481 $requests = AuthenticationRequest::loadRequestsFromSubmission( $this->authRequests, $data );
482 $response = $this->performAuthenticationStep( $this->authAction, $requests );
483
484 // we can't handle FAIL or similar as failure here since it might require changing the form
485 return Status::newGood( $response );
486 }
487
488 /**
489 * Returns URL query parameters which can be used to reload the page (or leave and return) while
490 * preserving all information that is necessary for authentication to continue. These parameters
491 * will be preserved in the action URL of the form and in the return URL for redirect flow.
492 * @param bool $withToken Include CSRF token
493 * @return array
494 */
495 protected function getPreservedParams( $withToken = false ) {
496 $params = [];
497 if ( $this->authAction !== $this->getDefaultAction( $this->subPage ) ) {
498 $params['authAction'] = $this->getContinueAction( $this->authAction );
499 }
500 if ( $withToken ) {
501 $params[$this->getTokenName()] = $this->getToken()->toString();
502 }
503 return $params;
504 }
505
506 /**
507 * Generates a HTMLForm descriptor array from a set of authentication requests.
508 * @param AuthenticationRequest[] $requests
509 * @param string $action AuthManager action name (one of the AuthManager::ACTION_* constants)
510 * @return array
511 */
512 protected function getAuthFormDescriptor( $requests, $action ) {
513 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
514 $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $action );
515
516 $this->addTabIndex( $formDescriptor );
517
518 return $formDescriptor;
519 }
520
521 /**
522 * @param AuthenticationRequest[] $requests
523 * @param string $action AuthManager action name (one of the AuthManager::ACTION_* constants)
524 * @return HTMLForm
525 */
526 protected function getAuthForm( array $requests, $action ) {
527 $formDescriptor = $this->getAuthFormDescriptor( $requests, $action );
528 $context = $this->getContext();
529 if ( $context->getRequest() !== $this->getRequest() ) {
530 // We have overridden the request, need to make sure the form uses that too.
531 $context = new DerivativeContext( $this->getContext() );
532 $context->setRequest( $this->getRequest() );
533 }
534 $form = HTMLForm::factory( 'ooui', $formDescriptor, $context );
535 $form->setAction( $this->getFullTitle()->getFullURL( $this->getPreservedParams() ) );
536 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
537 $form->addHiddenField( 'authAction', $this->authAction );
538 $form->suppressDefaultSubmit( !$this->needsSubmitButton( $requests ) );
539
540 return $form;
541 }
542
543 /**
544 * Display the form.
545 * @param false|Status|StatusValue $status A form submit status, as in HTMLForm::trySubmit()
546 */
547 protected function displayForm( $status ) {
548 if ( $status instanceof StatusValue ) {
549 $status = Status::wrap( $status );
550 }
551 $form = $this->getAuthForm( $this->authRequests, $this->authAction );
552 $form->prepareForm()->displayForm( $status );
553 }
554
555 /**
556 * Returns true if the form built from the given AuthenticationRequests needs a submit button.
557 * Providers using redirect flow (e.g. Google login) need their own submit buttons; if using
558 * one of those custom buttons is the only way to proceed, there is no point in displaying the
559 * default button which won't do anything useful.
560 *
561 * @param AuthenticationRequest[] $requests An array of AuthenticationRequests from which the
562 * form will be built
563 * @return bool
564 */
565 protected function needsSubmitButton( array $requests ) {
566 $customSubmitButtonPresent = false;
567
568 // Secondary and preauth providers always need their data; they will not care what button
569 // is used, so they can be ignored. So can OPTIONAL buttons createdby primary providers;
570 // that's the point in being optional. Se we need to check whether all primary providers
571 // have their own buttons and whether there is at least one button present.
572 foreach ( $requests as $req ) {
573 if ( $req->required === AuthenticationRequest::PRIMARY_REQUIRED ) {
574 if ( $this->hasOwnSubmitButton( $req ) ) {
575 $customSubmitButtonPresent = true;
576 } else {
577 return true;
578 }
579 }
580 }
581 return !$customSubmitButtonPresent;
582 }
583
584 /**
585 * Checks whether the given AuthenticationRequest has its own submit button.
586 * @param AuthenticationRequest $req
587 * @return bool
588 */
589 protected function hasOwnSubmitButton( AuthenticationRequest $req ) {
590 foreach ( $req->getFieldInfo() as $field => $info ) {
591 if ( $info['type'] === 'button' ) {
592 return true;
593 }
594 }
595 return false;
596 }
597
598 /**
599 * Adds a sequential tabindex starting from 1 to all form elements. This way the user can
600 * use the tab key to traverse the form without having to step through all links and such.
601 * @param array &$formDescriptor
602 */
603 protected function addTabIndex( &$formDescriptor ) {
604 $i = 1;
605 foreach ( $formDescriptor as $field => &$definition ) {
606 $class = false;
607 if ( array_key_exists( 'class', $definition ) ) {
608 $class = $definition['class'];
609 } elseif ( array_key_exists( 'type', $definition ) ) {
610 $class = HTMLForm::$typeMappings[$definition['type']];
611 }
612 if ( $class !== 'HTMLInfoField' ) {
613 $definition['tabindex'] = $i;
614 $i++;
615 }
616 }
617 }
618
619 /**
620 * Returns the CSRF token.
621 * @return Token
622 */
623 protected function getToken() {
624 return $this->getRequest()->getSession()->getToken( 'AuthManagerSpecialPage:'
625 . $this->getName() );
626 }
627
628 /**
629 * Returns the name of the CSRF token (under which it should be found in the POST or GET data).
630 * @return string
631 */
632 protected function getTokenName() {
633 return 'wpAuthToken';
634 }
635
636 /**
637 * Turns a field info array into a form descriptor. Behavior can be modified by the
638 * AuthChangeFormFields hook.
639 * @param AuthenticationRequest[] $requests
640 * @param array $fieldInfo Field information, in the format used by
641 * AuthenticationRequest::getFieldInfo()
642 * @param string $action One of the AuthManager::ACTION_* constants
643 * @return array A form descriptor that can be passed to HTMLForm
644 */
645 protected function fieldInfoToFormDescriptor( array $requests, array $fieldInfo, $action ) {
646 $formDescriptor = [];
647 foreach ( $fieldInfo as $fieldName => $singleFieldInfo ) {
648 $formDescriptor[$fieldName] = self::mapSingleFieldInfo( $singleFieldInfo, $fieldName );
649 }
650
651 $requestSnapshot = serialize( $requests );
652 $this->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
653 \Hooks::run( 'AuthChangeFormFields', [ $requests, $fieldInfo, &$formDescriptor, $action ] );
654 if ( $requestSnapshot !== serialize( $requests ) ) {
655 LoggerFactory::getInstance( 'authentication' )->warning(
656 'AuthChangeFormFields hook changed auth requests' );
657 }
658
659 // Process the special 'weight' property, which is a way for AuthChangeFormFields hook
660 // subscribers (who only see one field at a time) to influence ordering.
661 self::sortFormDescriptorFields( $formDescriptor );
662
663 return $formDescriptor;
664 }
665
666 /**
667 * Maps an authentication field configuration for a single field (as returned by
668 * AuthenticationRequest::getFieldInfo()) to a HTMLForm field descriptor.
669 * @param array $singleFieldInfo
670 * @param string $fieldName
671 * @return array
672 */
673 protected static function mapSingleFieldInfo( $singleFieldInfo, $fieldName ) {
674 $type = self::mapFieldInfoTypeToFormDescriptorType( $singleFieldInfo['type'] );
675 $descriptor = [
676 'type' => $type,
677 // Do not prefix input name with 'wp'. This is important for the redirect flow.
678 'name' => $fieldName,
679 ];
680
681 if ( $type === 'submit' && isset( $singleFieldInfo['label'] ) ) {
682 $descriptor['default'] = wfMessage( $singleFieldInfo['label'] )->plain();
683 } elseif ( $type !== 'submit' ) {
684 $descriptor += array_filter( [
685 // help-message is omitted as it is usually not really useful for a web interface
686 'label-message' => self::getField( $singleFieldInfo, 'label' ),
687 ] );
688
689 if ( isset( $singleFieldInfo['options'] ) ) {
690 $descriptor['options'] = array_flip( array_map( function ( $message ) {
691 /** @var $message Message */
692 return $message->parse();
693 }, $singleFieldInfo['options'] ) );
694 }
695
696 if ( isset( $singleFieldInfo['value'] ) ) {
697 $descriptor['default'] = $singleFieldInfo['value'];
698 }
699
700 if ( empty( $singleFieldInfo['optional'] ) ) {
701 $descriptor['required'] = true;
702 }
703 }
704
705 return $descriptor;
706 }
707
708 /**
709 * Sort the fields of a form descriptor by their 'weight' property. (Fields with higher weight
710 * are shown closer to the bottom; weight defaults to 0. Negative weight is allowed.)
711 * Keep order if weights are equal.
712 * @param array &$formDescriptor
713 * @return array
714 */
715 protected static function sortFormDescriptorFields( array &$formDescriptor ) {
716 $i = 0;
717 foreach ( $formDescriptor as &$field ) {
718 $field['__index'] = $i++;
719 }
720 uasort( $formDescriptor, function ( $first, $second ) {
721 return self::getField( $first, 'weight', 0 ) - self::getField( $second, 'weight', 0 )
722 ?: $first['__index'] - $second['__index'];
723 } );
724 foreach ( $formDescriptor as &$field ) {
725 unset( $field['__index'] );
726 }
727 }
728
729 /**
730 * Get an array value, or a default if it does not exist.
731 * @param array $array
732 * @param string $fieldName
733 * @param mixed $default
734 * @return mixed
735 */
736 protected static function getField( array $array, $fieldName, $default = null ) {
737 if ( array_key_exists( $fieldName, $array ) ) {
738 return $array[$fieldName];
739 } else {
740 return $default;
741 }
742 }
743
744 /**
745 * Maps AuthenticationRequest::getFieldInfo() types to HTMLForm types
746 * @param string $type
747 * @return string
748 * @throws \LogicException
749 */
750 protected static function mapFieldInfoTypeToFormDescriptorType( $type ) {
751 $map = [
752 'string' => 'text',
753 'password' => 'password',
754 'select' => 'select',
755 'checkbox' => 'check',
756 'multiselect' => 'multiselect',
757 'button' => 'submit',
758 'hidden' => 'hidden',
759 'null' => 'info',
760 ];
761 if ( !array_key_exists( $type, $map ) ) {
762 throw new \LogicException( 'invalid field type: ' . $type );
763 }
764 return $map[$type];
765 }
766 }