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
22 * Utility class for bot passwords
25 class BotPassword
implements IDBAccessObject
{
27 const APPID_MAXLENGTH
= 32;
41 /** @var MWRestrictions */
42 private $restrictions;
48 private $flags = self
::READ_NORMAL
;
51 * @param object $row bot_passwords database row
52 * @param bool $isSaved Whether the bot password was read from the database
53 * @param int $flags IDBAccessObject read flags
55 protected function __construct( $row, $isSaved, $flags = self
::READ_NORMAL
) {
56 $this->isSaved
= $isSaved;
57 $this->flags
= $flags;
59 $this->centralId
= (int)$row->bp_user
;
60 $this->appId
= $row->bp_app_id
;
61 $this->token
= $row->bp_token
;
62 $this->restrictions
= MWRestrictions
::newFromJson( $row->bp_restrictions
);
63 $this->grants
= FormatJson
::decode( $row->bp_grants
);
67 * Get a database connection for the bot passwords database
68 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_SLAVE.
69 * @return DatabaseBase
71 public static function getDB( $db ) {
72 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
74 $lb = $wgBotPasswordsCluster
75 ?
wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
76 : wfGetLB( $wgBotPasswordsDatabase );
77 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
81 * Load a BotPassword from the database
83 * @param string $appId
84 * @param int $flags IDBAccessObject read flags
85 * @return BotPassword|null
87 public static function newFromUser( User
$user, $appId, $flags = self
::READ_NORMAL
) {
88 $centralId = CentralIdLookup
::factory()->centralIdFromLocalUser(
89 $user, CentralIdLookup
::AUDIENCE_RAW
, $flags
91 return $centralId ? self
::newFromCentralId( $centralId, $appId, $flags ) : null;
95 * Load a BotPassword from the database
96 * @param int $centralId from CentralIdLookup
97 * @param string $appId
98 * @param int $flags IDBAccessObject read flags
99 * @return BotPassword|null
101 public static function newFromCentralId( $centralId, $appId, $flags = self
::READ_NORMAL
) {
102 global $wgEnableBotPasswords;
104 if ( !$wgEnableBotPasswords ) {
108 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
109 $db = self
::getDB( $index );
110 $row = $db->selectRow(
112 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
113 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
117 return $row ?
new self( $row, true, $flags ) : null;
121 * Create an unsaved BotPassword
122 * @param array $data Data to use to create the bot password. Keys are:
123 * - user: (User) User object to create the password for. Overrides username and centralId.
124 * - username: (string) Username to create the password for. Overrides centralId.
125 * - centralId: (int) User central ID to create the password for.
126 * - appId: (string) App ID for the password.
127 * - restrictions: (MWRestrictions, optional) Restrictions.
128 * - grants: (string[], optional) Grants.
129 * @param int $flags IDBAccessObject read flags
130 * @return BotPassword|null
132 public static function newUnsaved( array $data, $flags = self
::READ_NORMAL
) {
135 'bp_app_id' => isset( $data['appId'] ) ?
trim( $data['appId'] ) : '',
136 'bp_token' => '**unsaved**',
137 'bp_restrictions' => isset( $data['restrictions'] )
138 ?
$data['restrictions']
139 : MWRestrictions
::newDefault(),
140 'bp_grants' => isset( $data['grants'] ) ?
$data['grants'] : [],
144 $row->bp_app_id
=== '' ||
strlen( $row->bp_app_id
) > self
::APPID_MAXLENGTH ||
145 !$row->bp_restrictions
instanceof MWRestrictions ||
146 !is_array( $row->bp_grants
)
151 $row->bp_restrictions
= $row->bp_restrictions
->toJson();
152 $row->bp_grants
= FormatJson
::encode( $row->bp_grants
);
154 if ( isset( $data['user'] ) ) {
155 if ( !$data['user'] instanceof User
) {
158 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromLocalUser(
159 $data['user'], CentralIdLookup
::AUDIENCE_RAW
, $flags
161 } elseif ( isset( $data['username'] ) ) {
162 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromName(
163 $data['username'], CentralIdLookup
::AUDIENCE_RAW
, $flags
165 } elseif ( isset( $data['centralId'] ) ) {
166 $row->bp_user
= $data['centralId'];
168 if ( !$row->bp_user
) {
172 return new self( $row, false, $flags );
176 * Indicate whether this is known to be saved
179 public function isSaved() {
180 return $this->isSaved
;
184 * Get the central user ID
187 public function getUserCentralId() {
188 return $this->centralId
;
195 public function getAppId() {
203 public function getToken() {
208 * Get the restrictions
209 * @return MWRestrictions
211 public function getRestrictions() {
212 return $this->restrictions
;
219 public function getGrants() {
220 return $this->grants
;
224 * Get the separator for combined user name + app ID
227 public static function getSeparator() {
228 global $wgUserrightsInterwikiDelimiter;
229 return $wgUserrightsInterwikiDelimiter;
236 protected function getPassword() {
237 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->flags
);
238 $db = self
::getDB( $index );
239 $password = $db->selectField(
242 [ 'bp_user' => $this->centralId
, 'bp_app_id' => $this->appId
],
246 if ( $password === false ) {
247 return PasswordFactory
::newInvalidPassword();
250 $passwordFactory = new \
PasswordFactory();
251 $passwordFactory->init( \RequestContext
::getMain()->getConfig() );
253 return $passwordFactory->newFromCiphertext( $password );
254 } catch ( PasswordError
$ex ) {
255 return PasswordFactory
::newInvalidPassword();
260 * Save the BotPassword to the database
261 * @param string $operation 'update' or 'insert'
262 * @param Password|null $password Password to set.
263 * @return bool Success
265 public function save( $operation, Password
$password = null ) {
267 'bp_user' => $this->centralId
,
268 'bp_app_id' => $this->appId
,
271 'bp_token' => MWCryptRand
::generateHex( User
::TOKEN_LENGTH
),
272 'bp_restrictions' => $this->restrictions
->toJson(),
273 'bp_grants' => FormatJson
::encode( $this->grants
),
276 if ( $password !== null ) {
277 $fields['bp_password'] = $password->toString();
278 } elseif ( $operation === 'insert' ) {
279 $fields['bp_password'] = PasswordFactory
::newInvalidPassword()->toString();
282 $dbw = self
::getDB( DB_MASTER
);
283 switch ( $operation ) {
285 $dbw->insert( 'bot_passwords', $fields +
$conds, __METHOD__
, [ 'IGNORE' ] );
289 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__
);
295 $ok = (bool)$dbw->affectedRows();
297 $this->token
= $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__
);
298 $this->isSaved
= true;
304 * Delete the BotPassword from the database
305 * @return bool Success
307 public function delete() {
309 'bp_user' => $this->centralId
,
310 'bp_app_id' => $this->appId
,
312 $dbw = self
::getDB( DB_MASTER
);
313 $dbw->delete( 'bot_passwords', $conds, __METHOD__
);
314 $ok = (bool)$dbw->affectedRows();
316 $this->token
= '**unsaved**';
317 $this->isSaved
= false;
323 * Invalidate all passwords for a user, by name
324 * @param string $username User name
325 * @return bool Whether any passwords were invalidated
327 public static function invalidateAllPasswordsForUser( $username ) {
328 $centralId = CentralIdLookup
::factory()->centralIdFromName(
329 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
331 return $centralId && self
::invalidateAllPasswordsForCentralId( $centralId );
335 * Invalidate all passwords for a user, by central ID
336 * @param int $centralId
337 * @return bool Whether any passwords were invalidated
339 public static function invalidateAllPasswordsForCentralId( $centralId ) {
340 global $wgEnableBotPasswords;
342 if ( !$wgEnableBotPasswords ) {
346 $dbw = self
::getDB( DB_MASTER
);
349 [ 'bp_password' => PasswordFactory
::newInvalidPassword()->toString() ],
350 [ 'bp_user' => $centralId ],
353 return (bool)$dbw->affectedRows();
357 * Remove all passwords for a user, by name
358 * @param string $username User name
359 * @return bool Whether any passwords were removed
361 public static function removeAllPasswordsForUser( $username ) {
362 $centralId = CentralIdLookup
::factory()->centralIdFromName(
363 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
365 return $centralId && self
::removeAllPasswordsForCentralId( $centralId );
369 * Remove all passwords for a user, by central ID
370 * @param int $centralId
371 * @return bool Whether any passwords were removed
373 public static function removeAllPasswordsForCentralId( $centralId ) {
374 global $wgEnableBotPasswords;
376 if ( !$wgEnableBotPasswords ) {
380 $dbw = self
::getDB( DB_MASTER
);
383 [ 'bp_user' => $centralId ],
386 return (bool)$dbw->affectedRows();
390 * Try to log the user in
391 * @param string $username Combined user name and app ID
392 * @param string $password Supplied password
393 * @param WebRequest $request
394 * @return Status On success, the good status's value is the new Session object
396 public static function login( $username, $password, WebRequest
$request ) {
397 global $wgEnableBotPasswords;
399 if ( !$wgEnableBotPasswords ) {
400 return Status
::newFatal( 'botpasswords-disabled' );
403 $manager = MediaWiki\Session\SessionManager
::singleton();
404 $provider = $manager->getProvider(
405 'MediaWiki\\Session\\BotPasswordSessionProvider'
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 );
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 ) );