3 * Copyright © 2016 Brad Jorsch <bjorsch@wikimedia.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Auth\AuthManager
;
25 use MediaWiki\Auth\AuthenticationRequest
;
26 use MediaWiki\Auth\AuthenticationResponse
;
27 use MediaWiki\Auth\CreateFromLoginAuthenticationRequest
;
28 use MediaWiki\Logger\LoggerFactory
;
31 * Helper class for AuthManager-using API modules. Intended for use via
36 class ApiAuthManagerHelper
{
38 /** @var ApiBase API module, for context and parameters */
41 /** @var string Message output format */
42 private $messageFormat;
45 * @param ApiBase $module API module, for context and parameters
47 public function __construct( ApiBase
$module ) {
48 $this->module
= $module;
50 $params = $module->extractRequestParams();
51 $this->messageFormat
= isset( $params['messageformat'] ) ?
$params['messageformat'] : 'wikitext';
55 * Static version of the constructor, for chaining
56 * @param ApiBase $module API module, for context and parameters
57 * @return ApiAuthManagerHelper
59 public static function newForModule( ApiBase
$module ) {
60 return new self( $module );
64 * Format a message for output
65 * @param array &$res Result array
66 * @param string $key Result key
67 * @param Message $message
69 private function formatMessage( array &$res, $key, Message
$message ) {
70 switch ( $this->messageFormat
) {
75 $res[$key] = $message->setContext( $this->module
)->text();
79 $res[$key] = $message->setContext( $this->module
)->parseAsBlock();
80 $res[$key] = Parser
::stripOuterParagraph( $res[$key] );
85 'key' => $message->getKey(),
86 'params' => $message->getParams(),
88 ApiResult
::setIndexedTagName( $res[$key]['params'], 'param' );
94 * Call $manager->securitySensitiveOperationStatus()
95 * @param string $operation Operation being checked.
96 * @throws UsageException
98 public function securitySensitiveOperation( $operation ) {
99 $status = AuthManager
::singleton()->securitySensitiveOperationStatus( $operation );
101 case AuthManager
::SEC_OK
:
104 case AuthManager
::SEC_REAUTH
:
105 $this->module
->dieUsage(
106 'You have not authenticated recently in this session, please reauthenticate.', 'reauthenticate'
109 case AuthManager
::SEC_FAIL
:
110 $this->module
->dieUsage(
111 'This action is not available as your identify cannot be verified.', 'cannotreauthenticate'
115 throw new UnexpectedValueException( "Unknown status \"$status\"" );
120 * Filter out authentication requests by class name
121 * @param AuthenticationRequest[] $reqs Requests to filter
122 * @param string[] $blacklist Class names to remove
123 * @return AuthenticationRequest[]
125 public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
127 $blacklist = array_flip( $blacklist );
128 $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
129 return !isset( $blacklist[get_class( $req )] );
136 * Fetch and load the AuthenticationRequests for an action
137 * @param string $action One of the AuthManager::ACTION_* constants
138 * @return AuthenticationRequest[]
140 public function loadAuthenticationRequests( $action ) {
141 $params = $this->module
->extractRequestParams();
143 $manager = AuthManager
::singleton();
144 $reqs = $manager->getAuthenticationRequests( $action, $this->module
->getUser() );
146 // Filter requests, if requested to do so
147 $wantedRequests = null;
148 if ( isset( $params['requests'] ) ) {
149 $wantedRequests = array_flip( $params['requests'] );
150 } elseif ( isset( $params['request'] ) ) {
151 $wantedRequests = [ $params['request'] => true ];
153 if ( $wantedRequests !== null ) {
154 $reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
155 return isset( $wantedRequests[$req->getUniqueId()] );
159 // Collect the fields for all the requests
162 foreach ( $reqs as $req ) {
163 $info = (array)$req->getFieldInfo();
165 $sensitive +
= array_filter( $info, function ( $opts ) {
166 return !empty( $opts['sensitive'] );
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 ) );
177 $this->module
->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
178 } catch ( UsageException
$ex ) {
179 // Make this a warning for now, upgrade to an error in 1.29.
180 $this->module
->setWarning( $ex->getMessage() );
181 $this->module
->logFeatureUsage( $this->module
->getModuleName() . '-params-in-query-string' );
185 return AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
189 * Format an AuthenticationResponse for return
190 * @param AuthenticationResponse $res
193 public function formatAuthenticationResponse( AuthenticationResponse
$res ) {
195 'status' => $res->status
,
198 if ( $res->status
=== AuthenticationResponse
::PASS
&& $res->username
!== null ) {
199 $ret['username'] = $res->username
;
202 if ( $res->status
=== AuthenticationResponse
::REDIRECT
) {
203 $ret['redirecttarget'] = $res->redirectTarget
;
204 if ( $res->redirectApiData
!== null ) {
205 $ret['redirectdata'] = $res->redirectApiData
;
209 if ( $res->status
=== AuthenticationResponse
::REDIRECT ||
210 $res->status
=== AuthenticationResponse
::UI ||
211 $res->status
=== AuthenticationResponse
::RESTART
213 $ret +
= $this->formatRequests( $res->neededRequests
);
216 if ( $res->status
=== AuthenticationResponse
::FAIL ||
217 $res->status
=== AuthenticationResponse
::UI ||
218 $res->status
=== AuthenticationResponse
::RESTART
220 $this->formatMessage( $ret, 'message', $res->message
);
223 if ( $res->status
=== AuthenticationResponse
::FAIL ||
224 $res->status
=== AuthenticationResponse
::RESTART
226 $this->module
->getRequest()->getSession()->set(
227 'ApiAuthManagerHelper::createRequest',
230 $ret['canpreservestate'] = $res->createRequest
!== null;
232 $this->module
->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
239 * Logs successful or failed authentication.
240 * @param string|AuthenticationResponse $result Response or error message
241 * @param string $event Event type (e.g. 'accountcreation')
243 public function logAuthenticationResult( $event, $result ) {
244 if ( is_string( $result ) ) {
245 $status = Status
::newFatal( $result );
246 } elseif ( $result->status
=== AuthenticationResponse
::PASS
) {
247 $status = Status
::newGood();
248 } elseif ( $result->status
=== AuthenticationResponse
::FAIL
) {
249 $status = Status
::newFatal( $result->message
);
254 $module = $this->module
->getModuleName();
255 LoggerFactory
::getInstance( 'authevents' )->info( "$module API attempt", [
263 * Fetch the preserved CreateFromLoginAuthenticationRequest, if any
264 * @return CreateFromLoginAuthenticationRequest|null
266 public function getPreservedRequest() {
267 $ret = $this->module
->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
268 return $ret instanceof CreateFromLoginAuthenticationRequest ?
$ret : null;
272 * Format an array of AuthenticationRequests for return
273 * @param AuthenticationRequest[] $reqs
274 * @return array Will have a 'requests' key, and also 'fields' if $module's
275 * params include 'mergerequestfields'.
277 public function formatRequests( array $reqs ) {
278 $params = $this->module
->extractRequestParams();
279 $mergeFields = !empty( $params['mergerequestfields'] );
281 $ret = [ 'requests' => [] ];
282 foreach ( $reqs as $req ) {
283 $describe = $req->describeCredentials();
285 'id' => $req->getUniqueId(),
286 'metadata' => $req->getMetadata() +
[ ApiResult
::META_TYPE
=> 'assoc' ],
288 switch ( $req->required
) {
289 case AuthenticationRequest
::OPTIONAL
:
290 $reqInfo['required'] = 'optional';
292 case AuthenticationRequest
::REQUIRED
:
293 $reqInfo['required'] = 'required';
295 case AuthenticationRequest
::PRIMARY_REQUIRED
:
296 $reqInfo['required'] = 'primary-required';
299 $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
300 $this->formatMessage( $reqInfo, 'account', $describe['account'] );
301 if ( !$mergeFields ) {
302 $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
304 $ret['requests'][] = $reqInfo;
307 if ( $mergeFields ) {
308 $fields = AuthenticationRequest
::mergeFieldInfo( $reqs );
309 $ret['fields'] = $this->formatFields( $fields );
316 * Clean up a field array for output
317 * @param ApiBase $module For context and parameters 'mergerequestfields'
318 * and 'messageformat'
319 * @param array $fields
322 private function formatFields( array $fields ) {
328 $module = $this->module
;
331 foreach ( $fields as $name => $field ) {
332 $ret = array_intersect_key( $field, $copy );
334 if ( isset( $field['options'] ) ) {
335 $ret['options'] = array_map( function ( $msg ) use ( $module ) {
336 return $msg->setContext( $module )->plain();
337 }, $field['options'] );
338 ApiResult
::setArrayType( $ret['options'], 'assoc' );
340 $this->formatMessage( $ret, 'label', $field['label'] );
341 $this->formatMessage( $ret, 'help', $field['help'] );
342 $ret['optional'] = !empty( $field['optional'] );
343 $ret['sensitive'] = !empty( $field['sensitive'] );
345 $retFields[$name] = $ret;
348 ApiResult
::setArrayType( $retFields, 'assoc' );
354 * Fetch the standard parameters this helper recognizes
355 * @param string $action AuthManager action
356 * @param string $param... Parameters to use
359 public static function getStandardParams( $action, $param /* ... */ ) {
362 ApiBase
::PARAM_TYPE
=> 'string',
363 ApiBase
::PARAM_ISMULTI
=> true,
364 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-requests', $action ],
367 ApiBase
::PARAM_TYPE
=> 'string',
368 ApiBase
::PARAM_REQUIRED
=> true,
369 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-request', $action ],
372 ApiBase
::PARAM_DFLT
=> 'wikitext',
373 ApiBase
::PARAM_TYPE
=> [ 'html', 'wikitext', 'raw', 'none' ],
374 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-messageformat',
376 'mergerequestfields' => [
377 ApiBase
::PARAM_DFLT
=> false,
378 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-mergerequestfields',
381 ApiBase
::PARAM_DFLT
=> false,
382 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-preservestate',
385 ApiBase
::PARAM_TYPE
=> 'string',
386 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-returnurl',
389 ApiBase
::PARAM_DFLT
=> false,
390 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-continue',
395 $wantedParams = func_get_args();
396 array_shift( $wantedParams );
397 foreach ( $wantedParams as $name ) {
398 if ( isset( $params[$name] ) ) {
399 $ret[$name] = $params[$name];