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
;
22 use MediaWiki\Session\SessionInfo
;
25 * Utility class for bot passwords
28 class BotPassword
implements IDBAccessObject
{
30 const APPID_MAXLENGTH
= 32;
44 /** @var MWRestrictions */
45 private $restrictions;
51 private $flags = self
::READ_NORMAL
;
54 * @param object $row bot_passwords database row
55 * @param bool $isSaved Whether the bot password was read from the database
56 * @param int $flags IDBAccessObject read flags
58 protected function __construct( $row, $isSaved, $flags = self
::READ_NORMAL
) {
59 $this->isSaved
= $isSaved;
60 $this->flags
= $flags;
62 $this->centralId
= (int)$row->bp_user
;
63 $this->appId
= $row->bp_app_id
;
64 $this->token
= $row->bp_token
;
65 $this->restrictions
= MWRestrictions
::newFromJson( $row->bp_restrictions
);
66 $this->grants
= FormatJson
::decode( $row->bp_grants
);
70 * Get a database connection for the bot passwords database
71 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_SLAVE.
72 * @return DatabaseBase
74 public static function getDB( $db ) {
75 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
77 $lb = $wgBotPasswordsCluster
78 ?
wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
79 : wfGetLB( $wgBotPasswordsDatabase );
80 return $lb->getConnectionRef( $db, array(), $wgBotPasswordsDatabase );
84 * Load a BotPassword from the database
86 * @param string $appId
87 * @param int $flags IDBAccessObject read flags
88 * @return BotPassword|null
90 public static function newFromUser( User
$user, $appId, $flags = self
::READ_NORMAL
) {
91 $centralId = CentralIdLookup
::factory()->centralIdFromLocalUser(
92 $user, CentralIdLookup
::AUDIENCE_RAW
, $flags
94 return $centralId ? self
::newFromCentralId( $centralId, $appId, $flags ) : null;
98 * Load a BotPassword from the database
99 * @param int $centralId from CentralIdLookup
100 * @param string $appId
101 * @param int $flags IDBAccessObject read flags
102 * @return BotPassword|null
104 public static function newFromCentralId( $centralId, $appId, $flags = self
::READ_NORMAL
) {
105 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
106 $db = self
::getDB( $index );
107 $row = $db->selectRow(
109 array( 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ),
110 array( 'bp_user' => $centralId, 'bp_app_id' => $appId ),
114 return $row ?
new self( $row, true, $flags ) : null;
118 * Create an unsaved BotPassword
119 * @param array $data Data to use to create the bot password. Keys are:
120 * - user: (User) User object to create the password for. Overrides username and centralId.
121 * - username: (string) Username to create the password for. Overrides centralId.
122 * - centralId: (int) User central ID to create the password for.
123 * - appId: (string) App ID for the password.
124 * - restrictions: (MWRestrictions, optional) Restrictions.
125 * - grants: (string[], optional) Grants.
126 * @param int $flags IDBAccessObject read flags
127 * @return BotPassword|null
129 public static function newUnsaved( array $data, $flags = self
::READ_NORMAL
) {
130 $row = (object)array(
132 'bp_app_id' => isset( $data['appId'] ) ?
trim( $data['appId'] ) : '',
133 'bp_token' => '**unsaved**',
134 'bp_restrictions' => isset( $data['restrictions'] )
135 ?
$data['restrictions']
136 : MWRestrictions
::newDefault(),
137 'bp_grants' => isset( $data['grants'] ) ?
$data['grants'] : array(),
141 $row->bp_app_id
=== '' ||
strlen( $row->bp_app_id
) > self
::APPID_MAXLENGTH ||
142 !$row->bp_restrictions
instanceof MWRestrictions ||
143 !is_array( $row->bp_grants
)
148 $row->bp_restrictions
= $row->bp_restrictions
->toJson();
149 $row->bp_grants
= FormatJson
::encode( $row->bp_grants
);
151 if ( isset( $data['user'] ) ) {
152 if ( !$data['user'] instanceof User
) {
155 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromLocalUser(
156 $data['user'], CentralIdLookup
::AUDIENCE_RAW
, $flags
158 } elseif ( isset( $data['username'] ) ) {
159 $row->bp_user
= CentralIdLookup
::factory()->centralIdFromName(
160 $data['username'], CentralIdLookup
::AUDIENCE_RAW
, $flags
162 } elseif ( isset( $data['centralId'] ) ) {
163 $row->bp_user
= $data['centralId'];
165 if ( !$row->bp_user
) {
169 return new self( $row, false, $flags );
173 * Indicate whether this is known to be saved
176 public function isSaved() {
177 return $this->isSaved
;
181 * Get the central user ID
184 public function getUserCentralId() {
185 return $this->centralId
;
192 public function getAppId() {
200 public function getToken() {
205 * Get the restrictions
206 * @return MWRestrictions
208 public function getRestrictions() {
209 return $this->restrictions
;
216 public function getGrants() {
217 return $this->grants
;
221 * Get the separator for combined user name + app ID
224 public static function getSeparator() {
225 global $wgUserrightsInterwikiDelimiter;
226 return $wgUserrightsInterwikiDelimiter;
233 protected function getPassword() {
234 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->flags
);
235 $db = self
::getDB( $index );
236 $password = $db->selectField(
239 array( 'bp_user' => $this->centralId
, 'bp_app_id' => $this->appId
),
243 if ( $password === false ) {
244 return PasswordFactory
::newInvalidPassword();
247 $passwordFactory = new \
PasswordFactory();
248 $passwordFactory->init( \RequestContext
::getMain()->getConfig() );
250 return $passwordFactory->newFromCiphertext( $password );
251 } catch ( PasswordError
$ex ) {
252 return PasswordFactory
::newInvalidPassword();
257 * Save the BotPassword to the database
258 * @param string $operation 'update' or 'insert'
259 * @param Password|null $password Password to set.
260 * @return bool Success
262 public function save( $operation, Password
$password = null ) {
264 'bp_user' => $this->centralId
,
265 'bp_app_id' => $this->appId
,
268 'bp_token' => MWCryptRand
::generateHex( User
::TOKEN_LENGTH
),
269 'bp_restrictions' => $this->restrictions
->toJson(),
270 'bp_grants' => FormatJson
::encode( $this->grants
),
273 if ( $password !== null ) {
274 $fields['bp_password'] = $password->toString();
275 } elseif ( $operation === 'insert' ) {
276 $fields['bp_password'] = PasswordFactory
::newInvalidPassword()->toString();
279 $dbw = self
::getDB( DB_MASTER
);
280 switch ( $operation ) {
282 $dbw->insert( 'bot_passwords', $fields +
$conds, __METHOD__
, array( 'IGNORE' ) );
286 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__
);
292 $ok = (bool)$dbw->affectedRows();
294 $this->token
= $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__
);
295 $this->isSaved
= true;
301 * Delete the BotPassword from the database
302 * @return bool Success
304 public function delete() {
306 'bp_user' => $this->centralId
,
307 'bp_app_id' => $this->appId
,
309 $dbw = self
::getDB( DB_MASTER
);
310 $dbw->delete( 'bot_passwords', $conds, __METHOD__
);
311 $ok = (bool)$dbw->affectedRows();
313 $this->token
= '**unsaved**';
314 $this->isSaved
= false;
320 * Invalidate all passwords for a user, by name
321 * @param string $username User name
322 * @return bool Whether any passwords were invalidated
324 public static function invalidateAllPasswordsForUser( $username ) {
325 $centralId = CentralIdLookup
::factory()->centralIdFromName(
326 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
328 return $centralId && self
::invalidateAllPasswordsForCentralId( $centralId );
332 * Invalidate all passwords for a user, by central ID
333 * @param int $centralId
334 * @return bool Whether any passwords were invalidated
336 public static function invalidateAllPasswordsForCentralId( $centralId ) {
337 $dbw = self
::getDB( DB_MASTER
);
340 array( 'bp_password' => PasswordFactory
::newInvalidPassword()->toString() ),
341 array( 'bp_user' => $centralId ),
344 return (bool)$dbw->affectedRows();
348 * Remove all passwords for a user, by name
349 * @param string $username User name
350 * @return bool Whether any passwords were removed
352 public static function removeAllPasswordsForUser( $username ) {
353 $centralId = CentralIdLookup
::factory()->centralIdFromName(
354 $username, CentralIdLookup
::AUDIENCE_RAW
, CentralIdLookup
::READ_LATEST
356 return $centralId && self
::removeAllPasswordsForCentralId( $centralId );
360 * Remove all passwords for a user, by central ID
361 * @param int $centralId
362 * @return bool Whether any passwords were removed
364 public static function removeAllPasswordsForCentralId( $centralId ) {
365 $dbw = self
::getDB( DB_MASTER
);
368 array( 'bp_user' => $centralId ),
371 return (bool)$dbw->affectedRows();
375 * Try to log the user in
376 * @param string $username Combined user name and app ID
377 * @param string $password Supplied password
378 * @param WebRequest $request
379 * @return Status On success, the good status's value is the new Session object
381 public static function login( $username, $password, WebRequest
$request ) {
382 global $wgEnableBotPasswords;
384 if ( !$wgEnableBotPasswords ) {
385 return Status
::newFatal( 'botpasswords-disabled' );
388 $manager = MediaWiki\Session\SessionManager
::singleton();
389 $provider = $manager->getProvider(
390 'MediaWiki\\Session\\BotPasswordSessionProvider'
393 return Status
::newFatal( 'botpasswords-no-provider' );
396 // Split name into name+appId
397 $sep = self
::getSeparator();
398 if ( strpos( $username, $sep ) === false ) {
399 return Status
::newFatal( 'botpasswords-invalid-name', $sep );
401 list( $name, $appId ) = explode( $sep, $username, 2 );
403 // Find the named user
404 $user = User
::newFromName( $name );
405 if ( !$user ||
$user->isAnon() ) {
406 return Status
::newFatal( 'nosuchuser', $name );
409 // Get the bot password
410 $bp = self
::newFromUser( $user, $appId );
412 return Status
::newFatal( 'botpasswords-not-exist', $name, $appId );
415 // Check restrictions
416 $status = $bp->getRestrictions()->check( $request );
417 if ( !$status->isOk() ) {
418 return Status
::newFatal( 'botpasswords-restriction-failed' );
421 // Check the password
422 if ( !$bp->getPassword()->equals( $password ) ) {
423 return Status
::newFatal( 'wrongpassword' );
426 // Ok! Create the session.
427 return Status
::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );