MediaWiki  master
ApiAuthManagerHelper.php
Go to the documentation of this file.
1 <?php
29 
37 
39  private $module;
40 
42  private $messageFormat;
43 
47  public function __construct( ApiBase $module ) {
48  $this->module = $module;
49 
50  $params = $module->extractRequestParams();
51  $this->messageFormat = $params['messageformat'] ?? 'wikitext';
52  }
53 
59  public static function newForModule( ApiBase $module ) {
60  return new self( $module );
61  }
62 
69  private function formatMessage( array &$res, $key, Message $message ) {
70  switch ( $this->messageFormat ) {
71  case 'none':
72  break;
73 
74  case 'wikitext':
75  $res[$key] = $message->setContext( $this->module )->text();
76  break;
77 
78  case 'html':
79  $res[$key] = $message->setContext( $this->module )->parseAsBlock();
80  $res[$key] = Parser::stripOuterParagraph( $res[$key] );
81  break;
82 
83  case 'raw':
84  $params = $message->getParams();
85  $res[$key] = [
86  'key' => $message->getKey(),
87  'params' => $params,
88  ];
89  ApiResult::setIndexedTagName( $params, 'param' );
90  break;
91  }
92  }
93 
99  public function securitySensitiveOperation( $operation ) {
100  $status = AuthManager::singleton()->securitySensitiveOperationStatus( $operation );
101  switch ( $status ) {
102  case AuthManager::SEC_OK:
103  return;
104 
105  case AuthManager::SEC_REAUTH:
106  $this->module->dieWithError( 'apierror-reauthenticate' );
107 
108  case AuthManager::SEC_FAIL:
109  $this->module->dieWithError( 'apierror-cannotreauthenticate' );
110 
111  default:
112  throw new UnexpectedValueException( "Unknown status \"$status\"" );
113  }
114  }
115 
122  public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
123  if ( $blacklist ) {
124  $blacklist = array_flip( $blacklist );
125  $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
126  return !isset( $blacklist[get_class( $req )] );
127  } );
128  }
129  return $reqs;
130  }
131 
137  public function loadAuthenticationRequests( $action ) {
138  $params = $this->module->extractRequestParams();
139 
140  $manager = AuthManager::singleton();
141  $reqs = $manager->getAuthenticationRequests( $action, $this->module->getUser() );
142 
143  // Filter requests, if requested to do so
144  $wantedRequests = null;
145  if ( isset( $params['requests'] ) ) {
146  $wantedRequests = array_flip( $params['requests'] );
147  } elseif ( isset( $params['request'] ) ) {
148  $wantedRequests = [ $params['request'] => true ];
149  }
150  if ( $wantedRequests !== null ) {
151  $reqs = array_filter(
152  $reqs,
153  function ( AuthenticationRequest $req ) use ( $wantedRequests ) {
154  return isset( $wantedRequests[$req->getUniqueId()] );
155  }
156  );
157  }
158 
159  // Collect the fields for all the requests
160  $fields = [];
161  $sensitive = [];
162  foreach ( $reqs as $req ) {
163  $info = (array)$req->getFieldInfo();
164  $fields += $info;
165  $sensitive += array_filter( $info, function ( $opts ) {
166  return !empty( $opts['sensitive'] );
167  } );
168  }
169 
170  // Extract the request data for the fields and mark those request
171  // parameters as used
172  $data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
173  $this->module->getMain()->markParamsUsed( array_keys( $data ) );
174 
175  if ( $sensitive ) {
176  $this->module->getMain()->markParamsSensitive( array_keys( $sensitive ) );
177  $this->module->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
178  }
179 
180  return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
181  }
182 
189  $ret = [
190  'status' => $res->status,
191  ];
192 
193  if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
194  $ret['username'] = $res->username;
195  }
196 
197  if ( $res->status === AuthenticationResponse::REDIRECT ) {
198  $ret['redirecttarget'] = $res->redirectTarget;
199  if ( $res->redirectApiData !== null ) {
200  $ret['redirectdata'] = $res->redirectApiData;
201  }
202  }
203 
204  if ( $res->status === AuthenticationResponse::REDIRECT ||
205  $res->status === AuthenticationResponse::UI ||
206  $res->status === AuthenticationResponse::RESTART
207  ) {
208  $ret += $this->formatRequests( $res->neededRequests );
209  }
210 
211  if ( $res->status === AuthenticationResponse::FAIL ||
212  $res->status === AuthenticationResponse::UI ||
213  $res->status === AuthenticationResponse::RESTART
214  ) {
215  $this->formatMessage( $ret, 'message', $res->message );
216  $ret['messagecode'] = ApiMessage::create( $res->message )->getApiCode();
217  }
218 
219  if ( $res->status === AuthenticationResponse::FAIL ||
220  $res->status === AuthenticationResponse::RESTART
221  ) {
222  $this->module->getRequest()->getSession()->set(
223  'ApiAuthManagerHelper::createRequest',
224  $res->createRequest
225  );
226  $ret['canpreservestate'] = $res->createRequest !== null;
227  } else {
228  $this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
229  }
230 
231  return $ret;
232  }
233 
239  public function logAuthenticationResult( $event, $result ) {
240  if ( is_string( $result ) ) {
241  $status = Status::newFatal( $result );
242  } elseif ( $result->status === AuthenticationResponse::PASS ) {
243  $status = Status::newGood();
244  } elseif ( $result->status === AuthenticationResponse::FAIL ) {
245  $status = Status::newFatal( $result->message );
246  } else {
247  return;
248  }
249 
250  $module = $this->module->getModuleName();
251  LoggerFactory::getInstance( 'authevents' )->info( "$module API attempt", [
252  'event' => $event,
253  'status' => $status,
254  'module' => $module,
255  ] );
256  }
257 
262  public function getPreservedRequest() {
263  $ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
264  return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
265  }
266 
273  public function formatRequests( array $reqs ) {
274  $params = $this->module->extractRequestParams();
275  $mergeFields = !empty( $params['mergerequestfields'] );
276 
277  $ret = [ 'requests' => [] ];
278  foreach ( $reqs as $req ) {
279  $describe = $req->describeCredentials();
280  $reqInfo = [
281  'id' => $req->getUniqueId(),
282  'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
283  ];
284  switch ( $req->required ) {
285  case AuthenticationRequest::OPTIONAL:
286  $reqInfo['required'] = 'optional';
287  break;
288  case AuthenticationRequest::REQUIRED:
289  $reqInfo['required'] = 'required';
290  break;
291  case AuthenticationRequest::PRIMARY_REQUIRED:
292  $reqInfo['required'] = 'primary-required';
293  break;
294  }
295  $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
296  $this->formatMessage( $reqInfo, 'account', $describe['account'] );
297  if ( !$mergeFields ) {
298  $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
299  }
300  $ret['requests'][] = $reqInfo;
301  }
302 
303  if ( $mergeFields ) {
304  $fields = AuthenticationRequest::mergeFieldInfo( $reqs );
305  $ret['fields'] = $this->formatFields( $fields );
306  }
307 
308  return $ret;
309  }
310 
319  private function formatFields( array $fields ) {
320  static $copy = [
321  'type' => true,
322  'value' => true,
323  ];
324 
326  $retFields = [];
327 
328  foreach ( $fields as $name => $field ) {
329  $ret = array_intersect_key( $field, $copy );
330 
331  if ( isset( $field['options'] ) ) {
332  $ret['options'] = array_map( function ( $msg ) use ( $module ) {
333  return $msg->setContext( $module )->plain();
334  }, $field['options'] );
335  ApiResult::setArrayType( $ret['options'], 'assoc' );
336  }
337  $this->formatMessage( $ret, 'label', $field['label'] );
338  $this->formatMessage( $ret, 'help', $field['help'] );
339  $ret['optional'] = !empty( $field['optional'] );
340  $ret['sensitive'] = !empty( $field['sensitive'] );
341 
342  $retFields[$name] = $ret;
343  }
344 
345  ApiResult::setArrayType( $retFields, 'assoc' );
346 
347  return $retFields;
348  }
349 
356  public static function getStandardParams( $action, ...$wantedParams ) {
357  $params = [
358  'requests' => [
359  ApiBase::PARAM_TYPE => 'string',
360  ApiBase::PARAM_ISMULTI => true,
361  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
362  ],
363  'request' => [
364  ApiBase::PARAM_TYPE => 'string',
365  ApiBase::PARAM_REQUIRED => true,
366  ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
367  ],
368  'messageformat' => [
369  ApiBase::PARAM_DFLT => 'wikitext',
370  ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
371  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
372  ],
373  'mergerequestfields' => [
374  ApiBase::PARAM_DFLT => false,
375  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
376  ],
377  'preservestate' => [
378  ApiBase::PARAM_DFLT => false,
379  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
380  ],
381  'returnurl' => [
382  ApiBase::PARAM_TYPE => 'string',
383  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
384  ],
385  'continue' => [
386  ApiBase::PARAM_DFLT => false,
387  ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
388  ],
389  ];
390 
391  $ret = [];
392  foreach ( $wantedParams as $name ) {
393  if ( isset( $params[$name] ) ) {
394  $ret[$name] = $params[$name];
395  }
396  }
397  return $ret;
398  }
399 }
Message\getParams
getParams()
Returns the message parameters.
Definition: Message.php:376
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:74
ApiAuthManagerHelper\formatAuthenticationResponse
formatAuthenticationResponse(AuthenticationResponse $res)
Format an AuthenticationResponse for return.
Definition: ApiAuthManagerHelper.php:188
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:104
true
return true
Definition: router.php:90
ApiAuthManagerHelper\securitySensitiveOperation
securitySensitiveOperation( $operation)
Call $manager->securitySensitiveOperationStatus()
Definition: ApiAuthManagerHelper.php:99
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:68
ApiAuthManagerHelper\getStandardParams
static getStandardParams( $action,... $wantedParams)
Fetch the standard parameters this helper recognizes.
Definition: ApiAuthManagerHelper.php:356
$res
$res
Definition: testCompression.php:57
ApiAuthManagerHelper\formatRequests
formatRequests(array $reqs)
Format an array of AuthenticationRequests for return.
Definition: ApiAuthManagerHelper.php:273
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:50
Message\getKey
getKey()
Returns the message key.
Definition: Message.php:365
ApiAuthManagerHelper\loadAuthenticationRequests
loadAuthenticationRequests( $action)
Fetch and load the AuthenticationRequests for an action.
Definition: ApiAuthManagerHelper.php:137
ApiAuthManagerHelper\__construct
__construct(ApiBase $module)
Definition: ApiAuthManagerHelper.php:47
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:34
ApiAuthManagerHelper
Helper class for AuthManager-using API modules.
Definition: ApiAuthManagerHelper.php:36
MediaWiki\Auth\AuthenticationRequest\getUniqueId
getUniqueId()
Supply a unique key for deduplication.
Definition: AuthenticationRequest.php:88
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:695
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
ApiAuthManagerHelper\$messageFormat
string $messageFormat
Message output format.
Definition: ApiAuthManagerHelper.php:42
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:81
ApiAuthManagerHelper\logAuthenticationResult
logAuthenticationResult( $event, $result)
Logs successful or failed authentication.
Definition: ApiAuthManagerHelper.php:239
ApiAuthManagerHelper\blacklistAuthenticationRequests
static blacklistAuthenticationRequests(array $reqs, array $blacklist)
Filter out authentication requests by class name.
Definition: ApiAuthManagerHelper.php:122
ApiAuthManagerHelper\$module
ApiBase $module
API module, for context and parameters.
Definition: ApiAuthManagerHelper.php:39
Message\setContext
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition: Message.php:720
ApiAuthManagerHelper\formatMessage
formatMessage(array &$res, $key, Message $message)
Format a message for output.
Definition: ApiAuthManagerHelper.php:69
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:6218
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:66
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:426
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:67
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:160
ApiAuthManagerHelper\newForModule
static newForModule(ApiBase $module)
Static version of the constructor, for chaining.
Definition: ApiAuthManagerHelper.php:59
ApiAuthManagerHelper\getPreservedRequest
getPreservedRequest()
Fetch the preserved CreateFromLoginAuthenticationRequest, if any.
Definition: ApiAuthManagerHelper.php:262
ApiAuthManagerHelper\formatFields
formatFields(array $fields)
Clean up a field array for output.
Definition: ApiAuthManagerHelper.php:319
MediaWiki\Auth\AuthenticationRequest
This is a value object for authentication requests.
Definition: AuthenticationRequest.php:37