Merge "Beef up and generalize IDBAccessObject constants a bit"
[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( 'authmanager' )->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: ' . $message->plain() );
159 break;
160
161 default:
162 $authRes = 'Aborted';
163 break;
164 }
165 }
166
167 $result['result'] = $authRes;
168 switch ( $authRes ) {
169 case 'Success':
170 $user = $session->getUser();
171
172 ApiQueryInfo::resetTokenCache();
173
174 // Deprecated hook
175 $injected_html = '';
176 Hooks::run( 'UserLoginComplete', [ &$user, &$injected_html, true ] );
177
178 $result['lguserid'] = intval( $user->getId() );
179 $result['lgusername'] = $user->getName();
180
181 // @todo: These are deprecated, and should be removed at some
182 // point (1.28 at the earliest, and see T121527). They were ok
183 // when the core cookie-based login was the only thing, but
184 // CentralAuth broke that a while back and
185 // SessionManager/AuthManager *really* break it.
186 $result['lgtoken'] = $user->getToken();
187 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
188 $result['sessionid'] = $session->getId();
189 break;
190
191 case 'NeedToken':
192 $result['token'] = $token->toString();
193 $this->setWarning( 'Fetching a token via action=login is deprecated. ' .
194 'Use action=query&meta=tokens&type=login instead.' );
195 $this->logFeatureUsage( 'action=login&!lgtoken' );
196
197 // @todo: See above about deprecation
198 $result['cookieprefix'] = $this->getConfig()->get( 'CookiePrefix' );
199 $result['sessionid'] = $session->getId();
200 break;
201
202 case 'WrongToken':
203 break;
204
205 case 'Failed':
206 $result['reason'] = $message->useDatabase( 'false' )->inLanguage( 'en' )->text();
207 break;
208
209 case 'Aborted':
210 $result['reason'] = 'Authentication requires user interaction, ' .
211 'which is not supported by action=login.';
212 if ( $this->getConfig()->get( 'EnableBotPasswords' ) ) {
213 $result['reason'] .= ' To be able to login with action=login, see [[Special:BotPasswords]].';
214 $result['reason'] .= ' To continue using main-account login, see action=clientlogin.';
215 } else {
216 $result['reason'] .= ' To log in, see action=clientlogin.';
217 }
218 break;
219
220 default:
221 ApiBase::dieDebug( __METHOD__, "Unhandled case value: {$authRes}" );
222 }
223
224 $this->getResult()->addValue( null, 'login', $result );
225
226 if ( $loginType === 'LoginForm' && isset( LoginForm::$statusCodes[$authRes] ) ) {
227 $authRes = LoginForm::$statusCodes[$authRes];
228 }
229 LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', [
230 'event' => 'login',
231 'successful' => $authRes === 'Success',
232 'loginType' => $loginType,
233 'status' => $authRes,
234 ] );
235 }
236
237 public function isDeprecated() {
238 return !$this->getConfig()->get( 'EnableBotPasswords' );
239 }
240
241 public function mustBePosted() {
242 return true;
243 }
244
245 public function isReadMode() {
246 return false;
247 }
248
249 public function getAllowedParams() {
250 return [
251 'name' => null,
252 'password' => [
253 ApiBase::PARAM_TYPE => 'password',
254 ],
255 'domain' => null,
256 'token' => [
257 ApiBase::PARAM_TYPE => 'string',
258 ApiBase::PARAM_REQUIRED => false, // for BC
259 ApiBase::PARAM_HELP_MSG => [ 'api-help-param-token', 'login' ],
260 ],
261 ];
262 }
263
264 protected function getExamplesMessages() {
265 return [
266 'action=login&lgname=user&lgpassword=password'
267 => 'apihelp-login-example-gettoken',
268 'action=login&lgname=user&lgpassword=password&lgtoken=123ABC'
269 => 'apihelp-login-example-login',
270 ];
271 }
272
273 public function getHelpUrls() {
274 return 'https://www.mediawiki.org/wiki/API:Login';
275 }
276 }