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