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, true ] );
213 $result['lguserid'] = intval( $user->getId() );
214 $result['lgusername'] = $user->getName();
218 $result['token'] = $token->toString();
219 $this->setWarning( 'Fetching a token via action=login is deprecated. ' .
220 'Use action=query&meta=tokens&type=login instead.' );
221 $this->logFeatureUsage( 'action=login&!lgtoken' );
228 $result['reason'] = $message->useDatabase( 'false' )->inLanguage( 'en' )->text();
232 $result['reason'] = 'Authentication requires user interaction, ' .
233 'which is not supported by action=login.';
234 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
235 $result['reason'] .= ' To be able to login with action=login, see [[Special:BotPasswords]].';
236 $result['reason'] .= ' To continue using main-account login, see action=clientlogin.';
238 $result['reason'] .= ' To log in, see action=clientlogin.';
242 // Results from LoginForm for when $wgDisableAuthManager is true
243 case LoginForm
::WRONG_TOKEN
:
244 $result['result'] = 'WrongToken';
247 case LoginForm
::NO_NAME
:
248 $result['result'] = 'NoName';
251 case LoginForm
::ILLEGAL
:
252 $result['result'] = 'Illegal';
255 case LoginForm
::WRONG_PLUGIN_PASS
:
256 $result['result'] = 'WrongPluginPass';
259 case LoginForm
::NOT_EXISTS
:
260 $result['result'] = 'NotExists';
263 // bug 20223 - Treat a temporary password as wrong. Per SpecialUserLogin:
264 // The e-mailed temporary password should not be used for actual logins.
265 case LoginForm
::RESET_PASS
:
266 case LoginForm
::WRONG_PASS
:
267 $result['result'] = 'WrongPass';
270 case LoginForm
::EMPTY_PASS
:
271 $result['result'] = 'EmptyPass';
274 case LoginForm
::CREATE_BLOCKED
:
275 $result['result'] = 'CreateBlocked';
276 $result['details'] = 'Your IP address is blocked from account creation';
277 $block = $context->getUser()->getBlock();
279 $result = array_merge( $result, ApiQueryUserInfo
::getBlockInfo( $block ) );
283 case LoginForm
::THROTTLED
:
284 $result['result'] = 'Throttled';
285 $result['wait'] = intval( $loginForm->mThrottleWait
);
288 case LoginForm
::USER_BLOCKED
:
289 $result['result'] = 'Blocked';
290 $block = User
::newFromName( $params['name'] )->getBlock();
292 $result = array_merge( $result, ApiQueryUserInfo
::getBlockInfo( $block ) );
296 case LoginForm
::ABORTED
:
297 $result['result'] = 'Aborted';
298 $result['reason'] = $loginForm->mAbortLoginErrorMsg
;
302 ApiBase
::dieDebug( __METHOD__
, "Unhandled case value: {$authRes}" );
305 $this->getResult()->addValue( null, 'login', $result );
307 if ( $loginType === 'LoginForm' && isset( LoginForm
::$statusCodes[$authRes] ) ) {
308 $authRes = LoginForm
::$statusCodes[$authRes];
310 LoggerFactory
::getInstance( 'authmanager' )->info( 'Login attempt', [
312 'successful' => $authRes === 'Success',
313 'loginType' => $loginType,
314 'status' => $authRes,
318 public function isDeprecated() {
319 return !$this->getConfig()->get( 'DisableAuthManager' ) &&
320 !$this->getConfig()->get( 'EnableBotPasswords' );
323 public function mustBePosted() {
327 public function isReadMode() {
331 public function getAllowedParams() {
335 ApiBase
::PARAM_TYPE
=> 'password',
339 ApiBase
::PARAM_TYPE
=> 'string',
340 ApiBase
::PARAM_REQUIRED
=> false, // for BC
341 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-param-token', 'login' ],
346 protected function getExamplesMessages() {
348 'action=login&lgname=user&lgpassword=password'
349 => 'apihelp-login-example-gettoken',
350 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
351 => 'apihelp-login-example-login',
355 public function getHelpUrls() {
356 return 'https://www.mediawiki.org/wiki/API:Login';