MediaWiki REL1_35
ApiLogin.php
Go to the documentation of this file.
1<?php
29
35class ApiLogin extends ApiBase {
36
37 public function __construct( ApiMain $main, $action ) {
38 parent::__construct( $main, $action, 'lg' );
39 }
40
41 protected function getExtendedDescription() {
42 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
43 return 'apihelp-login-extended-description';
44 } else {
45 return 'apihelp-login-extended-description-nobotpasswords';
46 }
47 }
48
54 private function formatMessage( $message ) {
55 $message = Message::newFromSpecifier( $message );
56 $errorFormatter = $this->getErrorFormatter();
57 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat ) {
59 $message->useDatabase( false )->inLanguage( 'en' )->text()
60 );
61 } else {
62 return $errorFormatter->formatMessage( $message );
63 }
64 }
65
75 public function execute() {
76 // If we're in a mode that breaks the same-origin policy, no tokens can
77 // be obtained
78 if ( $this->lacksSameOriginSecurity() ) {
79 $this->getResult()->addValue( null, 'login', [
80 'result' => 'Aborted',
81 'reason' => $this->formatMessage( 'api-login-fail-sameorigin' ),
82 ] );
83
84 return;
85 }
86
87 $this->requirePostedParameters( [ 'password', 'token' ] );
88
89 $params = $this->extractRequestParams();
90
91 $result = [];
92
93 // Make sure session is persisted
94 $session = MediaWiki\Session\SessionManager::getGlobalSession();
95 $session->persist();
96
97 // Make sure it's possible to log in
98 if ( !$session->canSetUser() ) {
99 $this->getResult()->addValue( null, 'login', [
100 'result' => 'Aborted',
101 'reason' => $this->formatMessage( [
102 'api-login-fail-badsessionprovider',
103 $session->getProvider()->describe( $this->getErrorFormatter()->getLanguage() ),
104 ] )
105 ] );
106
107 return;
108 }
109
110 $authRes = false;
111 $loginType = 'N/A';
112
113 // Check login token
114 $token = $session->getToken( '', 'login' );
115 if ( !$params['token'] ) {
116 $authRes = 'NeedToken';
117 } elseif ( $token->wasNew() ) {
118 $authRes = 'Failed';
119 $message = ApiMessage::create( 'authpage-cannot-login-continue', 'sessionlost' );
120 } elseif ( !$token->match( $params['token'] ) ) {
121 $authRes = 'WrongToken';
122 }
123
124 // Try bot passwords
125 if (
126 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
127 ( $botLoginData = BotPassword::canonicalizeLoginData( $params['name'], $params['password'] ) )
128 ) {
129 $status = BotPassword::login(
130 $botLoginData[0], $botLoginData[1], $this->getRequest()
131 );
132 if ( $status->isOK() ) {
133 $session = $status->getValue();
134 $authRes = 'Success';
135 $loginType = 'BotPassword';
136 } elseif (
137 $status->hasMessage( 'login-throttled' ) ||
138 $status->hasMessage( 'botpasswords-needs-reset' ) ||
139 $status->hasMessage( 'botpasswords-locked' )
140 ) {
141 $authRes = 'Failed';
142 $message = $status->getMessage();
143 LoggerFactory::getInstance( 'authentication' )->info(
144 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
145 );
146 }
147 // For other errors, let's see if it's a valid non-bot login
148 }
149
150 if ( $authRes === false ) {
151 // Simplified AuthManager login, for backwards compatibility
152 $manager = MediaWikiServices::getInstance()->getAuthManager();
153 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
154 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN, $this->getUser() ),
155 [
156 'username' => $params['name'],
157 'password' => $params['password'],
158 'domain' => $params['domain'],
159 'rememberMe' => true,
160 ]
161 );
162 $res = $manager->beginAuthentication( $reqs, 'null:' );
163 switch ( $res->status ) {
164 case AuthenticationResponse::PASS:
165 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
166 $this->addDeprecation( 'apiwarn-deprecation-login-botpw', 'main-account-login' );
167 } else {
168 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
169 }
170 $authRes = 'Success';
171 $loginType = 'AuthManager';
172 break;
173
174 case AuthenticationResponse::FAIL:
175 // Hope it's not a PreAuthenticationProvider that failed...
176 $authRes = 'Failed';
177 $message = $res->message;
178 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
179 ->info( __METHOD__ . ': Authentication failed: '
180 . $message->inLanguage( 'en' )->plain() );
181 break;
182
183 default:
184 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
185 ->info( __METHOD__ . ': Authentication failed due to unsupported response type: '
186 . $res->status, $this->getAuthenticationResponseLogData( $res ) );
187 $authRes = 'Aborted';
188 break;
189 }
190 }
191
192 $result['result'] = $authRes;
193 switch ( $authRes ) {
194 case 'Success':
195 $user = $session->getUser();
196
198
199 // Deprecated hook
200 $injected_html = '';
201 $this->getHookRunner()->onUserLoginComplete( $user, $injected_html, true );
202
203 $result['lguserid'] = (int)$user->getId();
204 $result['lgusername'] = $user->getName();
205 break;
206
207 case 'NeedToken':
208 $result['token'] = $token->toString();
209 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
210 break;
211
212 case 'WrongToken':
213 break;
214
215 case 'Failed':
216 $result['reason'] = $this->formatMessage( $message );
217 break;
218
219 case 'Aborted':
220 $result['reason'] = $this->formatMessage(
221 $this->getConfig()->get( 'EnableBotPasswords' )
222 ? 'api-login-fail-aborted'
223 : 'api-login-fail-aborted-nobotpw'
224 );
225 break;
226
227 // @codeCoverageIgnoreStart
228 // Unreachable
229 default:
230 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
231 // @codeCoverageIgnoreEnd
232 }
233
234 $this->getResult()->addValue( null, 'login', $result );
235
236 LoggerFactory::getInstance( 'authevents' )->info( 'Login attempt', [
237 'event' => 'login',
238 'successful' => $authRes === 'Success',
239 'loginType' => $loginType,
240 'status' => $authRes,
241 ] );
242 }
243
244 public function isDeprecated() {
245 return !$this->getConfig()->get( 'EnableBotPasswords' );
246 }
247
248 public function mustBePosted() {
249 return true;
250 }
251
252 public function isReadMode() {
253 return false;
254 }
255
256 public function getAllowedParams() {
257 return [
258 'name' => null,
259 'password' => [
260 ApiBase::PARAM_TYPE => 'password',
261 ],
262 'domain' => null,
263 'token' => [
264 ApiBase::PARAM_TYPE => 'string',
265 ApiBase::PARAM_REQUIRED => false, // for BC
267 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
268 ],
269 ];
270 }
271
272 protected function getExamplesMessages() {
273 return [
274 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
275 => 'apihelp-login-example-login',
276 ];
277 }
278
279 public function getHelpUrls() {
280 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login';
281 }
282
289 $ret = [
290 'status' => $response->status,
291 ];
292 if ( $response->message ) {
293 $ret['responseMessage'] = $response->message->inLanguage( 'en' )->plain();
294 }
295 $reqs = [
296 'neededRequests' => $response->neededRequests,
297 'createRequest' => $response->createRequest,
298 'linkRequest' => $response->linkRequest,
299 ];
300 foreach ( $reqs as $k => $v ) {
301 if ( $v ) {
302 $v = is_array( $v ) ? $v : [ $v ];
303 $reqClasses = array_unique( array_map( 'get_class', $v ) );
304 sort( $reqClasses );
305 $ret[$k] = implode( ', ', $reqClasses );
306 }
307 }
308 return $ret;
309 }
310}
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:52
const PARAM_REQUIRED
Definition ApiBase.php:102
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1629
const PARAM_TYPE
Definition ApiBase.php:78
const PARAM_SENSITIVE
Definition ApiBase.php:122
getErrorFormatter()
Get the error formatter Stable to override.
Definition ApiBase.php:635
requirePostedParameters( $params, $prefix='prefix')
Die if any of the specified parameters were found in the query part of the URL rather than the post b...
Definition ApiBase.php:996
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition ApiBase.php:1370
getResult()
Get the result object.
Definition ApiBase.php:620
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:772
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:162
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:717
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
Definition ApiBase.php:548
Format errors and warnings in the old style, for backwards compatibility.
static stripMarkup( $text)
Turn wikitext into something resembling plaintext.
Unit to authenticate log-in attempts to the current wiki.
Definition ApiLogin.php:35
formatMessage( $message)
Format a message for the response.
Definition ApiLogin.php:54
getHelpUrls()
Return links to more detailed help pages about the module.
Definition ApiLogin.php:279
getExtendedDescription()
Return the extended help text message.
Definition ApiLogin.php:41
isDeprecated()
Indicates whether this module is deprecated.
Definition ApiLogin.php:244
__construct(ApiMain $main, $action)
Definition ApiLogin.php:37
isReadMode()
Indicates whether this module requires read rights Stable to override.
Definition ApiLogin.php:252
mustBePosted()
Indicates whether this module must be called with a POST request Stable to override.
Definition ApiLogin.php:248
execute()
Executes the log-in attempt using the parameters passed.
Definition ApiLogin.php:75
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition ApiLogin.php:256
getAuthenticationResponseLogData(AuthenticationResponse $response)
Turns an AuthenticationResponse into a hash suitable for passing to Logger.
Definition ApiLogin.php:288
getExamplesMessages()
Returns usage examples for this module.
Definition ApiLogin.php:272
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:47
static resetTokenCache()
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
This is a value object to hold authentication response data.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition Message.php:452