MediaWiki master
TemporaryPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1<?php
22namespace MediaWiki\Auth;
23
32use Wikimedia\IPUtils;
34
48{
50 protected $emailEnabled = null;
51
53 protected $newPasswordExpiry = null;
54
57
59 protected $allowRequiringEmail = null;
60
62 private $dbProvider;
63
65 private $userOptionsLookup;
66
76 public function __construct(
77 IConnectionProvider $dbProvider,
78 UserOptionsLookup $userOptionsLookup,
79 $params = []
80 ) {
81 parent::__construct( $params );
82
83 if ( isset( $params['emailEnabled'] ) ) {
84 $this->emailEnabled = (bool)$params['emailEnabled'];
85 }
86 if ( isset( $params['newPasswordExpiry'] ) ) {
87 $this->newPasswordExpiry = (int)$params['newPasswordExpiry'];
88 }
89 if ( isset( $params['passwordReminderResendTime'] ) ) {
90 $this->passwordReminderResendTime = $params['passwordReminderResendTime'];
91 }
92 if ( isset( $params['allowRequiringEmailForResets'] ) ) {
93 $this->allowRequiringEmail = $params['allowRequiringEmailForResets'];
94 }
95 $this->dbProvider = $dbProvider;
96 $this->userOptionsLookup = $userOptionsLookup;
97 }
98
99 protected function postInitSetup() {
100 $this->emailEnabled ??= $this->config->get( MainConfigNames::EnableEmail );
101 $this->newPasswordExpiry ??= $this->config->get( MainConfigNames::NewPasswordExpiry );
102 $this->passwordReminderResendTime ??=
104 $this->allowRequiringEmail ??=
106 }
107
108 protected function getPasswordResetData( $username, $data ) {
109 // Always reset
110 return (object)[
111 'msg' => wfMessage( 'resetpass-temp-emailed' ),
112 'hard' => true,
113 ];
114 }
115
116 public function getAuthenticationRequests( $action, array $options ) {
117 switch ( $action ) {
119 return [ new PasswordAuthenticationRequest() ];
120
123
125 if ( isset( $options['username'] ) && $this->emailEnabled ) {
126 // Creating an account for someone else
128 } else {
129 // It's not terribly likely that an anonymous user will
130 // be creating an account for someone else.
131 return [];
132 }
133
136
137 default:
138 return [];
139 }
140 }
141
142 public function beginPrimaryAuthentication( array $reqs ) {
143 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
144 if ( !$req || $req->username === null || $req->password === null ) {
146 }
147
148 $username = $this->userNameUtils->getCanonical(
149 $req->username, UserRigorOptions::RIGOR_USABLE );
150 if ( $username === false ) {
152 }
153
154 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
155 ->select( [ 'user_id', 'user_newpassword', 'user_newpass_time' ] )
156 ->from( 'user' )
157 ->where( [ 'user_name' => $username ] )
158 ->caller( __METHOD__ )->fetchRow();
159 if ( !$row ) {
161 }
162
163 $status = $this->checkPasswordValidity( $username, $req->password );
164 if ( !$status->isOK() ) {
165 return $this->getFatalPasswordErrorResponse( $username, $status );
166 }
167
168 $pwhash = $this->getPassword( $row->user_newpassword );
169 if ( !$pwhash->verify( $req->password ) ||
170 !$this->isTimestampValid( $row->user_newpass_time )
171 ) {
172 return $this->failResponse( $req );
173 }
174
175 // Add an extra log entry since a temporary password is
176 // an unusual way to log in, so its important to keep track
177 // of in case of abuse.
178 $this->logger->info( "{user} successfully logged in using temp password",
179 [
180 'user' => $username,
181 'requestIP' => $this->manager->getRequest()->getIP()
182 ]
183 );
184
185 $this->setPasswordResetFlag( $username, $status );
186
187 return AuthenticationResponse::newPass( $username );
188 }
189
190 public function testUserCanAuthenticate( $username ) {
191 $username = $this->userNameUtils->getCanonical( $username, UserRigorOptions::RIGOR_USABLE );
192 if ( $username === false ) {
193 return false;
194 }
195
196 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
197 ->select( [ 'user_newpassword', 'user_newpass_time' ] )
198 ->from( 'user' )
199 ->where( [ 'user_name' => $username ] )
200 ->caller( __METHOD__ )->fetchRow();
201 return $row &&
202 !( $this->getPassword( $row->user_newpassword ) instanceof InvalidPassword ) &&
203 $this->isTimestampValid( $row->user_newpass_time );
204 }
205
206 public function testUserExists( $username, $flags = IDBAccessObject::READ_NORMAL ) {
207 $username = $this->userNameUtils->getCanonical( $username, UserRigorOptions::RIGOR_USABLE );
208 if ( $username === false ) {
209 return false;
210 }
211
212 $db = \DBAccessObjectUtils::getDBFromRecency( $this->dbProvider, $flags );
213 return (bool)$db->newSelectQueryBuilder()
214 ->select( [ 'user_id' ] )
215 ->from( 'user' )
216 ->where( [ 'user_name' => $username ] )
217 ->recency( $flags )
218 ->caller( __METHOD__ )->fetchField();
219 }
220
222 AuthenticationRequest $req, $checkData = true
223 ) {
224 if ( get_class( $req ) !== TemporaryPasswordAuthenticationRequest::class ) {
225 // We don't really ignore it, but this is what the caller expects.
226 return \StatusValue::newGood( 'ignored' );
227 }
228
229 if ( !$checkData ) {
230 return \StatusValue::newGood();
231 }
232
233 $username = $this->userNameUtils->getCanonical(
234 $req->username, UserRigorOptions::RIGOR_USABLE );
235 if ( $username === false ) {
236 return \StatusValue::newGood( 'ignored' );
237 }
238
239 $row = $this->dbProvider->getPrimaryDatabase()->newSelectQueryBuilder()
240 ->select( [ 'user_id', 'user_newpass_time' ] )
241 ->from( 'user' )
242 ->where( [ 'user_name' => $username ] )
243 ->caller( __METHOD__ )->fetchRow();
244 if ( !$row ) {
245 return \StatusValue::newGood( 'ignored' );
246 }
247
248 $sv = \StatusValue::newGood();
249 if ( $req->password !== null ) {
250 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
251
252 if ( $req->mailpassword ) {
253 if ( !$this->emailEnabled ) {
254 return \StatusValue::newFatal( 'passwordreset-emaildisabled' );
255 }
256
257 // We don't check whether the user has an email address;
258 // that information should not be exposed to the caller.
259
260 // do not allow temporary password creation within
261 // $wgPasswordReminderResendTime from the last attempt
262 if (
263 $this->passwordReminderResendTime
264 && $row->user_newpass_time
265 && time() < (int)wfTimestamp( TS_UNIX, $row->user_newpass_time )
266 + $this->passwordReminderResendTime * 3600
267 ) {
268 // Round the time in hours to 3 d.p., in case someone is specifying
269 // minutes or seconds.
270 return \StatusValue::newFatal( 'throttled-mailpassword',
271 round( $this->passwordReminderResendTime, 3 ) );
272 }
273
274 if ( !$req->caller ) {
275 return \StatusValue::newFatal( 'passwordreset-nocaller' );
276 }
277 if ( !IPUtils::isValid( $req->caller ) ) {
278 $caller = User::newFromName( $req->caller );
279 if ( !$caller ) {
280 return \StatusValue::newFatal( 'passwordreset-nosuchcaller', $req->caller );
281 }
282 }
283 }
284 }
285 return $sv;
286 }
287
289 $username = $req->username !== null ?
290 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE ) : false;
291 if ( $username === false ) {
292 return;
293 }
294
295 $dbw = $this->dbProvider->getPrimaryDatabase();
296
297 $sendMail = false;
298 if ( $req->action !== AuthManager::ACTION_REMOVE &&
299 get_class( $req ) === TemporaryPasswordAuthenticationRequest::class
300 ) {
301 $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
302 $newpassTime = $dbw->timestamp();
303 $sendMail = $req->mailpassword;
304 } else {
305 // Invalidate the temporary password when any other auth is reset, or when removing
306 $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
307 $newpassTime = null;
308 }
309
310 $dbw->newUpdateQueryBuilder()
311 ->update( 'user' )
312 ->set( [
313 'user_newpassword' => $pwhash->toString(),
314 'user_newpass_time' => $newpassTime,
315 ] )
316 ->where( [ 'user_name' => $username ] )
317 ->caller( __METHOD__ )->execute();
318
319 if ( $sendMail ) {
320 // Send email after DB commit
321 $dbw->onTransactionCommitOrIdle(
322 function () use ( $req ) {
324 $this->sendPasswordResetEmail( $req );
325 },
326 __METHOD__
327 );
328 }
329 }
330
331 public function accountCreationType() {
332 return self::TYPE_CREATE;
333 }
334
335 public function testForAccountCreation( $user, $creator, array $reqs ) {
338 $reqs, TemporaryPasswordAuthenticationRequest::class
339 );
340
341 $ret = \StatusValue::newGood();
342 if ( $req ) {
343 if ( $req->mailpassword ) {
344 if ( !$this->emailEnabled ) {
345 $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
346 } elseif ( !$user->getEmail() ) {
347 $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
348 }
349 }
350
351 $ret->merge(
352 $this->checkPasswordValidity( $user->getName(), $req->password )
353 );
354 }
355 return $ret;
356 }
357
358 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
361 $reqs, TemporaryPasswordAuthenticationRequest::class
362 );
363 if ( $req && $req->username !== null && $req->password !== null ) {
364 // Nothing we can do yet, because the user isn't in the DB yet
365 if ( $req->username !== $user->getName() ) {
366 $req = clone $req;
367 $req->username = $user->getName();
368 }
369
370 if ( $req->mailpassword ) {
371 // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
372 $this->manager->setAuthenticationSessionData( 'no-email', true );
373 }
374
375 $ret = AuthenticationResponse::newPass( $req->username );
376 $ret->createRequest = $req;
377 return $ret;
378 }
380 }
381
382 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
384 $req = $res->createRequest;
385 $mailpassword = $req->mailpassword;
386 $req->mailpassword = false; // providerChangeAuthenticationData would send the wrong email
387
388 // Now that the user is in the DB, set the password on it.
390
391 if ( $mailpassword ) {
392 // Send email after DB commit
393 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
394 function () use ( $user, $creator, $req ) {
395 $this->sendNewAccountEmail( $user, $creator, $req->password );
396 },
397 __METHOD__
398 );
399 }
400
401 return $mailpassword ? 'byemail' : null;
402 }
403
409 protected function isTimestampValid( $timestamp ) {
410 $time = wfTimestampOrNull( TS_MW, $timestamp );
411 if ( $time !== null ) {
412 $expiry = (int)wfTimestamp( TS_UNIX, $time ) + $this->newPasswordExpiry;
413 if ( time() >= $expiry ) {
414 return false;
415 }
416 }
417 return true;
418 }
419
427 protected function sendNewAccountEmail( User $user, User $creatingUser, $password ) {
428 $ip = $creatingUser->getRequest()->getIP();
429 // @codeCoverageIgnoreStart
430 if ( !$ip ) {
431 return \MediaWiki\Status\Status::newFatal( 'badipaddress' );
432 }
433 // @codeCoverageIgnoreEnd
434
435 $this->getHookRunner()->onUser__mailPasswordInternal( $creatingUser, $ip, $user );
436
437 $mainPageUrl = Title::newMainPage()->getCanonicalURL();
438 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
439 $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
440 $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
441 '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
442 ->inLanguage( $userLanguage );
443
444 $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
445
446 // TODO show 'mailerror' message on error, 'accmailtext' success message otherwise?
447 // @codeCoverageIgnoreStart
448 if ( !$status->isGood() ) {
449 $this->logger->warning( 'Could not send account creation email: ' .
450 $status->getWikiText( false, false, 'en' ) );
451 }
452 // @codeCoverageIgnoreEnd
453
454 return $status;
455 }
456
462 $user = User::newFromName( $req->username );
463 if ( !$user ) {
464 return \MediaWiki\Status\Status::newFatal( 'noname' );
465 }
466 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
467 $callerIsAnon = IPUtils::isValid( $req->caller );
468 $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
469 $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
470 $req->password )->inLanguage( $userLanguage );
471 $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
472 : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
473 $body = $emailMessage->params( $callerName, $passwordMessage->text(), 1,
474 '<' . Title::newMainPage()->getCanonicalURL() . '>',
475 round( $this->newPasswordExpiry / 86400 ) )->text();
476
477 if ( $this->allowRequiringEmail && !$this->userOptionsLookup
478 ->getBoolOption( $user, 'requireemail' )
479 ) {
480 $body .= "\n\n";
481 $url = SpecialPage::getTitleFor( 'Preferences', false, 'mw-prefsection-personal-email' )
482 ->getCanonicalURL();
483 $body .= wfMessage( 'passwordreset-emailtext-require-email' )
484 ->inLanguage( $userLanguage )
485 ->params( "<$url>" )
486 ->text();
487 }
488
489 $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
490 return $user->sendMail( $emailTitle->text(), $body );
491 }
492}
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
array $params
The job parameters.
Basic framework for a primary authentication provider that uses passwords.
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
setPasswordResetFlag( $username, Status $status, $data=null)
Check if the password should be reset.
getFatalPasswordErrorResponse(string $username, Status $status)
Adds user-friendly description to a fatal password validity check error.
const ACTION_CHANGE
Change a user's credentials.
const ACTION_REMOVE
Remove a user's credentials.
const ACTION_LOGIN
Log in with an existing (not necessarily local) user.
const ACTION_CREATE
Create a new user.
This is a value object for authentication requests.
static getRequestByClass(array $reqs, $class, $allowSubclasses=false)
Select a request by class name.
This is a value object to hold authentication response data.
This is a value object for authentication requests with a username and password.
This represents the intention to set a temporary password for the user.
static newRandom()
Return an instance with a new, random password.
A primary authentication provider that uses the temporary password field in the 'user' table.
testUserExists( $username, $flags=IDBAccessObject::READ_NORMAL)
Test whether the named user exists.
__construct(IConnectionProvider $dbProvider, UserOptionsLookup $userOptionsLookup, $params=[])
beginPrimaryAccountCreation( $user, $creator, array $reqs)
Start an account creation flow.
sendNewAccountEmail(User $user, User $creatingUser, $password)
Send an email about the new account creation and the temporary password.
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
finishAccountCreation( $user, $creator, AuthenticationResponse $res)
Post-creation callback.Called after the user is added to the database, before secondary authenticatio...
testForAccountCreation( $user, $creator, array $reqs)
Determine whether an account creation may begin.Called from AuthManager::beginAccountCreation()No nee...
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
isTimestampValid( $timestamp)
Check that a temporary password is still valid (hasn't expired).
postInitSetup()
A provider can override this to do any necessary setup after init() is called.
testUserCanAuthenticate( $username)
Test whether the named user can authenticate with this provider.Should return true if the provider ha...
A class containing constants representing the names of configuration variables.
const PasswordReminderResendTime
Name constant for the PasswordReminderResendTime setting, for use with Config::get()
const EnableEmail
Name constant for the EnableEmail setting, for use with Config::get()
const NewPasswordExpiry
Name constant for the NewPasswordExpiry setting, for use with Config::get()
const AllowRequiringEmailForResets
Name constant for the AllowRequiringEmailForResets setting, for use with Config::get()
Represents an invalid password hash.
Parent class for all special pages.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Represents a title within MediaWiki.
Definition Title.php:79
Provides access to user options.
internal since 1.36
Definition User.php:93
sendMail( $subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
Definition User.php:2872
getRequest()
Get the WebRequest object to use with this object.
Definition User.php:2239
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:1568
Interface for database access objects.
Shared interface for rigor levels when dealing with User methods.
Provide primary and replica IDatabase connections.