MediaWiki  1.28.0
TemporaryPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1 <?php
22 namespace MediaWiki\Auth;
23 
24 use User;
25 
39 {
41  protected $emailEnabled = null;
42 
44  protected $newPasswordExpiry = null;
45 
47  protected $passwordReminderResendTime = null;
48 
56  public function __construct( $params = [] ) {
57  parent::__construct( $params );
58 
59  if ( isset( $params['emailEnabled'] ) ) {
60  $this->emailEnabled = (bool)$params['emailEnabled'];
61  }
62  if ( isset( $params['newPasswordExpiry'] ) ) {
63  $this->newPasswordExpiry = (int)$params['newPasswordExpiry'];
64  }
65  if ( isset( $params['passwordReminderResendTime'] ) ) {
66  $this->passwordReminderResendTime = $params['passwordReminderResendTime'];
67  }
68  }
69 
70  public function setConfig( \Config $config ) {
71  parent::setConfig( $config );
72 
73  if ( $this->emailEnabled === null ) {
74  $this->emailEnabled = $this->config->get( 'EnableEmail' );
75  }
76  if ( $this->newPasswordExpiry === null ) {
77  $this->newPasswordExpiry = $this->config->get( 'NewPasswordExpiry' );
78  }
79  if ( $this->passwordReminderResendTime === null ) {
80  $this->passwordReminderResendTime = $this->config->get( 'PasswordReminderResendTime' );
81  }
82  }
83 
84  protected function getPasswordResetData( $username, $data ) {
85  // Always reset
86  return (object)[
87  'msg' => wfMessage( 'resetpass-temp-emailed' ),
88  'hard' => true,
89  ];
90  }
91 
93  switch ( $action ) {
95  return [ new PasswordAuthenticationRequest() ];
96 
99 
101  if ( isset( $options['username'] ) && $this->emailEnabled ) {
102  // Creating an account for someone else
104  } else {
105  // It's not terribly likely that an anonymous user will
106  // be creating an account for someone else.
107  return [];
108  }
109 
112 
113  default:
114  return [];
115  }
116  }
117 
118  public function beginPrimaryAuthentication( array $reqs ) {
120  if ( !$req || $req->username === null || $req->password === null ) {
122  }
123 
124  $username = User::getCanonicalName( $req->username, 'usable' );
125  if ( $username === false ) {
127  }
128 
129  $dbr = wfGetDB( DB_REPLICA );
130  $row = $dbr->selectRow(
131  'user',
132  [
133  'user_id', 'user_newpassword', 'user_newpass_time',
134  ],
135  [ 'user_name' => $username ],
136  __METHOD__
137  );
138  if ( !$row ) {
140  }
141 
142  $status = $this->checkPasswordValidity( $username, $req->password );
143  if ( !$status->isOK() ) {
144  // Fatal, can't log in
145  return AuthenticationResponse::newFail( $status->getMessage() );
146  }
147 
148  $pwhash = $this->getPassword( $row->user_newpassword );
149  if ( !$pwhash->equals( $req->password ) ) {
150  return $this->failResponse( $req );
151  }
152 
153  if ( !$this->isTimestampValid( $row->user_newpass_time ) ) {
154  return $this->failResponse( $req );
155  }
156 
158 
160  }
161 
162  public function testUserCanAuthenticate( $username ) {
164  if ( $username === false ) {
165  return false;
166  }
167 
168  $dbr = wfGetDB( DB_REPLICA );
169  $row = $dbr->selectRow(
170  'user',
171  [ 'user_newpassword', 'user_newpass_time' ],
172  [ 'user_name' => $username ],
173  __METHOD__
174  );
175  if ( !$row ) {
176  return false;
177  }
178 
179  if ( $this->getPassword( $row->user_newpassword ) instanceof \InvalidPassword ) {
180  return false;
181  }
182 
183  if ( !$this->isTimestampValid( $row->user_newpass_time ) ) {
184  return false;
185  }
186 
187  return true;
188  }
189 
190  public function testUserExists( $username, $flags = User::READ_NORMAL ) {
192  if ( $username === false ) {
193  return false;
194  }
195 
197  return (bool)wfGetDB( $db )->selectField(
198  [ 'user' ],
199  [ 'user_id' ],
200  [ 'user_name' => $username ],
201  __METHOD__,
202  $options
203  );
204  }
205 
207  AuthenticationRequest $req, $checkData = true
208  ) {
209  if ( get_class( $req ) !== TemporaryPasswordAuthenticationRequest::class ) {
210  // We don't really ignore it, but this is what the caller expects.
211  return \StatusValue::newGood( 'ignored' );
212  }
213 
214  if ( !$checkData ) {
215  return \StatusValue::newGood();
216  }
217 
218  $username = User::getCanonicalName( $req->username, 'usable' );
219  if ( $username === false ) {
220  return \StatusValue::newGood( 'ignored' );
221  }
222 
223  $row = wfGetDB( DB_MASTER )->selectRow(
224  'user',
225  [ 'user_id', 'user_newpass_time' ],
226  [ 'user_name' => $username ],
227  __METHOD__
228  );
229 
230  if ( !$row ) {
231  return \StatusValue::newGood( 'ignored' );
232  }
233 
234  $sv = \StatusValue::newGood();
235  if ( $req->password !== null ) {
236  $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
237 
238  if ( $req->mailpassword ) {
239  if ( !$this->emailEnabled && !$req->hasBackchannel ) {
240  return \StatusValue::newFatal( 'passwordreset-emaildisabled' );
241  }
242 
243  // We don't check whether the user has an email address;
244  // that information should not be exposed to the caller.
245 
246  // do not allow temporary password creation within
247  // $wgPasswordReminderResendTime from the last attempt
248  if (
249  $this->passwordReminderResendTime
250  && $row->user_newpass_time
251  && time() < wfTimestamp( TS_UNIX, $row->user_newpass_time )
252  + $this->passwordReminderResendTime * 3600
253  ) {
254  // Round the time in hours to 3 d.p., in case someone is specifying
255  // minutes or seconds.
256  return \StatusValue::newFatal( 'throttled-mailpassword',
257  round( $this->passwordReminderResendTime, 3 ) );
258  }
259 
260  if ( !$req->caller ) {
261  return \StatusValue::newFatal( 'passwordreset-nocaller' );
262  }
263  if ( !\IP::isValid( $req->caller ) ) {
264  $caller = User::newFromName( $req->caller );
265  if ( !$caller ) {
266  return \StatusValue::newFatal( 'passwordreset-nosuchcaller', $req->caller );
267  }
268  }
269  }
270  }
271  return $sv;
272  }
273 
275  $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
276  if ( $username === false ) {
277  return;
278  }
279 
280  $dbw = wfGetDB( DB_MASTER );
281 
282  $sendMail = false;
283  if ( $req->action !== AuthManager::ACTION_REMOVE &&
285  ) {
286  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
287  $newpassTime = $dbw->timestamp();
288  $sendMail = $req->mailpassword;
289  } else {
290  // Invalidate the temporary password when any other auth is reset, or when removing
291  $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
292  $newpassTime = null;
293  }
294 
295  $dbw->update(
296  'user',
297  [
298  'user_newpassword' => $pwhash->toString(),
299  'user_newpass_time' => $newpassTime,
300  ],
301  [ 'user_name' => $username ],
302  __METHOD__
303  );
304 
305  if ( $sendMail ) {
306  // Send email after DB commit
307  $dbw->onTransactionIdle(
308  function () use ( $req ) {
310  $this->sendPasswordResetEmail( $req );
311  },
312  __METHOD__
313  );
314  }
315  }
316 
317  public function accountCreationType() {
318  return self::TYPE_CREATE;
319  }
320 
321  public function testForAccountCreation( $user, $creator, array $reqs ) {
325  );
326 
328  if ( $req ) {
329  if ( $req->mailpassword && !$req->hasBackchannel ) {
330  if ( !$this->emailEnabled ) {
331  $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
332  } elseif ( !$user->getEmail() ) {
333  $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
334  }
335  }
336 
337  $ret->merge(
338  $this->checkPasswordValidity( $user->getName(), $req->password )
339  );
340  }
341  return $ret;
342  }
343 
344  public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
348  );
349  if ( $req ) {
350  if ( $req->username !== null && $req->password !== null ) {
351  // Nothing we can do yet, because the user isn't in the DB yet
352  if ( $req->username !== $user->getName() ) {
353  $req = clone( $req );
354  $req->username = $user->getName();
355  }
356 
357  if ( $req->mailpassword ) {
358  // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
359  $this->manager->setAuthenticationSessionData( 'no-email', true );
360  }
361 
363  $ret->createRequest = $req;
364  return $ret;
365  }
366  }
368  }
369 
370  public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
372  $req = $res->createRequest;
373  $mailpassword = $req->mailpassword;
374  $req->mailpassword = false; // providerChangeAuthenticationData would send the wrong email
375 
376  // Now that the user is in the DB, set the password on it.
378 
379  if ( $mailpassword ) {
380  // Send email after DB commit
381  wfGetDB( DB_MASTER )->onTransactionIdle(
382  function () use ( $user, $creator, $req ) {
383  $this->sendNewAccountEmail( $user, $creator, $req->password );
384  },
385  __METHOD__
386  );
387  }
388 
389  return $mailpassword ? 'byemail' : null;
390  }
391 
397  protected function isTimestampValid( $timestamp ) {
399  if ( $time !== null ) {
401  if ( time() >= $expiry ) {
402  return false;
403  }
404  }
405  return true;
406  }
407 
415  protected function sendNewAccountEmail( User $user, User $creatingUser, $password ) {
416  $ip = $creatingUser->getRequest()->getIP();
417  // @codeCoverageIgnoreStart
418  if ( !$ip ) {
419  return \Status::newFatal( 'badipaddress' );
420  }
421  // @codeCoverageIgnoreEnd
422 
423  \Hooks::run( 'User::mailPasswordInternal', [ &$creatingUser, &$ip, &$user ] );
424 
425  $mainPageUrl = \Title::newMainPage()->getCanonicalURL();
426  $userLanguage = $user->getOption( 'language' );
427  $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
428  $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
429  '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
430  ->inLanguage( $userLanguage );
431 
432  $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
433 
434  // TODO show 'mailerror' message on error, 'accmailtext' success message otherwise?
435  // @codeCoverageIgnoreStart
436  if ( !$status->isGood() ) {
437  $this->logger->warning( 'Could not send account creation email: ' .
438  $status->getWikiText( false, false, 'en' ) );
439  }
440  // @codeCoverageIgnoreEnd
441 
442  return $status;
443  }
444 
450  $user = User::newFromName( $req->username );
451  if ( !$user ) {
452  return \Status::newFatal( 'noname' );
453  }
454  $userLanguage = $user->getOption( 'language' );
455  $callerIsAnon = \IP::isValid( $req->caller );
456  $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
457  $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
458  $req->password )->inLanguage( $userLanguage );
459  $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
460  : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
461  $emailMessage->params( $callerName, $passwordMessage->text(), 1,
462  '<' . \Title::newMainPage()->getCanonicalURL() . '>',
463  round( $this->newPasswordExpiry / 86400 ) );
464  $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
465  return $user->sendMail( $emailTitle->text(), $emailMessage->text() );
466  }
467 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:525
testUserCanAuthenticate($username)
Test whether the named user can authenticate with this provider.
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:556
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:1936
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getCanonicalName($name, $validate= 'valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid...
Definition: User.php:1046
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
setPasswordResetFlag($username, Status $status, $data=null)
Check if the password should be reset.
Represents an invalid password hash.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
This is a value object to hold authentication response data.
sendNewAccountEmail(User $user, User $creatingUser, $password)
Send an email about the new account creation and the temporary password.
const DB_MASTER
Definition: defines.php:23
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2108
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: defines.php:6
sendMail($subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
Definition: User.php:4345
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
if($limit) $timestamp
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
static isValid($ip)
Validate an IP address.
Definition: IP.php:113
$res
Definition: database.txt:21
const ACTION_CHANGE
Change a user's credentials.
Definition: AuthManager.php:98
A primary authentication provider that uses the temporary password field in the 'user' table...
beginPrimaryAccountCreation($user, $creator, array $reqs)
Start an account creation flow.
$params
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: defines.php:11
Basic framework for a primary authentication provider that uses passwords.
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static getDBOptions($bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
testForAccountCreation($user, $creator, array $reqs)
Determine whether an account creation may begin.
This represents the intention to set a temporary password for the 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 local account $user
Definition: hooks.txt:242
This is a value object for authentication requests with a username and password.
getOption($oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2766
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
String $action
Cache what action this request is.
Definition: MediaWiki.php:43
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:3490
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
this hook is for auditing only $req
Definition: hooks.txt:1007
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:802
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
static newRandom()
Return an instance with a new, random password.
const ACTION_REMOVE
Remove a user's credentials.
static getRequestByClass(array $reqs, $class, $allowSubclasses=false)
Select a request by class name.
getAuthenticationRequests($action, array $options)
{{Return the applicable list of AuthenticationRequests.Possible values for $action depend on whether ...
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
const ACTION_CREATE
Create a new user.
Definition: AuthManager.php:88
const DB_REPLICA
Definition: defines.php:22
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
const ACTION_LOGIN
Log in with an existing (not necessarily local) user.
Definition: AuthManager.php:83
wfTimestampOrNull($outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
testUserExists($username, $flags=User::READ_NORMAL)
Test whether the named user exists.
isTimestampValid($timestamp)
Check that a temporary password is still valid (hasn't expired).
finishAccountCreation($user, $creator, AuthenticationResponse $res)
Post-creation callback.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1749
This is a value object for authentication requests.