Merge "New maintenance script to clean up rows with invalid DB keys"
[lhc/web/wiklou.git] / includes / api / ApiLogin.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 19, 2006
6 *
7 * Copyright © 2006-2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
8 * Daniel Cannon (cannon dot danielc at gmail dot com)
9 *
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.
14 *
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.
19 *
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
24 *
25 * @file
26 */
27
28 use MediaWiki\Auth\AuthManager;
29 use MediaWiki\Auth\AuthenticationRequest;
30 use MediaWiki\Auth\AuthenticationResponse;
31 use MediaWiki\Logger\LoggerFactory;
32
33 /**
34 * Unit to authenticate log-in attempts to the current wiki.
35 *
36 * @ingroup API
37 */
38 class ApiLogin extends ApiBase {
39
40 public function __construct( ApiMain $main, $action ) {
41 parent::__construct( $main, $action, 'lg' );
42 }
43
44 protected function getDescriptionMessage() {
45 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
46 return 'apihelp-login-description';
47 } else {
48 return 'apihelp-login-description-nobotpasswords';
49 }
50 }
51
52 /**
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.
60 */
61 public function execute() {
62 // If we're in a mode that breaks the same-origin policy, no tokens can
63 // be obtained
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',
68 ] );
69
70 return;
71 }
72
73 $this->requirePostedParameters( [ 'password', 'token' ] );
74
75 $params = $this->extractRequestParams();
76
77 $result = [];
78
79 // Make sure session is persisted
80 $session = MediaWiki\Session\SessionManager::getGlobalSession();
81 $session->persist();
82
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' ) ),
89 ] );
90
91 return;
92 }
93
94 $authRes = false;
95 $context = new DerivativeContext( $this->getContext() );
96 $loginType = 'N/A';
97
98 // Check login token
99 $token = $session->getToken( '', 'login' );
100 if ( $token->wasNew() || !$params['token'] ) {
101 $authRes = 'NeedToken';
102 } elseif ( !$token->match( $params['token'] ) ) {
103 $authRes = 'WrongToken';
104 }
105
106 // Try bot passwords
107 if (
108 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
109 ( $botLoginData = BotPassword::canonicalizeLoginData( $params['name'], $params['password'] ) )
110 ) {
111 $status = BotPassword::login(
112 $botLoginData[0], $botLoginData[1], $this->getRequest()
113 );
114 if ( $status->isOK() ) {
115 $session = $status->getValue();
116 $authRes = 'Success';
117 $loginType = 'BotPassword';
118 } elseif ( !$botLoginData[2] ) {
119 $authRes = 'Failed';
120 $message = $status->getMessage();
121 LoggerFactory::getInstance( 'authentication' )->info(
122 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
123 );
124 }
125 }
126
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() ),
132 [
133 'username' => $params['name'],
134 'password' => $params['password'],
135 'domain' => $params['domain'],
136 'rememberMe' => true,
137 ]
138 );
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' );
144 } else {
145 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
146 }
147 $authRes = 'Success';
148 $loginType = 'AuthManager';
149 break;
150
151 case AuthenticationResponse::FAIL:
152 // Hope it's not a PreAuthenticationProvider that failed...
153 $authRes = 'Failed';
154 $message = $res->message;
155 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
156 ->info( __METHOD__ . ': Authentication failed: '
157 . $message->inLanguage( 'en' )->plain() );
158 break;
159
160 default:
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';
165 break;
166 }
167 }
168
169 $result['result'] = $authRes;
170 switch ( $authRes ) {
171 case 'Success':
172 $user = $session->getUser();
173
174 ApiQueryInfo::resetTokenCache();
175
176 // Deprecated hook
177 $injected_html = '';
178 Hooks::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
179
180 $result['lguserid'] = intval( $user->getId() );
181 $result['lgusername'] = $user->getName();
182 break;
183
184 case 'NeedToken':
185 $result['token'] = $token->toString();
186 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
187 break;
188
189 case 'WrongToken':
190 break;
191
192 case 'Failed':
193 $errorFormatter = $this->getErrorFormatter();
194 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat ) {
195 $result['reason'] = ApiErrorFormatter::stripMarkup(
196 $message->useDatabase( false )->inLanguage( 'en' )->text()
197 );
198 } else {
199 $result['reason'] = $errorFormatter->formatMessage( $message );
200 }
201 break;
202
203 case 'Aborted':
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.';
209 } else {
210 $result['reason'] .= ' To log in, see action=clientlogin.';
211 }
212 break;
213
214 default:
215 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
216 }
217
218 $this->getResult()->addValue( null, 'login', $result );
219
220 if ( $loginType === 'LoginForm' && isset( LoginForm::$statusCodes[$authRes] ) ) {
221 $authRes = LoginForm::$statusCodes[$authRes];
222 }
223 LoggerFactory::getInstance( 'authevents' )->info( 'Login attempt', [
224 'event' => 'login',
225 'successful' => $authRes === 'Success',
226 'loginType' => $loginType,
227 'status' => $authRes,
228 ] );
229 }
230
231 public function isDeprecated() {
232 return !$this->getConfig()->get( 'EnableBotPasswords' );
233 }
234
235 public function mustBePosted() {
236 return true;
237 }
238
239 public function isReadMode() {
240 return false;
241 }
242
243 public function getAllowedParams() {
244 return [
245 'name' => null,
246 'password' => [
247 ApiBase::PARAM_TYPE => 'password',
248 ],
249 'domain' => null,
250 'token' => [
251 ApiBase::PARAM_TYPE => 'string',
252 ApiBase::PARAM_REQUIRED => false, // for BC
253 ApiBase::PARAM_SENSITIVE => true,
254 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
255 ],
256 ];
257 }
258
259 protected function getExamplesMessages() {
260 return [
261 'action=login&lgname=user&lgpassword=password'
262 => 'apihelp-login-example-gettoken',
263 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
264 => 'apihelp-login-example-login',
265 ];
266 }
267
268 public function getHelpUrls() {
269 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login';
270 }
271
272 /**
273 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
274 * @param AuthenticationResponse $response
275 * @return array
276 */
277 protected function getAuthenticationResponseLogData( AuthenticationResponse $response ) {
278 $ret = [
279 'status' => $response->status,
280 ];
281 if ( $response->message ) {
282 $ret['message'] = $response->message->inLanguage( 'en' )->plain();
283 };
284 $reqs = [
285 'neededRequests' => $response->neededRequests,
286 'createRequest' => $response->createRequest,
287 'linkRequest' => $response->linkRequest,
288 ];
289 foreach ( $reqs as $k => $v ) {
290 if ( $v ) {
291 $v = is_array( $v ) ? $v : [ $v ];
292 $reqClasses = array_unique( array_map( 'get_class', $v ) );
293 sort( $reqClasses );
294 $ret[$k] = implode( ', ', $reqClasses );
295 }
296 }
297 return $ret;
298 }
299 }