5 * Created on Sep 19, 2006
7 * Copyright © 2006-2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
8 * Daniel Cannon (cannon dot danielc at gmail dot com)
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
28 use MediaWiki\Auth\AuthManager
;
29 use MediaWiki\Auth\AuthenticationRequest
;
30 use MediaWiki\Auth\AuthenticationResponse
;
31 use MediaWiki\Logger\LoggerFactory
;
34 * Unit to authenticate log-in attempts to the current wiki.
38 class ApiLogin
extends ApiBase
{
40 public function __construct( ApiMain
$main, $action ) {
41 parent
::__construct( $main, $action, 'lg' );
44 protected function getDescriptionMessage() {
45 if ( $this->getConfig()->get( 'DisableAuthManager' ) ) {
46 return 'apihelp-login-description-nonauthmanager';
47 } elseif ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
48 return 'apihelp-login-description';
50 return 'apihelp-login-description-nobotpasswords';
55 * Executes the log-in attempt using the parameters passed. If
56 * the log-in succeeds, it attaches a cookie to the session
57 * and outputs the user id, username, and session token. If a
58 * log-in fails, as the result of a bad password, a nonexistent
59 * user, or any other reason, the host is cached with an expiry
60 * and no log-in attempts will be accepted until that expiry
61 * is reached. The expiry is $this->mLoginThrottle.
63 public function execute() {
64 // If we're in a mode that breaks the same-origin policy, no tokens can
66 if ( $this->lacksSameOriginSecurity() ) {
67 $this->getResult()->addValue( null, 'login', [
68 'result' => 'Aborted',
69 'reason' => 'Cannot log in when the same-origin policy is not applied',
75 $params = $this->extractRequestParams();
79 // Make sure session is persisted
80 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
83 // Make sure it's possible to log in
84 if ( !$session->canSetUser() ) {
85 $this->getResult()->addValue( null, 'login', [
86 'result' => 'Aborted',
87 'reason' => 'Cannot log in when using ' .
88 $session->getProvider()->describe( Language
::factory( 'en' ) ),
95 $context = new DerivativeContext( $this->getContext() );
99 $token = $session->getToken( '', 'login' );
100 if ( $token->wasNew() ||
!$params['token'] ) {
101 $authRes = 'NeedToken';
102 } elseif ( !$token->match( $params['token'] ) ) {
103 $authRes = 'WrongToken';
107 if ( $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
108 strpos( $params['name'], BotPassword
::getSeparator() ) !== false
110 $status = BotPassword
::login(
111 $params['name'], $params['password'], $this->getRequest()
113 if ( $status->isOK() ) {
114 $session = $status->getValue();
115 $authRes = 'Success';
116 $loginType = 'BotPassword';
119 $message = $status->getMessage();
120 LoggerFactory
::getInstance( 'authmanager' )->info(
121 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
126 if ( $authRes === false ) {
127 if ( $this->getConfig()->get( 'DisableAuthManager' ) ) {
128 // Non-AuthManager login
129 $context->setRequest( new DerivativeRequest(
130 $this->getContext()->getRequest(),
132 'wpName' => $params['name'],
133 'wpPassword' => $params['password'],
134 'wpDomain' => $params['domain'],
135 'wpLoginToken' => $params['token'],
139 $loginForm = new LoginForm();
140 $loginForm->setContext( $context );
141 $authRes = $loginForm->authenticateUserData();
142 $loginType = 'LoginForm';
144 switch ( $authRes ) {
145 case LoginForm
::SUCCESS
:
146 $authRes = 'Success';
148 case LoginForm
::NEED_TOKEN
:
149 $authRes = 'NeedToken';
153 // Simplified AuthManager login, for backwards compatibility
154 $manager = AuthManager
::singleton();
155 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
156 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
, $this->getUser() ),
158 'username' => $params['name'],
159 'password' => $params['password'],
160 'domain' => $params['domain'],
161 'rememberMe' => true,
164 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
165 switch ( $res->status
) {
166 case AuthenticationResponse
::PASS
:
167 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
168 $warn = 'Main-account login via action=login is deprecated and may stop working ' .
170 $warn .= ' To continue login with action=login, see [[Special:BotPasswords]].';
171 $warn .= ' To safely continue using main-account login, see action=clientlogin.';
173 $warn = 'Login via action=login is deprecated and may stop working without warning.';
174 $warn .= ' To safely log in, see action=clientlogin.';
176 $this->setWarning( $warn );
177 $authRes = 'Success';
178 $loginType = 'AuthManager';
181 case AuthenticationResponse
::FAIL
:
182 // Hope it's not a PreAuthenticationProvider that failed...
184 $message = $res->message
;
185 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
186 ->info( __METHOD__
. ': Authentication failed: ' . $message->plain() );
190 $authRes = 'Aborted';
196 $result['result'] = $authRes;
197 switch ( $authRes ) {
199 if ( $this->getConfig()->get( 'DisableAuthManager' ) ) {
200 $user = $context->getUser();
201 $this->getContext()->setUser( $user );
202 $user->setCookies( $this->getRequest(), null, true );
204 $user = $session->getUser();
207 ApiQueryInfo
::resetTokenCache();
211 Hooks
::run( 'UserLoginComplete', [ &$user, &$injected_html ] );
213 $result['lguserid'] = intval( $user->getId() );
214 $result['lgusername'] = $user->getName();
216 // @todo: These are deprecated, and should be removed at some
217 // point (1.28 at the earliest, and see T121527). They were ok
218 // when the core cookie-based login was the only thing, but
219 // CentralAuth broke that a while back and
220 // SessionManager/AuthManager *really* break it.
221 $result['lgtoken'] = $user->getToken();
222 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
223 $result['sessionid'] = $session->getId();
227 $result['token'] = $token->toString();
228 $this->setWarning( 'Fetching a token via action=login is deprecated. ' .
229 'Use action=query&meta=tokens&type=login instead.' );
230 $this->logFeatureUsage( 'action=login&!lgtoken' );
232 // @todo: See above about deprecation
233 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
234 $result['sessionid'] = $session->getId();
241 $result['reason'] = $message->useDatabase( 'false' )->inLanguage( 'en' )->text();
245 $result['reason'] = 'Authentication requires user interaction, ' .
246 'which is not supported by action=login.';
247 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
248 $result['reason'] .= ' To be able to login with action=login, see [[Special:BotPasswords]].';
249 $result['reason'] .= ' To continue using main-account login, see action=clientlogin.';
251 $result['reason'] .= ' To log in, see action=clientlogin.';
255 // Results from LoginForm for when $wgDisableAuthManager is true
256 case LoginForm
::WRONG_TOKEN
:
257 $result['result'] = 'WrongToken';
260 case LoginForm
::NO_NAME
:
261 $result['result'] = 'NoName';
264 case LoginForm
::ILLEGAL
:
265 $result['result'] = 'Illegal';
268 case LoginForm
::WRONG_PLUGIN_PASS
:
269 $result['result'] = 'WrongPluginPass';
272 case LoginForm
::NOT_EXISTS
:
273 $result['result'] = 'NotExists';
276 // bug 20223 - Treat a temporary password as wrong. Per SpecialUserLogin:
277 // The e-mailed temporary password should not be used for actual logins.
278 case LoginForm
::RESET_PASS
:
279 case LoginForm
::WRONG_PASS
:
280 $result['result'] = 'WrongPass';
283 case LoginForm
::EMPTY_PASS
:
284 $result['result'] = 'EmptyPass';
287 case LoginForm
::CREATE_BLOCKED
:
288 $result['result'] = 'CreateBlocked';
289 $result['details'] = 'Your IP address is blocked from account creation';
290 $block = $context->getUser()->getBlock();
292 $result = array_merge( $result, ApiQueryUserInfo
::getBlockInfo( $block ) );
296 case LoginForm
::THROTTLED
:
297 $result['result'] = 'Throttled';
298 $result['wait'] = intval( $loginForm->mThrottleWait
);
301 case LoginForm
::USER_BLOCKED
:
302 $result['result'] = 'Blocked';
303 $block = User
::newFromName( $params['name'] )->getBlock();
305 $result = array_merge( $result, ApiQueryUserInfo
::getBlockInfo( $block ) );
309 case LoginForm
::ABORTED
:
310 $result['result'] = 'Aborted';
311 $result['reason'] = $loginForm->mAbortLoginErrorMsg
;
315 ApiBase
::dieDebug( __METHOD__
, "Unhandled case value: {$authRes}" );
318 $this->getResult()->addValue( null, 'login', $result );
320 if ( $loginType === 'LoginForm' && isset( LoginForm
::$statusCodes[$authRes] ) ) {
321 $authRes = LoginForm
::$statusCodes[$authRes];
323 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', [
325 'successful' => $authRes === 'Success',
326 'loginType' => $loginType,
327 'status' => $authRes,
331 public function isDeprecated() {
332 return !$this->getConfig()->get( 'DisableAuthManager' ) &&
333 !$this->getConfig()->get( 'EnableBotPasswords' );
336 public function mustBePosted() {
340 public function isReadMode() {
344 public function getAllowedParams() {
348 ApiBase
::PARAM_TYPE
=> 'password',
352 ApiBase
::PARAM_TYPE
=> 'string',
353 ApiBase
::PARAM_REQUIRED
=> false, // for BC
354 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-param-token', 'login' ],
359 protected function getExamplesMessages() {
361 'action=login&lgname=user&lgpassword=password'
362 => 'apihelp-login-example-gettoken',
363 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
364 => 'apihelp-login-example-login',
368 public function getHelpUrls() {
369 return 'https://www.mediawiki.org/wiki/API:Login';