Fix ApiBase::getErrorFromStatus() and ApiMessages
[mediawiki.git] / includes / user / BotPassword.php
blob49a71633c7f3ef89fdd60838f734f9cf6dd47982
1 <?php
2 /**
3 * Utility class for bot passwords
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Session\BotPasswordSessionProvider;
23 /**
24 * Utility class for bot passwords
25 * @since 1.27
27 class BotPassword implements IDBAccessObject {
29 const APPID_MAXLENGTH = 32;
31 /** @var bool */
32 private $isSaved;
34 /** @var int */
35 private $centralId;
37 /** @var string */
38 private $appId;
40 /** @var string */
41 private $token;
43 /** @var MWRestrictions */
44 private $restrictions;
46 /** @var string[] */
47 private $grants;
49 /** @var int */
50 private $flags = self::READ_NORMAL;
52 /**
53 * @param object $row bot_passwords database row
54 * @param bool $isSaved Whether the bot password was read from the database
55 * @param int $flags IDBAccessObject read flags
57 protected function __construct( $row, $isSaved, $flags = self::READ_NORMAL ) {
58 $this->isSaved = $isSaved;
59 $this->flags = $flags;
61 $this->centralId = (int)$row->bp_user;
62 $this->appId = $row->bp_app_id;
63 $this->token = $row->bp_token;
64 $this->restrictions = MWRestrictions::newFromJson( $row->bp_restrictions );
65 $this->grants = FormatJson::decode( $row->bp_grants );
68 /**
69 * Get a database connection for the bot passwords database
70 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_SLAVE.
71 * @return DatabaseBase
73 public static function getDB( $db ) {
74 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
76 $lb = $wgBotPasswordsCluster
77 ? wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
78 : wfGetLB( $wgBotPasswordsDatabase );
79 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
82 /**
83 * Load a BotPassword from the database
84 * @param User $user
85 * @param string $appId
86 * @param int $flags IDBAccessObject read flags
87 * @return BotPassword|null
89 public static function newFromUser( User $user, $appId, $flags = self::READ_NORMAL ) {
90 $centralId = CentralIdLookup::factory()->centralIdFromLocalUser(
91 $user, CentralIdLookup::AUDIENCE_RAW, $flags
93 return $centralId ? self::newFromCentralId( $centralId, $appId, $flags ) : null;
96 /**
97 * Load a BotPassword from the database
98 * @param int $centralId from CentralIdLookup
99 * @param string $appId
100 * @param int $flags IDBAccessObject read flags
101 * @return BotPassword|null
103 public static function newFromCentralId( $centralId, $appId, $flags = self::READ_NORMAL ) {
104 global $wgEnableBotPasswords;
106 if ( !$wgEnableBotPasswords ) {
107 return null;
110 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
111 $db = self::getDB( $index );
112 $row = $db->selectRow(
113 'bot_passwords',
114 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
115 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
116 __METHOD__,
117 $options
119 return $row ? new self( $row, true, $flags ) : null;
123 * Create an unsaved BotPassword
124 * @param array $data Data to use to create the bot password. Keys are:
125 * - user: (User) User object to create the password for. Overrides username and centralId.
126 * - username: (string) Username to create the password for. Overrides centralId.
127 * - centralId: (int) User central ID to create the password for.
128 * - appId: (string) App ID for the password.
129 * - restrictions: (MWRestrictions, optional) Restrictions.
130 * - grants: (string[], optional) Grants.
131 * @param int $flags IDBAccessObject read flags
132 * @return BotPassword|null
134 public static function newUnsaved( array $data, $flags = self::READ_NORMAL ) {
135 $row = (object)[
136 'bp_user' => 0,
137 'bp_app_id' => isset( $data['appId'] ) ? trim( $data['appId'] ) : '',
138 'bp_token' => '**unsaved**',
139 'bp_restrictions' => isset( $data['restrictions'] )
140 ? $data['restrictions']
141 : MWRestrictions::newDefault(),
142 'bp_grants' => isset( $data['grants'] ) ? $data['grants'] : [],
145 if (
146 $row->bp_app_id === '' || strlen( $row->bp_app_id ) > self::APPID_MAXLENGTH ||
147 !$row->bp_restrictions instanceof MWRestrictions ||
148 !is_array( $row->bp_grants )
150 return null;
153 $row->bp_restrictions = $row->bp_restrictions->toJson();
154 $row->bp_grants = FormatJson::encode( $row->bp_grants );
156 if ( isset( $data['user'] ) ) {
157 if ( !$data['user'] instanceof User ) {
158 return null;
160 $row->bp_user = CentralIdLookup::factory()->centralIdFromLocalUser(
161 $data['user'], CentralIdLookup::AUDIENCE_RAW, $flags
163 } elseif ( isset( $data['username'] ) ) {
164 $row->bp_user = CentralIdLookup::factory()->centralIdFromName(
165 $data['username'], CentralIdLookup::AUDIENCE_RAW, $flags
167 } elseif ( isset( $data['centralId'] ) ) {
168 $row->bp_user = $data['centralId'];
170 if ( !$row->bp_user ) {
171 return null;
174 return new self( $row, false, $flags );
178 * Indicate whether this is known to be saved
179 * @return bool
181 public function isSaved() {
182 return $this->isSaved;
186 * Get the central user ID
187 * @return int
189 public function getUserCentralId() {
190 return $this->centralId;
194 * Get the app ID
195 * @return string
197 public function getAppId() {
198 return $this->appId;
202 * Get the token
203 * @return string
205 public function getToken() {
206 return $this->token;
210 * Get the restrictions
211 * @return MWRestrictions
213 public function getRestrictions() {
214 return $this->restrictions;
218 * Get the grants
219 * @return string[]
221 public function getGrants() {
222 return $this->grants;
226 * Get the separator for combined user name + app ID
227 * @return string
229 public static function getSeparator() {
230 global $wgUserrightsInterwikiDelimiter;
231 return $wgUserrightsInterwikiDelimiter;
235 * Get the password
236 * @return Password
238 protected function getPassword() {
239 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->flags );
240 $db = self::getDB( $index );
241 $password = $db->selectField(
242 'bot_passwords',
243 'bp_password',
244 [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ],
245 __METHOD__,
246 $options
248 if ( $password === false ) {
249 return PasswordFactory::newInvalidPassword();
252 $passwordFactory = new \PasswordFactory();
253 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
254 try {
255 return $passwordFactory->newFromCiphertext( $password );
256 } catch ( PasswordError $ex ) {
257 return PasswordFactory::newInvalidPassword();
262 * Save the BotPassword to the database
263 * @param string $operation 'update' or 'insert'
264 * @param Password|null $password Password to set.
265 * @return bool Success
267 public function save( $operation, Password $password = null ) {
268 $conds = [
269 'bp_user' => $this->centralId,
270 'bp_app_id' => $this->appId,
272 $fields = [
273 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
274 'bp_restrictions' => $this->restrictions->toJson(),
275 'bp_grants' => FormatJson::encode( $this->grants ),
278 if ( $password !== null ) {
279 $fields['bp_password'] = $password->toString();
280 } elseif ( $operation === 'insert' ) {
281 $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
284 $dbw = self::getDB( DB_MASTER );
285 switch ( $operation ) {
286 case 'insert':
287 $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
288 break;
290 case 'update':
291 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
292 break;
294 default:
295 return false;
297 $ok = (bool)$dbw->affectedRows();
298 if ( $ok ) {
299 $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
300 $this->isSaved = true;
302 return $ok;
306 * Delete the BotPassword from the database
307 * @return bool Success
309 public function delete() {
310 $conds = [
311 'bp_user' => $this->centralId,
312 'bp_app_id' => $this->appId,
314 $dbw = self::getDB( DB_MASTER );
315 $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
316 $ok = (bool)$dbw->affectedRows();
317 if ( $ok ) {
318 $this->token = '**unsaved**';
319 $this->isSaved = false;
321 return $ok;
325 * Invalidate all passwords for a user, by name
326 * @param string $username User name
327 * @return bool Whether any passwords were invalidated
329 public static function invalidateAllPasswordsForUser( $username ) {
330 $centralId = CentralIdLookup::factory()->centralIdFromName(
331 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
333 return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
337 * Invalidate all passwords for a user, by central ID
338 * @param int $centralId
339 * @return bool Whether any passwords were invalidated
341 public static function invalidateAllPasswordsForCentralId( $centralId ) {
342 global $wgEnableBotPasswords;
344 if ( !$wgEnableBotPasswords ) {
345 return false;
348 $dbw = self::getDB( DB_MASTER );
349 $dbw->update(
350 'bot_passwords',
351 [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
352 [ 'bp_user' => $centralId ],
353 __METHOD__
355 return (bool)$dbw->affectedRows();
359 * Remove all passwords for a user, by name
360 * @param string $username User name
361 * @return bool Whether any passwords were removed
363 public static function removeAllPasswordsForUser( $username ) {
364 $centralId = CentralIdLookup::factory()->centralIdFromName(
365 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
367 return $centralId && self::removeAllPasswordsForCentralId( $centralId );
371 * Remove all passwords for a user, by central ID
372 * @param int $centralId
373 * @return bool Whether any passwords were removed
375 public static function removeAllPasswordsForCentralId( $centralId ) {
376 global $wgEnableBotPasswords;
378 if ( !$wgEnableBotPasswords ) {
379 return false;
382 $dbw = self::getDB( DB_MASTER );
383 $dbw->delete(
384 'bot_passwords',
385 [ 'bp_user' => $centralId ],
386 __METHOD__
388 return (bool)$dbw->affectedRows();
392 * Try to log the user in
393 * @param string $username Combined user name and app ID
394 * @param string $password Supplied password
395 * @param WebRequest $request
396 * @return Status On success, the good status's value is the new Session object
398 public static function login( $username, $password, WebRequest $request ) {
399 global $wgEnableBotPasswords;
401 if ( !$wgEnableBotPasswords ) {
402 return Status::newFatal( 'botpasswords-disabled' );
405 $manager = MediaWiki\Session\SessionManager::singleton();
406 $provider = $manager->getProvider( BotPasswordSessionProvider::class );
407 if ( !$provider ) {
408 return Status::newFatal( 'botpasswords-no-provider' );
411 // Split name into name+appId
412 $sep = self::getSeparator();
413 if ( strpos( $username, $sep ) === false ) {
414 return Status::newFatal( 'botpasswords-invalid-name', $sep );
416 list( $name, $appId ) = explode( $sep, $username, 2 );
418 // Find the named user
419 $user = User::newFromName( $name );
420 if ( !$user || $user->isAnon() ) {
421 return Status::newFatal( 'nosuchuser', $name );
424 // Get the bot password
425 $bp = self::newFromUser( $user, $appId );
426 if ( !$bp ) {
427 return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
430 // Check restrictions
431 $status = $bp->getRestrictions()->check( $request );
432 if ( !$status->isOK() ) {
433 return Status::newFatal( 'botpasswords-restriction-failed' );
436 // Check the password
437 if ( !$bp->getPassword()->equals( $password ) ) {
438 return Status::newFatal( 'wrongpassword' );
441 // Ok! Create the session.
442 return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );