MediaWiki fundraising/REL1_35
ApiAuthManagerHelper.php
Go to the documentation of this file.
1<?php
30
38
40 private $module;
41
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' => strval( $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}
Helper class for AuthManager-using API modules.
static newForModule(ApiBase $module, AuthManager $authManager=null)
Static version of the constructor, for chaining.
logAuthenticationResult( $event, $result)
Logs successful or failed authentication.
getPreservedRequest()
Fetch the preserved CreateFromLoginAuthenticationRequest, if any.
static getStandardParams( $action,... $wantedParams)
Fetch the standard parameters this helper recognizes.
formatAuthenticationResponse(AuthenticationResponse $res)
Format an AuthenticationResponse for return.
__construct(ApiBase $module, AuthManager $authManager=null)
ApiBase $module
API module, for context and parameters.
formatRequests(array $reqs)
Format an array of AuthenticationRequests for return.
formatFields(array $fields)
Clean up a field array for output.
formatMessage(array &$res, $key, Message $message)
Format a message for output.
securitySensitiveOperation( $operation)
Call $manager->securitySensitiveOperationStatus()
static blacklistAuthenticationRequests(array $reqs, array $blacklist)
Filter out authentication requests by class name.
loadAuthenticationRequests( $action)
Fetch and load the AuthenticationRequests for an action.
string $messageFormat
Message output format.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:52
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:772
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:499
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
getUniqueId()
Supply a unique key for deduplication.
This is a value object to hold authentication response data.
This transfers state between the login and account creation flows.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:161
getParams()
Returns the message parameters.
Definition Message.php:394
getKey()
Returns the message key.
Definition Message.php:383
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition Message.php:738
return true
Definition router.php:92