Merge "momentjs: Hack around bug in node/browser compat wrapper in locale files"
[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 try {
74 $this->requirePostedParameters( [ 'password', 'token' ] );
75 } catch ( UsageException $ex ) {
76 // Make this a warning for now, upgrade to an error in 1.29.
77 $this->setWarning( $ex->getMessage() );
78 $this->logFeatureUsage( 'login-params-in-query-string' );
79 }
80
81 $params = $this->extractRequestParams();
82
83 $result = [];
84
85 // Make sure session is persisted
86 $session = MediaWiki\Session\SessionManager::getGlobalSession();
87 $session->persist();
88
89 // Make sure it's possible to log in
90 if ( !$session->canSetUser() ) {
91 $this->getResult()->addValue( null, 'login', [
92 'result' => 'Aborted',
93 'reason' => 'Cannot log in when using ' .
94 $session->getProvider()->describe( Language::factory( 'en' ) ),
95 ] );
96
97 return;
98 }
99
100 $authRes = false;
101 $context = new DerivativeContext( $this->getContext() );
102 $loginType = 'N/A';
103
104 // Check login token
105 $token = $session->getToken( '', 'login' );
106 if ( $token->wasNew() || !$params['token'] ) {
107 $authRes = 'NeedToken';
108 } elseif ( !$token->match( $params['token'] ) ) {
109 $authRes = 'WrongToken';
110 }
111
112 // Try bot passwords
113 if (
114 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
115 ( $botLoginData = BotPassword::canonicalizeLoginData( $params['name'], $params['password'] ) )
116 ) {
117 $status = BotPassword::login(
118 $botLoginData[0], $botLoginData[1], $this->getRequest()
119 );
120 if ( $status->isOK() ) {
121 $session = $status->getValue();
122 $authRes = 'Success';
123 $loginType = 'BotPassword';
124 } elseif ( !$botLoginData[2] ) {
125 $authRes = 'Failed';
126 $message = $status->getMessage();
127 LoggerFactory::getInstance( 'authentication' )->info(
128 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
129 );
130 }
131 }
132
133 if ( $authRes === false ) {
134 // Simplified AuthManager login, for backwards compatibility
135 $manager = AuthManager::singleton();
136 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
137 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN, $this->getUser() ),
138 [
139 'username' => $params['name'],
140 'password' => $params['password'],
141 'domain' => $params['domain'],
142 'rememberMe' => true,
143 ]
144 );
145 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
146 switch ( $res->status ) {
147 case AuthenticationResponse::PASS:
148 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
149 $warn = 'Main-account login via action=login is deprecated and may stop working ' .
150 'without warning.';
151 $warn .= ' To continue login with action=login, see [[Special:BotPasswords]].';
152 $warn .= ' To safely continue using main-account login, see action=clientlogin.';
153 } else {
154 $warn = 'Login via action=login is deprecated and may stop working without warning.';
155 $warn .= ' To safely log in, see action=clientlogin.';
156 }
157 $this->setWarning( $warn );
158 $authRes = 'Success';
159 $loginType = 'AuthManager';
160 break;
161
162 case AuthenticationResponse::FAIL:
163 // Hope it's not a PreAuthenticationProvider that failed...
164 $authRes = 'Failed';
165 $message = $res->message;
166 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
167 ->info( __METHOD__ . ': Authentication failed: '
168 . $message->inLanguage( 'en' )->plain() );
169 break;
170
171 default:
172 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
173 ->info( __METHOD__ . ': Authentication failed due to unsupported response type: '
174 . $res->status, $this->getAuthenticationResponseLogData( $res ) );
175 $authRes = 'Aborted';
176 break;
177 }
178 }
179
180 $result['result'] = $authRes;
181 switch ( $authRes ) {
182 case 'Success':
183 $user = $session->getUser();
184
185 ApiQueryInfo::resetTokenCache();
186
187 // Deprecated hook
188 $injected_html = '';
189 Hooks::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
190
191 $result['lguserid'] = intval( $user->getId() );
192 $result['lgusername'] = $user->getName();
193
194 // @todo: These are deprecated, and should be removed at some
195 // point (1.28 at the earliest, and see T121527). They were ok
196 // when the core cookie-based login was the only thing, but
197 // CentralAuth broke that a while back and
198 // SessionManager/AuthManager *really* break it.
199 $result['lgtoken'] = $user->getToken();
200 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
201 $result['sessionid'] = $session->getId();
202 break;
203
204 case 'NeedToken':
205 $result['token'] = $token->toString();
206 $this->setWarning( 'Fetching a token via action=login is deprecated. ' .
207 'Use action=query&meta=tokens&type=login instead.' );
208 $this->logFeatureUsage( 'action=login&!lgtoken' );
209
210 // @todo: See above about deprecation
211 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
212 $result['sessionid'] = $session->getId();
213 break;
214
215 case 'WrongToken':
216 break;
217
218 case 'Failed':
219 $result['reason'] = $message->useDatabase( 'false' )->inLanguage( 'en' )->text();
220 break;
221
222 case 'Aborted':
223 $result['reason'] = 'Authentication requires user interaction, ' .
224 'which is not supported by action=login.';
225 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
226 $result['reason'] .= ' To be able to login with action=login, see [[Special:BotPasswords]].';
227 $result['reason'] .= ' To continue using main-account login, see action=clientlogin.';
228 } else {
229 $result['reason'] .= ' To log in, see action=clientlogin.';
230 }
231 break;
232
233 default:
234 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
235 }
236
237 $this->getResult()->addValue( null, 'login', $result );
238
239 if ( $loginType === 'LoginForm' && isset( LoginForm::$statusCodes[$authRes] ) ) {
240 $authRes = LoginForm::$statusCodes[$authRes];
241 }
242 LoggerFactory::getInstance( 'authevents' )->info( 'Login attempt', [
243 'event' => 'login',
244 'successful' => $authRes === 'Success',
245 'loginType' => $loginType,
246 'status' => $authRes,
247 ] );
248 }
249
250 public function isDeprecated() {
251 return !$this->getConfig()->get( 'EnableBotPasswords' );
252 }
253
254 public function mustBePosted() {
255 return true;
256 }
257
258 public function isReadMode() {
259 return false;
260 }
261
262 public function getAllowedParams() {
263 return [
264 'name' => null,
265 'password' => [
266 ApiBase::PARAM_TYPE => 'password',
267 ],
268 'domain' => null,
269 'token' => [
270 ApiBase::PARAM_TYPE => 'string',
271 ApiBase::PARAM_REQUIRED => false, // for BC
272 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
273 ],
274 ];
275 }
276
277 protected function getExamplesMessages() {
278 return [
279 'action=login&lgname=user&lgpassword=password'
280 => 'apihelp-login-example-gettoken',
281 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
282 => 'apihelp-login-example-login',
283 ];
284 }
285
286 public function getHelpUrls() {
287 return 'https://www.mediawiki.org/wiki/API:Login';
288 }
289
290 /**
291 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
292 * @param AuthenticationResponse $response
293 * @return array
294 */
295 protected function getAuthenticationResponseLogData( AuthenticationResponse $response ) {
296 $ret = [
297 'status' => $response->status,
298 ];
299 if ( $response->message ) {
300 $ret['message'] = $response->message->inLanguage( 'en' )->plain();
301 };
302 $reqs = [
303 'neededRequests' => $response->neededRequests,
304 'createRequest' => $response->createRequest,
305 'linkRequest' => $response->linkRequest,
306 ];
307 foreach ( $reqs as $k => $v ) {
308 if ( $v ) {
309 $v = is_array( $v ) ? $v : [ $v ];
310 $reqClasses = array_unique( array_map( 'get_class', $v ) );
311 sort( $reqClasses );
312 $ret[$k] = implode( ', ', $reqClasses );
313 }
314 }
315 return $ret;
316 }
317 }