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( 'EnableBotPasswords' ) ) {
46 return 'apihelp-login-description';
48 return 'apihelp-login-description-nobotpasswords';
53 * Executes the log-in attempt using the parameters passed. If
54 * the log-in succeeds, it attaches a cookie to the session
55 * and outputs the user id, username, and session token. If a
56 * log-in fails, as the result of a bad password, a nonexistent
57 * user, or any other reason, the host is cached with an expiry
58 * and no log-in attempts will be accepted until that expiry
59 * is reached. The expiry is $this->mLoginThrottle.
61 public function execute() {
62 // If we're in a mode that breaks the same-origin policy, no tokens can
64 if ( $this->lacksSameOriginSecurity() ) {
65 $this->getResult()->addValue( null, 'login', [
66 'result' => 'Aborted',
67 'reason' => 'Cannot log in when the same-origin policy is not applied',
73 $this->requirePostedParameters( [ 'password', 'token' ] );
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';
108 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
109 ( $botLoginData = BotPassword
::canonicalizeLoginData( $params['name'], $params['password'] ) )
111 $status = BotPassword
::login(
112 $botLoginData[0], $botLoginData[1], $this->getRequest()
114 if ( $status->isOK() ) {
115 $session = $status->getValue();
116 $authRes = 'Success';
117 $loginType = 'BotPassword';
118 } elseif ( !$botLoginData[2] ) {
120 $message = $status->getMessage();
121 LoggerFactory
::getInstance( 'authentication' )->info(
122 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
127 if ( $authRes === false ) {
128 // Simplified AuthManager login, for backwards compatibility
129 $manager = AuthManager
::singleton();
130 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
131 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
, $this->getUser() ),
133 'username' => $params['name'],
134 'password' => $params['password'],
135 'domain' => $params['domain'],
136 'rememberMe' => true,
139 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
140 switch ( $res->status
) {
141 case AuthenticationResponse
::PASS
:
142 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
143 $this->addDeprecation( 'apiwarn-deprecation-login-botpw', 'main-account-login' );
145 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
147 $authRes = 'Success';
148 $loginType = 'AuthManager';
151 case AuthenticationResponse
::FAIL
:
152 // Hope it's not a PreAuthenticationProvider that failed...
154 $message = $res->message
;
155 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
156 ->info( __METHOD__
. ': Authentication failed: '
157 . $message->inLanguage( 'en' )->plain() );
161 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
162 ->info( __METHOD__
. ': Authentication failed due to unsupported response type: '
163 . $res->status
, $this->getAuthenticationResponseLogData( $res ) );
164 $authRes = 'Aborted';
169 $result['result'] = $authRes;
170 switch ( $authRes ) {
172 $user = $session->getUser();
174 ApiQueryInfo
::resetTokenCache();
178 Hooks
::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
180 $result['lguserid'] = intval( $user->getId() );
181 $result['lgusername'] = $user->getName();
185 $result['token'] = $token->toString();
186 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
193 $errorFormatter = $this->getErrorFormatter();
194 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat
) {
195 $result['reason'] = ApiErrorFormatter
::stripMarkup(
196 $message->useDatabase( false )->inLanguage( 'en' )->text()
199 $result['reason'] = $errorFormatter->formatMessage( $message );
204 $result['reason'] = 'Authentication requires user interaction, ' .
205 'which is not supported by action=login.';
206 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
207 $result['reason'] .= ' To be able to login with action=login, see [[Special:BotPasswords]].';
208 $result['reason'] .= ' To continue using main-account login, see action=clientlogin.';
210 $result['reason'] .= ' To log in, see action=clientlogin.';
215 ApiBase
::dieDebug( __METHOD__
, "Unhandled case value: {$authRes}" );
218 $this->getResult()->addValue( null, 'login', $result );
220 if ( $loginType === 'LoginForm' && isset( LoginForm
::$statusCodes[$authRes] ) ) {
221 $authRes = LoginForm
::$statusCodes[$authRes];
223 LoggerFactory
::getInstance( 'authevents' )->info( 'Login attempt', [
225 'successful' => $authRes === 'Success',
226 'loginType' => $loginType,
227 'status' => $authRes,
231 public function isDeprecated() {
232 return !$this->getConfig()->get( 'EnableBotPasswords' );
235 public function mustBePosted() {
239 public function isReadMode() {
243 public function getAllowedParams() {
247 ApiBase
::PARAM_TYPE
=> 'password',
251 ApiBase
::PARAM_TYPE
=> 'string',
252 ApiBase
::PARAM_REQUIRED
=> false, // for BC
253 ApiBase
::PARAM_HELP_MSG
=> [ 'api-help-param-token', 'login' ],
258 protected function getExamplesMessages() {
260 'action=login&lgname=user&lgpassword=password'
261 => 'apihelp-login-example-gettoken',
262 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
263 => 'apihelp-login-example-login',
267 public function getHelpUrls() {
268 return 'https://www.mediawiki.org/wiki/API:Login';
272 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
273 * @param AuthenticationResponse $response
276 protected function getAuthenticationResponseLogData( AuthenticationResponse
$response ) {
278 'status' => $response->status
,
280 if ( $response->message
) {
281 $ret['message'] = $response->message
->inLanguage( 'en' )->plain();
284 'neededRequests' => $response->neededRequests
,
285 'createRequest' => $response->createRequest
,
286 'linkRequest' => $response->linkRequest
,
288 foreach ( $reqs as $k => $v ) {
290 $v = is_array( $v ) ?
$v : [ $v ];
291 $reqClasses = array_unique( array_map( 'get_class', $v ) );
293 $ret[$k] = implode( ', ', $reqClasses );