MediaWiki  1.27.2
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  $dbw = wfGetDB( DB_MASTER );
130  $row = $dbw->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  $dbw = wfGetDB( DB_MASTER );
169  $row = $dbw->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 
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  $this->sendPasswordResetEmail( $req );
307  }
308  }
309 
310  public function accountCreationType() {
311  return self::TYPE_CREATE;
312  }
313 
314  public function testForAccountCreation( $user, $creator, array $reqs ) {
318  );
319 
321  if ( $req ) {
322  if ( $req->mailpassword && !$req->hasBackchannel ) {
323  if ( !$this->emailEnabled ) {
324  $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
325  } elseif ( !$user->getEmail() ) {
326  $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
327  }
328  }
329 
330  $ret->merge(
331  $this->checkPasswordValidity( $user->getName(), $req->password )
332  );
333  }
334  return $ret;
335  }
336 
337  public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
341  );
342  if ( $req ) {
343  if ( $req->username !== null && $req->password !== null ) {
344  // Nothing we can do yet, because the user isn't in the DB yet
345  if ( $req->username !== $user->getName() ) {
346  $req = clone( $req );
347  $req->username = $user->getName();
348  }
349 
350  if ( $req->mailpassword ) {
351  // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
352  $this->manager->setAuthenticationSessionData( 'no-email', true );
353  }
354 
356  $ret->createRequest = $req;
357  return $ret;
358  }
359  }
361  }
362 
363  public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
365  $req = $res->createRequest;
366  $mailpassword = $req->mailpassword;
367  $req->mailpassword = false; // providerChangeAuthenticationData would send the wrong email
368 
369  // Now that the user is in the DB, set the password on it.
371 
372  if ( $mailpassword ) {
373  $this->sendNewAccountEmail( $user, $creator, $req->password );
374  }
375 
376  return $mailpassword ? 'byemail' : null;
377  }
378 
384  protected function isTimestampValid( $timestamp ) {
386  if ( $time !== null ) {
388  if ( time() >= $expiry ) {
389  return false;
390  }
391  }
392  return true;
393  }
394 
402  protected function sendNewAccountEmail( User $user, User $creatingUser, $password ) {
403  $ip = $creatingUser->getRequest()->getIP();
404  // @codeCoverageIgnoreStart
405  if ( !$ip ) {
406  return \Status::newFatal( 'badipaddress' );
407  }
408  // @codeCoverageIgnoreEnd
409 
410  \Hooks::run( 'User::mailPasswordInternal', [ &$creatingUser, &$ip, &$user ] );
411 
412  $mainPageUrl = \Title::newMainPage()->getCanonicalURL();
413  $userLanguage = $user->getOption( 'language' );
414  $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
415  $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
416  '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
417  ->inLanguage( $userLanguage );
418 
419  $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
420 
421  // TODO show 'mailerror' message on error, 'accmailtext' success message otherwise?
422  // @codeCoverageIgnoreStart
423  if ( !$status->isGood() ) {
424  $this->logger->warning( 'Could not send account creation email: ' .
425  $status->getWikiText( false, false, 'en' ) );
426  }
427  // @codeCoverageIgnoreEnd
428 
429  return $status;
430  }
431 
437  $user = User::newFromName( $req->username );
438  if ( !$user ) {
439  return \Status::newFatal( 'noname' );
440  }
441  $userLanguage = $user->getOption( 'language' );
442  $callerIsAnon = \IP::isValid( $req->caller );
443  $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
444  $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
445  $req->password )->inLanguage( $userLanguage );
446  $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
447  : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
448  $emailMessage->params( $callerName, $passwordMessage->text(), 1,
449  '<' . \Title::newMainPage()->getCanonicalURL() . '>',
450  round( $this->newPasswordExpiry / 86400 ) );
451  $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
452  return $user->sendMail( $emailTitle->text(), $emailMessage->text() );
453  }
454 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
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:569
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:1050
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
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:1798
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:2548
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.
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2086
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1612
sendMail($subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
Definition: User.php:4272
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
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:1004
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:60
A primary authentication provider that uses the temporary password field in the 'user' table...
beginPrimaryAccountCreation($user, $creator, array $reqs)
Start an account creation flow.
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing 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
$params
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 and options 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:2746
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
String $action
Cache what action this request is.
Definition: MediaWiki.php:42
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:3455
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:965
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:762
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.
Definition: AuthManager.php:62
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:1004
const ACTION_CREATE
Create a new user.
Definition: AuthManager.php:50
const DB_MASTER
Definition: Defines.php:47
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
const ACTION_LOGIN
Log in with an existing (not necessarily local) user.
Definition: AuthManager.php:45
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.
This is a value object for authentication requests.