MediaWiki  master
ApiAuthManagerHelper.php
Go to the documentation of this file.
1 <?php
30 
38 
40  private $module;
41 
43  private $messageFormat;
44 
46  private $authManager;
47 
52  public function __construct( ApiBase $module, AuthManager $authManager = null ) {
53  $this->module = $module;
54 
55  $params = $module->extractRequestParams();
56  $this->messageFormat = $params['messageformat'] ?? 'wikitext';
57  $this->authManager = $authManager ?: MediaWikiServices::getInstance()->getAuthManager();
58  }
59 
66  public static function newForModule( ApiBase $module, AuthManager $authManager = null ) {
67  return new self( $module, $authManager );
68  }
69 
76  private function formatMessage( array &$res, $key, Message $message ) {
77  switch ( $this->messageFormat ) {
78  case 'none':
79  break;
80 
81  case 'wikitext':
82  $res[$key] = $message->setContext( $this->module )->text();
83  break;
84 
85  case 'html':
86  $res[$key] = $message->setContext( $this->module )->parseAsBlock();
87  $res[$key] = Parser::stripOuterParagraph( $res[$key] );
88  break;
89 
90  case 'raw':
91  $params = $message->getParams();
92  $res[$key] = [
93  'key' => $message->getKey(),
94  'params' => $params,
95  ];
96  ApiResult::setIndexedTagName( $params, 'param' );
97  break;
98  }
99  }
100 
106  public function securitySensitiveOperation( $operation ) {
107  $status = $this->authManager->securitySensitiveOperationStatus( $operation );
108  switch ( $status ) {
109  case AuthManager::SEC_OK:
110  return;
111 
112  case AuthManager::SEC_REAUTH:
113  $this->module->dieWithError( 'apierror-reauthenticate' );
114 
115  case AuthManager::SEC_FAIL:
116  $this->module->dieWithError( 'apierror-cannotreauthenticate' );
117 
118  default:
119  throw new UnexpectedValueException( "Unknown status \"$status\"" );
120  }
121  }
122 
129  public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
130  if ( $blacklist ) {
131  $blacklist = array_flip( $blacklist );
132  $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
133  return !isset( $blacklist[get_class( $req )] );
134  } );
135  }
136  return $reqs;
137  }
138 
144  public function loadAuthenticationRequests( $action ) {
145  $params = $this->module->extractRequestParams();
146 
147  $reqs = $this->authManager->getAuthenticationRequests( $action, $this->module->getUser() );
148 
149  // Filter requests, if requested to do so
150  $wantedRequests = null;
151  if ( isset( $params['requests'] ) ) {
152  $wantedRequests = array_flip( $params['requests'] );
153  } elseif ( isset( $params['request'] ) ) {
154  $wantedRequests = [ $params['request'] => true ];
155  }
156  if ( $wantedRequests !== null ) {
157  $reqs = array_filter(
158  $reqs,
159  function ( AuthenticationRequest $req ) use ( $wantedRequests ) {
160  return isset( $wantedRequests[$req->getUniqueId()] );
161  }
162  );
163  }
164 
165  // Collect the fields for all the requests
166  $fields = [];
167  $sensitive = [];
168  foreach ( $reqs as $req ) {
169  $info = (array)$req->getFieldInfo();
170  $fields += $info;
171  $sensitive += array_filter( $info, function ( $opts ) {
172  return !empty( $opts['sensitive'] );
173  } );
174  }
175 
176  // Extract the request data for the fields and mark those request
177  // parameters as used
178  $data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
179  $this->module->getMain()->markParamsUsed( array_keys( $data ) );
180 
181  if ( $sensitive ) {
182  $this->module->getMain()->markParamsSensitive( array_keys( $sensitive ) );
183  $this->module->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
184  }
185 
186  return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
187  }
188 
195  $ret = [
196  'status' => $res->status,
197  ];
198 
199  if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
200  $ret['username'] = $res->username;
201  }
202 
203  if ( $res->status === AuthenticationResponse::REDIRECT ) {
204  $ret['redirecttarget'] = $res->redirectTarget;
205  if ( $res->redirectApiData !== null ) {
206  $ret['redirectdata'] = $res->redirectApiData;
207  }
208  }
209 
210  if ( $res->status === AuthenticationResponse::REDIRECT ||
211  $res->status === AuthenticationResponse::UI ||
212  $res->status === AuthenticationResponse::RESTART
213  ) {
214  $ret += $this->formatRequests( $res->neededRequests );
215  }
216 
217  if ( $res->status === AuthenticationResponse::FAIL ||
218  $res->status === AuthenticationResponse::UI ||
219  $res->status === AuthenticationResponse::RESTART
220  ) {
221  $this->formatMessage( $ret, 'message', $res->message );
222  $ret['messagecode'] = ApiMessage::create( $res->message )->getApiCode();
223  }
224 
225  if ( $res->status === AuthenticationResponse::FAIL ||
226  $res->status === AuthenticationResponse::RESTART
227  ) {
228  $this->module->getRequest()->getSession()->set(
229  'ApiAuthManagerHelper::createRequest',
230  $res->createRequest
231  );
232  $ret['canpreservestate'] = $res->createRequest !== null;
233  } else {
234  $this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
235  }
236 
237  return $ret;
238  }
239 
245  public function logAuthenticationResult( $event, $result ) {
246  if ( is_string( $result ) ) {
247  $status = Status::newFatal( $result );
248  } elseif ( $result->status === AuthenticationResponse::PASS ) {
249  $status = Status::newGood();
250  } elseif ( $result->status === AuthenticationResponse::FAIL ) {
251  $status = Status::newFatal( $result->message );
252  } else {
253  return;
254  }
255 
256  $module = $this->module->getModuleName();
257  LoggerFactory::getInstance( 'authevents' )->info( "$module API attempt", [
258  'event' => $event,
259  'status' => $status,
260  'module' => $module,
261  ] );
262  }
263 
268  public function getPreservedRequest() {
269  $ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
270  return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
271  }
272 
279  public function formatRequests( array $reqs ) {
280  $params = $this->module->extractRequestParams();
281  $mergeFields = !empty( $params['mergerequestfields'] );
282 
283  $ret = [ 'requests' => [] ];
284  foreach ( $reqs as $req ) {
285  $describe = $req->describeCredentials();
286  $reqInfo = [
287  'id' => $req->getUniqueId(),
288  'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
289  ];
290  switch ( $req->required ) {
291  case AuthenticationRequest::OPTIONAL:
292  $reqInfo['required'] = 'optional';
293  break;
294  case AuthenticationRequest::REQUIRED:
295  $reqInfo['required'] = 'required';
296  break;
297  case AuthenticationRequest::PRIMARY_REQUIRED:
298  $reqInfo['required'] = 'primary-required';
299  break;
300  }
301  $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
302  $this->formatMessage( $reqInfo, 'account', $describe['account'] );
303  if ( !$mergeFields ) {
304  $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
305  }
306  $ret['requests'][] = $reqInfo;
307  }
308 
309  if ( $mergeFields ) {
310  $fields = AuthenticationRequest::mergeFieldInfo( $reqs );
311  $ret['fields'] = $this->formatFields( $fields );
312  }
313 
314  return $ret;
315  }
316 
325  private function formatFields( array $fields ) {
326  static $copy = [
327  'type' => true,
328  'value' => true,
329  ];
330 
332  $retFields = [];
333 
334  foreach ( $fields as $name => $field ) {
335  $ret = array_intersect_key( $field, $copy );
336 
337  if ( isset( $field['options'] ) ) {
338  $ret['options'] = array_map( function ( $msg ) use ( $module ) {
339  return $msg->setContext( $module )->plain();
340  }, $field['options'] );
341  ApiResult::setArrayType( $ret['options'], 'assoc' );
342  }
343  $this->formatMessage( $ret, 'label', $field['label'] );
344  $this->formatMessage( $ret, 'help', $field['help'] );
345  $ret['optional'] = !empty( $field['optional'] );
346  $ret['sensitive'] = !empty( $field['sensitive'] );
347 
348  $retFields[$name] = $ret;
349  }
350 
351  ApiResult::setArrayType( $retFields, 'assoc' );
352 
353  return $retFields;
354  }
355 
362  public static function getStandardParams( $action, ...$wantedParams ) {
363  $params = [
364  'requests' => [
365  ApiBase::PARAM_TYPE => 'string',
366  ApiBase::PARAM_ISMULTI => true,
367  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
368  ],
369  'request' => [
370  ApiBase::PARAM_TYPE => 'string',
371  ApiBase::PARAM_REQUIRED => true,
372  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
373  ],
374  'messageformat' => [
375  ApiBase::PARAM_DFLT => 'wikitext',
376  ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
377  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
378  ],
379  'mergerequestfields' => [
380  ApiBase::PARAM_DFLT => false,
381  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
382  ],
383  'preservestate' => [
384  ApiBase::PARAM_DFLT => false,
385  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
386  ],
387  'returnurl' => [
388  ApiBase::PARAM_TYPE => 'string',
389  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
390  ],
391  'continue' => [
392  ApiBase::PARAM_DFLT => false,
393  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
394  ],
395  ];
396 
397  $ret = [];
398  foreach ( $wantedParams as $name ) {
399  if ( isset( $params[$name] ) ) {
400  $ret[$name] = $params[$name];
401  }
402  }
403  return $ret;
404  }
405 }
ApiAuthManagerHelper\newForModule
static newForModule(ApiBase $module, AuthManager $authManager=null)
Static version of the constructor, for chaining.
Definition: ApiAuthManagerHelper.php:66
Message\getParams
getParams()
Returns the message parameters.
Definition: Message.php:378
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:77
ApiAuthManagerHelper\formatAuthenticationResponse
formatAuthenticationResponse(AuthenticationResponse $res)
Format an AuthenticationResponse for return.
Definition: ApiAuthManagerHelper.php:194
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:154
ApiResult\META_TYPE
const META_TYPE
Key for the 'type' metadata item.
Definition: ApiResult.php:110
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:107
true
return true
Definition: router.php:90
ApiAuthManagerHelper\securitySensitiveOperation
securitySensitiveOperation( $operation)
Call $manager->securitySensitiveOperationStatus()
Definition: ApiAuthManagerHelper.php:106
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:71
ApiAuthManagerHelper\getStandardParams
static getStandardParams( $action,... $wantedParams)
Fetch the standard parameters this helper recognizes.
Definition: ApiAuthManagerHelper.php:362
$res
$res
Definition: testCompression.php:57
ApiAuthManagerHelper\formatRequests
formatRequests(array $reqs)
Format an array of AuthenticationRequests for return.
Definition: ApiAuthManagerHelper.php:279
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
Message\getKey
getKey()
Returns the message key.
Definition: Message.php:367
ApiAuthManagerHelper\loadAuthenticationRequests
loadAuthenticationRequests( $action)
Fetch and load the AuthenticationRequests for an action.
Definition: ApiAuthManagerHelper.php:144
ApiResult\setArrayType
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:716
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
MediaWiki\Auth\AuthenticationResponse
This is a value object to hold authentication response data.
Definition: AuthenticationResponse.php:37
MediaWiki\Auth\CreateFromLoginAuthenticationRequest
This transfers state between the login and account creation flows.
Definition: CreateFromLoginAuthenticationRequest.php:35
ApiAuthManagerHelper
Helper class for AuthManager-using API modules.
Definition: ApiAuthManagerHelper.php:37
MediaWiki\Auth\AuthenticationRequest\getUniqueId
getUniqueId()
Supply a unique key for deduplication.
Definition: AuthenticationRequest.php:90
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:717
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:42
ApiAuthManagerHelper\$messageFormat
string $messageFormat
Message output format.
Definition: ApiAuthManagerHelper.php:43
ApiAuthManagerHelper\__construct
__construct(ApiBase $module, AuthManager $authManager=null)
Definition: ApiAuthManagerHelper.php:52
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
ApiAuthManagerHelper\logAuthenticationResult
logAuthenticationResult( $event, $result)
Logs successful or failed authentication.
Definition: ApiAuthManagerHelper.php:245
ApiAuthManagerHelper\blacklistAuthenticationRequests
static blacklistAuthenticationRequests(array $reqs, array $blacklist)
Filter out authentication requests by class name.
Definition: ApiAuthManagerHelper.php:129
ApiAuthManagerHelper\$module
ApiBase $module
API module, for context and parameters.
Definition: ApiAuthManagerHelper.php:40
Message\setContext
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition: Message.php:722
ApiAuthManagerHelper\formatMessage
formatMessage(array &$res, $key, Message $message)
Format a message for output.
Definition: ApiAuthManagerHelper.php:76
MediaWiki\Auth\AuthManager
This serves as the entry point to the authentication system.
Definition: AuthManager.php:88
Parser\stripOuterParagraph
static stripOuterParagraph( $html)
Strip outer.
Definition: Parser.php:6263
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:69
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:444
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:161
ApiAuthManagerHelper\getPreservedRequest
getPreservedRequest()
Fetch the preserved CreateFromLoginAuthenticationRequest, if any.
Definition: ApiAuthManagerHelper.php:268
ApiAuthManagerHelper\formatFields
formatFields(array $fields)
Clean up a field array for output.
Definition: ApiAuthManagerHelper.php:325
ApiAuthManagerHelper\$authManager
AuthManager $authManager
Definition: ApiAuthManagerHelper.php:46
MediaWiki\Auth\AuthenticationRequest
This is a value object for authentication requests.
Definition: AuthenticationRequest.php:38