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(),
93 * Call $manager->securitySensitiveOperationStatus()
94 * @param string $operation Operation being checked.
95 * @throws UsageException
97 public function securitySensitiveOperation( $operation ) {
98 $status = AuthManager
::singleton()->securitySensitiveOperationStatus( $operation );
100 case AuthManager
::SEC_OK
:
103 case AuthManager
::SEC_REAUTH
:
104 $this->module
->dieUsage(
105 'You have not authenticated recently in this session, please reauthenticate.', 'reauthenticate'
108 case AuthManager
::SEC_FAIL
:
109 $this->module
->dieUsage(
110 'This action is not available as your identify cannot be verified.', 'cannotreauthenticate'
114 throw new UnexpectedValueException( "Unknown status \"$status\"" );
119 * Filter out authentication requests by class name
120 * @param AuthenticationRequest[] $reqs Requests to filter
121 * @param string[] $blacklist Class names to remove
122 * @return AuthenticationRequest[]
124 public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
126 $blacklist = array_flip( $blacklist );
127 $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
128 return !isset( $blacklist[get_class( $req )] );
135 * Fetch and load the AuthenticationRequests for an action
136 * @param string $action One of the AuthManager::ACTION_* constants
137 * @return AuthenticationRequest[]
139 public function loadAuthenticationRequests( $action ) {
140 $params = $this->module
->extractRequestParams();
142 $manager = AuthManager
::singleton();
143 $reqs = $manager->getAuthenticationRequests( $action, $this->module
->getUser() );
145 // Filter requests, if requested to do so
146 $wantedRequests = null;
147 if ( isset( $params['requests'] ) ) {
148 $wantedRequests = array_flip( $params['requests'] );
149 } elseif ( isset( $params['request'] ) ) {
150 $wantedRequests = [ $params['request'] => true ];
152 if ( $wantedRequests !== null ) {
153 $reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
154 return isset( $wantedRequests[$req->getUniqueId()] );
158 // Collect the fields for all the requests
160 foreach ( $reqs as $req ) {
161 $fields +
= (array)$req->getFieldInfo();
164 // Extract the request data for the fields and mark those request
165 // parameters as used
166 $data = array_intersect_key( $this->module
->getRequest()->getValues(), $fields );
167 $this->module
->getMain()->markParamsUsed( array_keys( $data ) );
169 return AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
173 * Format an AuthenticationResponse for return
174 * @param AuthenticationResponse $res
177 public function formatAuthenticationResponse( AuthenticationResponse
$res ) {
178 $params = $this->module
->extractRequestParams();
181 'status' => $res->status
,
184 if ( $res->status
=== AuthenticationResponse
::PASS
&& $res->username
!== null ) {
185 $ret['username'] = $res->username
;
188 if ( $res->status
=== AuthenticationResponse
::REDIRECT
) {
189 $ret['redirecttarget'] = $res->redirectTarget
;
190 if ( $res->redirectApiData
!== null ) {
191 $ret['redirectdata'] = $res->redirectApiData
;
195 if ( $res->status
=== AuthenticationResponse
::REDIRECT ||
196 $res->status
=== AuthenticationResponse
::UI ||
197 $res->status
=== AuthenticationResponse
::RESTART
199 $ret +
= $this->formatRequests( $res->neededRequests
);
202 if ( $res->status
=== AuthenticationResponse
::FAIL ||
203 $res->status
=== AuthenticationResponse
::UI ||
204 $res->status
=== AuthenticationResponse
::RESTART
206 $this->formatMessage( $ret, 'message', $res->message
);
209 if ( $res->status
=== AuthenticationResponse
::FAIL ||
210 $res->status
=== AuthenticationResponse
::RESTART
212 $this->module
->getRequest()->getSession()->set(
213 'ApiAuthManagerHelper::createRequest',
216 $ret['canpreservestate'] = $res->createRequest
!== null;
218 $this->module
->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
225 * Logs successful or failed authentication.
226 * @param string|AuthenticationResponse $result Response or error message
227 * @param string $event Event type (e.g. 'accountcreation')
229 public function logAuthenticationResult( $event, $result ) {
230 if ( is_string( $result ) ) {
231 $status = Status
::newFatal( $result );
232 } elseif ( $result->status
=== AuthenticationResponse
::PASS
) {
233 $status = Status
::newGood();
234 } elseif ( $result->status
=== AuthenticationResponse
::FAIL
) {
235 $status = Status
::newFatal( $result->message
);
240 $module = $this->module
->getModuleName();
241 LoggerFactory
::getInstance( 'authmanager' )->info( "$module API attempt", [
249 * Fetch the preserved CreateFromLoginAuthenticationRequest, if any
250 * @return CreateFromLoginAuthenticationRequest|null
252 public function getPreservedRequest() {
253 $ret = $this->module
->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
254 return $ret instanceof CreateFromLoginAuthenticationRequest ?
$ret : null;
258 * Format an array of AuthenticationRequests for return
259 * @param AuthenticationRequest[] $reqs
260 * @return array Will have a 'requests' key, and also 'fields' if $module's
261 * params include 'mergerequestfields'.
263 public function formatRequests( array $reqs ) {
264 $params = $this->module
->extractRequestParams();
265 $mergeFields = !empty( $params['mergerequestfields'] );
267 $ret = [ 'requests' => [] ];
268 foreach ( $reqs as $req ) {
269 $describe = $req->describeCredentials();
271 'id' => $req->getUniqueId(),
272 'metadata' => $req->getMetadata() +
[ ApiResult
::META_TYPE
=> 'assoc' ],
274 switch ( $req->required
) {
275 case AuthenticationRequest
::OPTIONAL
:
276 $reqInfo['required'] = 'optional';
278 case AuthenticationRequest
::REQUIRED
:
279 $reqInfo['required'] = 'required';
281 case AuthenticationRequest
::PRIMARY_REQUIRED
:
282 $reqInfo['required'] = 'primary-required';
285 $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
286 $this->formatMessage( $reqInfo, 'account', $describe['account'] );
287 if ( !$mergeFields ) {
288 $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
290 $ret['requests'][] = $reqInfo;
293 if ( $mergeFields ) {
294 $fields = AuthenticationRequest
::mergeFieldInfo( $reqs );
295 $ret['fields'] = $this->formatFields( $fields );
302 * Clean up a field array for output
303 * @param ApiBase $module For context and parameters 'mergerequestfields'
304 * and 'messageformat'
305 * @param array $fields
308 private function formatFields( array $fields ) {
314 $module = $this->module
;
317 foreach ( $fields as $name => $field ) {
318 $ret = array_intersect_key( $field, $copy );
320 if ( isset( $field['options'] ) ) {
321 $ret['options'] = array_map( function ( $msg ) use ( $module ) {
322 return $msg->setContext( $module )->plain();
323 }, $field['options'] );
324 ApiResult
::setArrayType( $ret['options'], 'assoc' );
326 $this->formatMessage( $ret, 'label', $field['label'] );
327 $this->formatMessage( $ret, 'help', $field['help'] );
328 $ret['optional'] = !empty( $field['optional'] );
330 $retFields[$name] = $ret;
333 ApiResult
::setArrayType( $retFields, 'assoc' );
339 * Fetch the standard parameters this helper recognizes
340 * @param string $action AuthManager action
341 * @param string $param... Parameters to use
344 public static function getStandardParams( $action, $param /* ... */ ) {
347 ApiBase
::PARAM_TYPE
=> 'string',
348 ApiBase
::PARAM_ISMULTI
=> true,
349 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-requests', $action ],
352 ApiBase
::PARAM_TYPE
=> 'string',
353 ApiBase
::PARAM_REQUIRED
=> true,
354 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-authmanagerhelper-request', $action ],
357 ApiBase
::PARAM_DFLT
=> 'wikitext',
358 ApiBase
::PARAM_TYPE
=> [ 'html', 'wikitext', 'raw', 'none' ],
359 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-messageformat',
361 'mergerequestfields' => [
362 ApiBase
::PARAM_DFLT
=> false,
363 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-mergerequestfields',
366 ApiBase
::PARAM_DFLT
=> false,
367 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-preservestate',
370 ApiBase
::PARAM_TYPE
=> 'string',
371 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-returnurl',
374 ApiBase
::PARAM_DFLT
=> false,
375 ApiBase
::PARAM_HELP_MSG
=> 'api-help-authmanagerhelper-continue',
380 $wantedParams = func_get_args();
381 array_shift( $wantedParams );
382 foreach ( $wantedParams as $name ) {
383 if ( isset( $params[$name] ) ) {
384 $ret[$name] = $params[$name];