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 ApiUsageException
98 public function securitySensitiveOperation( $operation ) {
99 $status = AuthManager
::singleton()->securitySensitiveOperationStatus( $operation );
101 case AuthManager
::SEC_OK
:
104 case AuthManager
::SEC_REAUTH
:
105 $this->module
->dieWithError( 'apierror-reauthenticate' );
107 case AuthManager
::SEC_FAIL
:
108 $this->module
->dieWithError( 'apierror-cannotreauthenticate' );
111 throw new UnexpectedValueException( "Unknown status \"$status\"" );
116 * Filter out authentication requests by class name
117 * @param AuthenticationRequest[] $reqs Requests to filter
118 * @param string[] $blacklist Class names to remove
119 * @return AuthenticationRequest[]
121 public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
123 $blacklist = array_flip( $blacklist );
124 $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
125 return !isset( $blacklist[get_class( $req )] );
132 * Fetch and load the AuthenticationRequests for an action
133 * @param string $action One of the AuthManager::ACTION_* constants
134 * @return AuthenticationRequest[]
136 public function loadAuthenticationRequests( $action ) {
137 $params = $this->module
->extractRequestParams();
139 $manager = AuthManager
::singleton();
140 $reqs = $manager->getAuthenticationRequests( $action, $this->module
->getUser() );
142 // Filter requests, if requested to do so
143 $wantedRequests = null;
144 if ( isset( $params['requests'] ) ) {
145 $wantedRequests = array_flip( $params['requests'] );
146 } elseif ( isset( $params['request'] ) ) {
147 $wantedRequests = [ $params['request'] => true ];
149 if ( $wantedRequests !== null ) {
150 $reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
151 return isset( $wantedRequests[$req->getUniqueId()] );
155 // Collect the fields for all the requests
158 foreach ( $reqs as $req ) {
159 $info = (array)$req->getFieldInfo();
161 $sensitive +
= array_filter( $info, function ( $opts ) {
162 return !empty( $opts['sensitive'] );
166 // Extract the request data for the fields and mark those request
167 // parameters as used
168 $data = array_intersect_key( $this->module
->getRequest()->getValues(), $fields );
169 $this->module
->getMain()->markParamsUsed( array_keys( $data ) );
172 $this->module
->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
175 return AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
179 * Format an AuthenticationResponse for return
180 * @param AuthenticationResponse $res
183 public function formatAuthenticationResponse( AuthenticationResponse
$res ) {
185 'status' => $res->status
,
188 if ( $res->status
=== AuthenticationResponse
::PASS
&& $res->username
!== null ) {
189 $ret['username'] = $res->username
;
192 if ( $res->status
=== AuthenticationResponse
::REDIRECT
) {
193 $ret['redirecttarget'] = $res->redirectTarget
;
194 if ( $res->redirectApiData
!== null ) {
195 $ret['redirectdata'] = $res->redirectApiData
;
199 if ( $res->status
=== AuthenticationResponse
::REDIRECT ||
200 $res->status
=== AuthenticationResponse
::UI ||
201 $res->status
=== AuthenticationResponse
::RESTART
203 $ret +
= $this->formatRequests( $res->neededRequests
);
206 if ( $res->status
=== AuthenticationResponse
::FAIL ||
207 $res->status
=== AuthenticationResponse
::UI ||
208 $res->status
=== AuthenticationResponse
::RESTART
210 $this->formatMessage( $ret, 'message', $res->message
);
213 if ( $res->status
=== AuthenticationResponse
::FAIL ||
214 $res->status
=== AuthenticationResponse
::RESTART
216 $this->module
->getRequest()->getSession()->set(
217 'ApiAuthManagerHelper::createRequest',
220 $ret['canpreservestate'] = $res->createRequest
!== null;
222 $this->module
->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
229 * Logs successful or failed authentication.
230 * @param string|AuthenticationResponse $result Response or error message
231 * @param string $event Event type (e.g. 'accountcreation')
233 public function logAuthenticationResult( $event, $result ) {
234 if ( is_string( $result ) ) {
235 $status = Status
::newFatal( $result );
236 } elseif ( $result->status
=== AuthenticationResponse
::PASS
) {
237 $status = Status
::newGood();
238 } elseif ( $result->status
=== AuthenticationResponse
::FAIL
) {
239 $status = Status
::newFatal( $result->message
);
244 $module = $this->module
->getModuleName();
245 LoggerFactory
::getInstance( 'authevents' )->info( "$module API attempt", [
253 * Fetch the preserved CreateFromLoginAuthenticationRequest, if any
254 * @return CreateFromLoginAuthenticationRequest|null
256 public function getPreservedRequest() {
257 $ret = $this->module
->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
258 return $ret instanceof CreateFromLoginAuthenticationRequest ?
$ret : null;
262 * Format an array of AuthenticationRequests for return
263 * @param AuthenticationRequest[] $reqs
264 * @return array Will have a 'requests' key, and also 'fields' if $module's
265 * params include 'mergerequestfields'.
267 public function formatRequests( array $reqs ) {
268 $params = $this->module
->extractRequestParams();
269 $mergeFields = !empty( $params['mergerequestfields'] );
271 $ret = [ 'requests' => [] ];
272 foreach ( $reqs as $req ) {
273 $describe = $req->describeCredentials();
275 'id' => $req->getUniqueId(),
276 'metadata' => $req->getMetadata() +
[ ApiResult
::META_TYPE
=> 'assoc' ],
278 switch ( $req->required
) {
279 case AuthenticationRequest
::OPTIONAL
:
280 $reqInfo['required'] = 'optional';
282 case AuthenticationRequest
::REQUIRED
:
283 $reqInfo['required'] = 'required';
285 case AuthenticationRequest
::PRIMARY_REQUIRED
:
286 $reqInfo['required'] = 'primary-required';
289 $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
290 $this->formatMessage( $reqInfo, 'account', $describe['account'] );
291 if ( !$mergeFields ) {
292 $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
294 $ret['requests'][] = $reqInfo;
297 if ( $mergeFields ) {
298 $fields = AuthenticationRequest
::mergeFieldInfo( $reqs );
299 $ret['fields'] = $this->formatFields( $fields );
306 * Clean up a field array for output
307 * @param ApiBase $module For context and parameters 'mergerequestfields'
308 * and 'messageformat'
309 * @param array $fields
312 private function formatFields( array $fields ) {
318 $module = $this->module
;
321 foreach ( $fields as $name => $field ) {
322 $ret = array_intersect_key( $field, $copy );
324 if ( isset( $field['options'] ) ) {
325 $ret['options'] = array_map( function ( $msg ) use ( $module ) {
326 return $msg->setContext( $module )->plain();
327 }, $field['options'] );
328 ApiResult
::setArrayType( $ret['options'], 'assoc' );
330 $this->formatMessage( $ret, 'label', $field['label'] );
331 $this->formatMessage( $ret, 'help', $field['help'] );
332 $ret['optional'] = !empty( $field['optional'] );
333 $ret['sensitive'] = !empty( $field['sensitive'] );
335 $retFields[$name] = $ret;
338 ApiResult
::setArrayType( $retFields, 'assoc' );
344 * Fetch the standard parameters this helper recognizes
345 * @param string $action AuthManager action
346 * @param string $param... Parameters to use
349 public static function getStandardParams( $action, $param /* ... */ ) {
352 ApiBase
::PARAM_TYPE
=> 'string',
353 ApiBase
::PARAM_ISMULTI
=> true,
354 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-requests', $action ],
357 ApiBase
::PARAM_TYPE
=> 'string',
358 ApiBase
::PARAM_REQUIRED
=> true,
359 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-request', $action ],
362 ApiBase
::PARAM_DFLT
=> 'wikitext',
363 ApiBase
::PARAM_TYPE
=> [ 'html', 'wikitext', 'raw', 'none' ],
364 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-messageformat',
366 'mergerequestfields' => [
367 ApiBase
::PARAM_DFLT
=> false,
368 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-mergerequestfields',
371 ApiBase
::PARAM_DFLT
=> false,
372 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-preservestate',
375 ApiBase
::PARAM_TYPE
=> 'string',
376 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-returnurl',
379 ApiBase
::PARAM_DFLT
=> false,
380 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-continue',
385 $wantedParams = func_get_args();
386 array_shift( $wantedParams );
387 foreach ( $wantedParams as $name ) {
388 if ( isset( $params[$name] ) ) {
389 $ret[$name] = $params[$name];