Merge "Document nodata for HTMLFormFields"
[lhc/web/wiklou.git] / includes / api / ApiLogin.php
1 <?php
2 /**
3 * Copyright © 2006-2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
4 * Daniel Cannon (cannon dot danielc at gmail dot com)
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 use MediaWiki\Auth\AuthManager;
25 use MediaWiki\Auth\AuthenticationRequest;
26 use MediaWiki\Auth\AuthenticationResponse;
27 use MediaWiki\Logger\LoggerFactory;
28
29 /**
30 * Unit to authenticate log-in attempts to the current wiki.
31 *
32 * @ingroup API
33 */
34 class ApiLogin extends ApiBase {
35
36 public function __construct( ApiMain $main, $action ) {
37 parent::__construct( $main, $action, 'lg' );
38 }
39
40 protected function getExtendedDescription() {
41 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
42 return 'apihelp-login-extended-description';
43 } else {
44 return 'apihelp-login-extended-description-nobotpasswords';
45 }
46 }
47
48 /**
49 * Format a message for the response
50 * @param Message|string|array $message
51 * @return string|array
52 */
53 private function formatMessage( $message ) {
54 $message = Message::newFromSpecifier( $message );
55 $errorFormatter = $this->getErrorFormatter();
56 if ( $errorFormatter instanceof ApiErrorFormatter_BackCompat ) {
57 return ApiErrorFormatter::stripMarkup(
58 $message->useDatabase( false )->inLanguage( 'en' )->text()
59 );
60 } else {
61 return $errorFormatter->formatMessage( $message );
62 }
63 }
64
65 /**
66 * Executes the log-in attempt using the parameters passed. If
67 * the log-in succeeds, it attaches a cookie to the session
68 * and outputs the user id, username, and session token. If a
69 * log-in fails, as the result of a bad password, a nonexistent
70 * user, or any other reason, the host is cached with an expiry
71 * and no log-in attempts will be accepted until that expiry
72 * is reached. The expiry is $this->mLoginThrottle.
73 */
74 public function execute() {
75 // If we're in a mode that breaks the same-origin policy, no tokens can
76 // be obtained
77 if ( $this->lacksSameOriginSecurity() ) {
78 $this->getResult()->addValue( null, 'login', [
79 'result' => 'Aborted',
80 'reason' => $this->formatMessage( 'api-login-fail-sameorigin' ),
81 ] );
82
83 return;
84 }
85
86 $this->requirePostedParameters( [ 'password', 'token' ] );
87
88 $params = $this->extractRequestParams();
89
90 $result = [];
91
92 // Make sure session is persisted
93 $session = MediaWiki\Session\SessionManager::getGlobalSession();
94 $session->persist();
95
96 // Make sure it's possible to log in
97 if ( !$session->canSetUser() ) {
98 $this->getResult()->addValue( null, 'login', [
99 'result' => 'Aborted',
100 'reason' => $this->formatMessage( [
101 'api-login-fail-badsessionprovider',
102 $session->getProvider()->describe( $this->getErrorFormatter()->getLanguage() ),
103 ] )
104 ] );
105
106 return;
107 }
108
109 $authRes = false;
110 $context = new DerivativeContext( $this->getContext() );
111 $loginType = 'N/A';
112
113 // Check login token
114 $token = $session->getToken( '', 'login' );
115 if ( $token->wasNew() || !$params['token'] ) {
116 $authRes = 'NeedToken';
117 } elseif ( !$token->match( $params['token'] ) ) {
118 $authRes = 'WrongToken';
119 }
120
121 // Try bot passwords
122 if (
123 $authRes === false && $this->getConfig()->get( 'EnableBotPasswords' ) &&
124 ( $botLoginData = BotPassword::canonicalizeLoginData( $params['name'], $params['password'] ) )
125 ) {
126 $status = BotPassword::login(
127 $botLoginData[0], $botLoginData[1], $this->getRequest()
128 );
129 if ( $status->isOK() ) {
130 $session = $status->getValue();
131 $authRes = 'Success';
132 $loginType = 'BotPassword';
133 } elseif ( !$botLoginData[2] ||
134 $status->hasMessage( 'login-throttled' ) ||
135 $status->hasMessage( 'botpasswords-needs-reset' )
136 ) {
137 $authRes = 'Failed';
138 $message = $status->getMessage();
139 LoggerFactory::getInstance( 'authentication' )->info(
140 'BotPassword login failed: ' . $status->getWikiText( false, false, 'en' )
141 );
142 }
143 }
144
145 if ( $authRes === false ) {
146 // Simplified AuthManager login, for backwards compatibility
147 $manager = AuthManager::singleton();
148 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
149 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN, $this->getUser() ),
150 [
151 'username' => $params['name'],
152 'password' => $params['password'],
153 'domain' => $params['domain'],
154 'rememberMe' => true,
155 ]
156 );
157 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
158 switch ( $res->status ) {
159 case AuthenticationResponse::PASS:
160 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
161 $this->addDeprecation( 'apiwarn-deprecation-login-botpw', 'main-account-login' );
162 } else {
163 $this->addDeprecation( 'apiwarn-deprecation-login-nobotpw', 'main-account-login' );
164 }
165 $authRes = 'Success';
166 $loginType = 'AuthManager';
167 break;
168
169 case AuthenticationResponse::FAIL:
170 // Hope it's not a PreAuthenticationProvider that failed...
171 $authRes = 'Failed';
172 $message = $res->message;
173 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
174 ->info( __METHOD__ . ': Authentication failed: '
175 . $message->inLanguage( 'en' )->plain() );
176 break;
177
178 default:
179 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
180 ->info( __METHOD__ . ': Authentication failed due to unsupported response type: '
181 . $res->status, $this->getAuthenticationResponseLogData( $res ) );
182 $authRes = 'Aborted';
183 break;
184 }
185 }
186
187 $result['result'] = $authRes;
188 switch ( $authRes ) {
189 case 'Success':
190 $user = $session->getUser();
191
192 ApiQueryInfo::resetTokenCache();
193
194 // Deprecated hook
195 $injected_html = '';
196 Hooks::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
197
198 $result['lguserid'] = intval( $user->getId() );
199 $result['lgusername'] = $user->getName();
200 break;
201
202 case 'NeedToken':
203 $result['token'] = $token->toString();
204 $this->addDeprecation( 'apiwarn-deprecation-login-token', 'action=login&!lgtoken' );
205 break;
206
207 case 'WrongToken':
208 break;
209
210 case 'Failed':
211 $result['reason'] = $this->formatMessage( $message );
212 break;
213
214 case 'Aborted':
215 $result['reason'] = $this->formatMessage(
216 $this->getConfig()->get( 'EnableBotPasswords' )
217 ? 'api-login-fail-aborted'
218 : 'api-login-fail-aborted-nobotpw'
219 );
220 break;
221
222 default:
223 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
224 }
225
226 $this->getResult()->addValue( null, 'login', $result );
227
228 if ( $loginType === 'LoginForm' && isset( LoginForm::$statusCodes[$authRes] ) ) {
229 $authRes = LoginForm::$statusCodes[$authRes];
230 }
231 LoggerFactory::getInstance( 'authevents' )->info( 'Login attempt', [
232 'event' => 'login',
233 'successful' => $authRes === 'Success',
234 'loginType' => $loginType,
235 'status' => $authRes,
236 ] );
237 }
238
239 public function isDeprecated() {
240 return !$this->getConfig()->get( 'EnableBotPasswords' );
241 }
242
243 public function mustBePosted() {
244 return true;
245 }
246
247 public function isReadMode() {
248 return false;
249 }
250
251 public function getAllowedParams() {
252 return [
253 'name' => null,
254 'password' => [
255 ApiBase::PARAM_TYPE => 'password',
256 ],
257 'domain' => null,
258 'token' => [
259 ApiBase::PARAM_TYPE => 'string',
260 ApiBase::PARAM_REQUIRED => false, // for BC
261 ApiBase::PARAM_SENSITIVE => true,
262 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
263 ],
264 ];
265 }
266
267 protected function getExamplesMessages() {
268 return [
269 'action=login&lgname=user&lgpassword=password'
270 => 'apihelp-login-example-gettoken',
271 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
272 => 'apihelp-login-example-login',
273 ];
274 }
275
276 public function getHelpUrls() {
277 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login';
278 }
279
280 /**
281 * Turns an AuthenticationResponse into a hash suitable for passing to Logger
282 * @param AuthenticationResponse $response
283 * @return array
284 */
285 protected function getAuthenticationResponseLogData( AuthenticationResponse $response ) {
286 $ret = [
287 'status' => $response->status,
288 ];
289 if ( $response->message ) {
290 $ret['message'] = $response->message->inLanguage( 'en' )->plain();
291 };
292 $reqs = [
293 'neededRequests' => $response->neededRequests,
294 'createRequest' => $response->createRequest,
295 'linkRequest' => $response->linkRequest,
296 ];
297 foreach ( $reqs as $k => $v ) {
298 if ( $v ) {
299 $v = is_array( $v ) ? $v : [ $v ];
300 $reqClasses = array_unique( array_map( 'get_class', $v ) );
301 sort( $reqClasses );
302 $ret[$k] = implode( ', ', $reqClasses );
303 }
304 }
305 return $ret;
306 }
307 }