MediaWiki  1.29.0
LocalPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1 <?php
22 namespace MediaWiki\Auth;
23 
24 use User;
25 
33 {
34 
36  protected $loginOnly = false;
37 
44  public function __construct( $params = [] ) {
45  parent::__construct( $params );
46  $this->loginOnly = !empty( $params['loginOnly'] );
47  }
48 
49  protected function getPasswordResetData( $username, $row ) {
50  $now = wfTimestamp();
51  $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
52  if ( $expiration === null || $expiration >= $now ) {
53  return null;
54  }
55 
56  $grace = $this->config->get( 'PasswordExpireGrace' );
57  if ( $expiration + $grace < $now ) {
58  $data = [
59  'hard' => true,
60  'msg' => \Status::newFatal( 'resetpass-expired' )->getMessage(),
61  ];
62  } else {
63  $data = [
64  'hard' => false,
65  'msg' => \Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
66  ];
67  }
68 
69  return (object)$data;
70  }
71 
72  public function beginPrimaryAuthentication( array $reqs ) {
74  if ( !$req ) {
76  }
77 
78  if ( $req->username === null || $req->password === null ) {
80  }
81 
82  $username = User::getCanonicalName( $req->username, 'usable' );
83  if ( $username === false ) {
85  }
86 
87  $fields = [
88  'user_id', 'user_password', 'user_password_expires',
89  ];
90 
91  $dbr = wfGetDB( DB_REPLICA );
92  $row = $dbr->selectRow(
93  'user',
94  $fields,
95  [ 'user_name' => $username ],
96  __METHOD__
97  );
98  if ( !$row ) {
100  }
101 
102  $oldRow = clone $row;
103  // Check for *really* old password hashes that don't even have a type
104  // The old hash format was just an md5 hex hash, with no type information
105  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
106  if ( $this->config->get( 'PasswordSalt' ) ) {
107  $row->user_password = ":B:{$row->user_id}:{$row->user_password}";
108  } else {
109  $row->user_password = ":A:{$row->user_password}";
110  }
111  }
112 
113  $status = $this->checkPasswordValidity( $username, $req->password );
114  if ( !$status->isOK() ) {
115  // Fatal, can't log in
116  return AuthenticationResponse::newFail( $status->getMessage() );
117  }
118 
119  $pwhash = $this->getPassword( $row->user_password );
120  if ( !$pwhash->equals( $req->password ) ) {
121  if ( $this->config->get( 'LegacyEncoding' ) ) {
122  // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
123  // Check for this with iconv
124  $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
125  if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
126  return $this->failResponse( $req );
127  }
128  } else {
129  return $this->failResponse( $req );
130  }
131  }
132 
133  // @codeCoverageIgnoreStart
134  if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
135  $newHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
136  \DeferredUpdates::addCallableUpdate( function () use ( $newHash, $oldRow ) {
137  $dbw = wfGetDB( DB_MASTER );
138  $dbw->update(
139  'user',
140  [ 'user_password' => $newHash->toString() ],
141  [
142  'user_id' => $oldRow->user_id,
143  'user_password' => $oldRow->user_password
144  ],
145  __METHOD__
146  );
147  } );
148  }
149  // @codeCoverageIgnoreEnd
150 
151  $this->setPasswordResetFlag( $username, $status, $row );
152 
154  }
155 
156  public function testUserCanAuthenticate( $username ) {
158  if ( $username === false ) {
159  return false;
160  }
161 
162  $dbr = wfGetDB( DB_REPLICA );
163  $row = $dbr->selectRow(
164  'user',
165  [ 'user_password' ],
166  [ 'user_name' => $username ],
167  __METHOD__
168  );
169  if ( !$row ) {
170  return false;
171  }
172 
173  // Check for *really* old password hashes that don't even have a type
174  // The old hash format was just an md5 hex hash, with no type information
175  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
176  return true;
177  }
178 
179  return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
180  }
181 
182  public function testUserExists( $username, $flags = User::READ_NORMAL ) {
184  if ( $username === false ) {
185  return false;
186  }
187 
189  return (bool)wfGetDB( $db )->selectField(
190  [ 'user' ],
191  [ 'user_id' ],
192  [ 'user_name' => $username ],
193  __METHOD__,
194  $options
195  );
196  }
197 
199  AuthenticationRequest $req, $checkData = true
200  ) {
201  // We only want to blank the password if something else will accept the
202  // new authentication data, so return 'ignore' here.
203  if ( $this->loginOnly ) {
204  return \StatusValue::newGood( 'ignored' );
205  }
206 
207  if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
208  if ( !$checkData ) {
209  return \StatusValue::newGood();
210  }
211 
212  $username = User::getCanonicalName( $req->username, 'usable' );
213  if ( $username !== false ) {
214  $row = wfGetDB( DB_MASTER )->selectRow(
215  'user',
216  [ 'user_id' ],
217  [ 'user_name' => $username ],
218  __METHOD__
219  );
220  if ( $row ) {
221  $sv = \StatusValue::newGood();
222  if ( $req->password !== null ) {
223  if ( $req->password !== $req->retype ) {
224  $sv->fatal( 'badretype' );
225  } else {
226  $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
227  }
228  }
229  return $sv;
230  }
231  }
232  }
233 
234  return \StatusValue::newGood( 'ignored' );
235  }
236 
238  $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
239  if ( $username === false ) {
240  return;
241  }
242 
243  $pwhash = null;
244 
245  if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
246  if ( $this->loginOnly ) {
247  $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
248  $expiry = null;
249  } else {
250  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
251  $expiry = $this->getNewPasswordExpiry( $username );
252  }
253  }
254 
255  if ( $pwhash ) {
256  $dbw = wfGetDB( DB_MASTER );
257  $dbw->update(
258  'user',
259  [
260  'user_password' => $pwhash->toString(),
261  'user_password_expires' => $dbw->timestampOrNull( $expiry ),
262  ],
263  [ 'user_name' => $username ],
264  __METHOD__
265  );
266  }
267  }
268 
269  public function accountCreationType() {
270  return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
271  }
272 
273  public function testForAccountCreation( $user, $creator, array $reqs ) {
275 
277  if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
278  if ( $req->password !== $req->retype ) {
279  $ret->fatal( 'badretype' );
280  } else {
281  $ret->merge(
282  $this->checkPasswordValidity( $user->getName(), $req->password )
283  );
284  }
285  }
286  return $ret;
287  }
288 
289  public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
290  if ( $this->accountCreationType() === self::TYPE_NONE ) {
291  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
292  }
293 
295  if ( $req ) {
296  if ( $req->username !== null && $req->password !== null ) {
297  // Nothing we can do besides claim it, because the user isn't in
298  // the DB yet
299  if ( $req->username !== $user->getName() ) {
300  $req = clone( $req );
301  $req->username = $user->getName();
302  }
304  $ret->createRequest = $req;
305  return $ret;
306  }
307  }
309  }
310 
311  public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
312  if ( $this->accountCreationType() === self::TYPE_NONE ) {
313  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
314  }
315 
316  // Now that the user is in the DB, set the password on it.
317  $this->providerChangeAuthenticationData( $res->createRequest );
318 
319  return null;
320  }
321 }
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\$loginOnly
bool $loginOnly
If true, this instance is for legacy logins only.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:36
MediaWiki\Auth\PrimaryAuthenticationProvider\TYPE_CREATE
const TYPE_CREATE
Provider can create accounts.
Definition: PrimaryAuthenticationProvider.php:77
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\accountCreationType
accountCreationType()
Fetch the account-creation type.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:269
MediaWiki\Auth\PrimaryAuthenticationProvider\TYPE_NONE
const TYPE_NONE
Provider cannot create or link to accounts.
Definition: PrimaryAuthenticationProvider.php:81
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getPassword
getPassword( $hash)
Get a Password object from the hash.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:67
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\failResponse
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:83
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider
Basic framework for a primary authentication provider that uses passwords.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:33
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
$req
this hook is for auditing only $req
Definition: hooks.txt:990
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
$params
$params
Definition: styleTest.css.php:40
$res
$res
Definition: database.txt:21
DBAccessObjectUtils\getDBOptions
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
Definition: DBAccessObjectUtils.php:52
User
User
Definition: All_system_messages.txt:425
MediaWiki\Auth\AuthenticationRequest\getRequestByClass
static getRequestByClass(array $reqs, $class, $allowSubclasses=false)
Select a request by class name.
Definition: AuthenticationRequest.php:253
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$dbr
$dbr
Definition: testCompression.php:50
MediaWiki\Auth\AuthenticationResponse\newAbstain
static newAbstain()
Definition: AuthenticationResponse.php:170
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:111
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getNewPasswordExpiry
getNewPasswordExpiry( $username)
Get expiration date for a new password, if any.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:150
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:198
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider
A primary authentication provider that uses the password field in the 'user' table.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:31
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate
testUserCanAuthenticate( $username)
Test whether the named user can authenticate with this provider.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:156
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication
beginPrimaryAuthentication(array $reqs)
Start an authentication flow.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:72
MediaWiki\Auth\AuthenticationResponse
This is a value object to hold authentication response data.
Definition: AuthenticationResponse.php:37
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:2010
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\finishAccountCreation
finishAccountCreation( $user, $creator, AuthenticationResponse $res)
Post-creation callback.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:311
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testForAccountCreation
testForAccountCreation( $user, $creator, array $reqs)
Determine whether an account creation may begin.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:273
DB_MASTER
const DB_MASTER
Definition: defines.php:26
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:237
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\beginPrimaryAccountCreation
beginPrimaryAccountCreation( $user, $creator, array $reqs)
Start an account creation flow.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:289
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:76
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1956
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\setPasswordResetFlag
setPasswordResetFlag( $username, Status $status, $data=null)
Check if the password should be reset.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:118
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\getPasswordResetData
getPasswordResetData( $username, $row)
Get password reset data, if any.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:49
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\checkPasswordValidity
checkPasswordValidity( $username, $password)
Check that the password is valid.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:103
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserExists
testUserExists( $username, $flags=User::READ_NORMAL)
Test whether the named user exists.
Definition: LocalPasswordPrimaryAuthenticationProvider.php:182
MediaWiki\Auth\AuthenticationResponse\newFail
static newFail(Message $msg)
Definition: AuthenticationResponse.php:146
User\getCanonicalName
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition: User.php:1076
MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getPasswordFactory
getPasswordFactory()
Get the PasswordFactory.
Definition: AbstractPasswordPrimaryAuthenticationProvider.php:54
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:783
MediaWiki\Auth
Definition: AbstractAuthenticationProvider.php:22
MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\__construct
__construct( $params=[])
Definition: LocalPasswordPrimaryAuthenticationProvider.php:44
MediaWiki\Auth\AuthenticationResponse\newPass
static newPass( $username=null)
Definition: AuthenticationResponse.php:134
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
MediaWiki\Auth\AuthenticationRequest
This is a value object for authentication requests.
Definition: AuthenticationRequest.php:37
array
the array() calling protocol came about after MediaWiki 1.4rc1.