MediaWiki master
AbstractTemporaryPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1<?php
22namespace MediaWiki\Auth;
23
33use Wikimedia\IPUtils;
36
50{
52 protected $emailEnabled = null;
53
55 protected $newPasswordExpiry = null;
56
59
62
72 public function __construct(
75 $params = []
76 ) {
77 parent::__construct( $params );
78
79 if ( isset( $params['emailEnabled'] ) ) {
80 $this->emailEnabled = (bool)$params['emailEnabled'];
81 }
82 if ( isset( $params['newPasswordExpiry'] ) ) {
83 $this->newPasswordExpiry = (int)$params['newPasswordExpiry'];
84 }
85 if ( isset( $params['passwordReminderResendTime'] ) ) {
86 $this->passwordReminderResendTime = $params['passwordReminderResendTime'];
87 }
88 $this->dbProvider = $dbProvider;
89 $this->userOptionsLookup = $userOptionsLookup;
90 }
91
92 protected function postInitSetup() {
93 $this->emailEnabled ??= $this->config->get( MainConfigNames::EnableEmail );
94 $this->newPasswordExpiry ??= $this->config->get( MainConfigNames::NewPasswordExpiry );
95 $this->passwordReminderResendTime ??=
97 }
98
100 protected function getPasswordResetData( $username, $data ) {
101 // Always reset
102 return (object)[
103 'msg' => wfMessage( 'resetpass-temp-emailed' ),
104 'hard' => true,
105 ];
106 }
107
109 public function getAuthenticationRequests( $action, array $options ) {
110 switch ( $action ) {
112 return [ new PasswordAuthenticationRequest() ];
113
116
118 // Allow named users creating a new account to email a temporary password to a given address
119 // in case they are creating an account for somebody else.
120 // This isn't a likely scenario for account creations by anonymous or temporary users
121 // and is therefore disabled for them (T328718).
122 if (
123 isset( $options['username'] ) &&
124 !$this->userNameUtils->isTemp( $options['username'] ) &&
125 $this->emailEnabled
126 ) {
128 } else {
129 return [];
130 }
131
134
135 default:
136 return [];
137 }
138 }
139
141 public function beginPrimaryAuthentication( array $reqs ) {
142 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
143 if ( !$req || $req->username === null || $req->password === null ) {
145 }
146
147 $username = $this->userNameUtils->getCanonical(
148 $req->username, UserRigorOptions::RIGOR_USABLE );
149 if ( $username === false ) {
151 }
152
153 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
154 if ( !$tempPassHash ) {
156 }
157
158 $status = $this->checkPasswordValidity( $username, $req->password );
159 if ( !$status->isOK() ) {
160 return $this->getFatalPasswordErrorResponse( $username, $status );
161 }
162
163 if ( !$tempPassHash->verify( $req->password ) ||
164 !$this->isTimestampValid( $tempPassTime )
165 ) {
166 return $this->failResponse( $req );
167 }
168
169 // Add an extra log entry since a temporary password is
170 // an unusual way to log in, so its important to keep track
171 // of in case of abuse.
172 $this->logger->info( "{user} successfully logged in using temp password",
173 [
174 'provider' => static::class,
175 'user' => $username,
176 'requestIP' => $this->manager->getRequest()->getIP()
177 ]
178 );
179
180 $this->setPasswordResetFlag( $username, $status );
181
182 return AuthenticationResponse::newPass( $username );
183 }
184
186 public function testUserCanAuthenticate( $username ) {
187 $username = $this->userNameUtils->getCanonical( $username, UserRigorOptions::RIGOR_USABLE );
188 if ( $username === false ) {
189 return false;
190 }
191
192 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username );
193 return $tempPassHash &&
194 !( $tempPassHash instanceof InvalidPassword ) &&
195 $this->isTimestampValid( $tempPassTime );
196 }
197
200 AuthenticationRequest $req, $checkData = true
201 ) {
202 if ( get_class( $req ) !== TemporaryPasswordAuthenticationRequest::class ) {
203 // We don't really ignore it, but this is what the caller expects.
204 return \StatusValue::newGood( 'ignored' );
205 }
206
207 if ( !$checkData ) {
208 return \StatusValue::newGood();
209 }
210
211 $username = $this->userNameUtils->getCanonical(
212 $req->username, UserRigorOptions::RIGOR_USABLE );
213 if ( $username === false ) {
214 return \StatusValue::newGood( 'ignored' );
215 }
216
217 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
218 if ( !$tempPassHash ) {
219 return \StatusValue::newGood( 'ignored' );
220 }
221
222 $sv = \StatusValue::newGood();
223 if ( $req->password !== null ) {
224 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
225
226 if ( $req->mailpassword ) {
227 if ( !$this->emailEnabled ) {
228 return \StatusValue::newFatal( 'passwordreset-emaildisabled' );
229 }
230
231 // We don't check whether the user has an email address;
232 // that information should not be exposed to the caller.
233
234 // do not allow temporary password creation within
235 // $wgPasswordReminderResendTime from the last attempt
236 if (
237 $this->passwordReminderResendTime
238 && $tempPassTime
239 && time() < (int)wfTimestamp( TS_UNIX, $tempPassTime )
240 + $this->passwordReminderResendTime * 3600
241 ) {
242 // Round the time in hours to 3 d.p., in case someone is specifying
243 // minutes or seconds.
244 return \StatusValue::newFatal( 'throttled-mailpassword',
245 round( $this->passwordReminderResendTime, 3 ) );
246 }
247
248 if ( !$req->caller ) {
249 return \StatusValue::newFatal( 'passwordreset-nocaller' );
250 }
251 if ( !IPUtils::isValid( $req->caller ) ) {
252 $caller = User::newFromName( $req->caller );
253 if ( !$caller ) {
254 return \StatusValue::newFatal( 'passwordreset-nosuchcaller', $req->caller );
255 }
256 }
257 }
258 }
259 return $sv;
260 }
261
263 $username = $req->username !== null ?
264 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE ) : false;
265 if ( $username === false ) {
266 return;
267 }
268
269 $sendMail = false;
270 if ( $req->action !== AuthManager::ACTION_REMOVE &&
271 get_class( $req ) === TemporaryPasswordAuthenticationRequest::class
272 ) {
273 $tempPassHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
274 $tempPassTime = wfTimestampNow();
275 $sendMail = $req->mailpassword;
276 // Prevent other temp password providers from sending duplicate emails
277 $req->mailpassword = false;
278 } else {
279 // Invalidate the temporary password when any other auth is reset, or when removing
280 $tempPassHash = PasswordFactory::newInvalidPassword();
281 $tempPassTime = null;
282 }
283
284 $this->setTemporaryPassword( $username, $tempPassHash, $tempPassTime );
285
286 if ( $sendMail ) {
287 $this->maybeSendPasswordResetEmail( $req );
288 }
289 }
290
292 public function accountCreationType() {
293 return self::TYPE_CREATE;
294 }
295
297 public function testForAccountCreation( $user, $creator, array $reqs ) {
300 $reqs, TemporaryPasswordAuthenticationRequest::class
301 );
302
303 $ret = \StatusValue::newGood();
304 if ( $req ) {
305 if ( $req->mailpassword ) {
306 if ( !$this->emailEnabled ) {
307 $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
308 } elseif ( !$user->getEmail() ) {
309 $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
310 }
311 }
312
313 $ret->merge(
314 $this->checkPasswordValidity( $user->getName(), $req->password )
315 );
316 }
317 return $ret;
318 }
319
321 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
324 $reqs, TemporaryPasswordAuthenticationRequest::class
325 );
326 if ( $req && $req->username !== null && $req->password !== null ) {
327 // Nothing we can do yet, because the user isn't in the DB yet
328 if ( $req->username !== $user->getName() ) {
329 $req = clone $req;
330 $req->username = $user->getName();
331 }
332
333 if ( $req->mailpassword ) {
334 // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
335 $this->manager->setAuthenticationSessionData( 'no-email', true );
336 }
337
338 $ret = AuthenticationResponse::newPass( $req->username );
339 $ret->createRequest = $req;
340 return $ret;
341 }
343 }
344
346 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
348 $req = $res->createRequest;
349 $mailpassword = $req->mailpassword;
350 // Prevent providerChangeAuthenticationData() from sending the wrong email
351 $req->mailpassword = false;
352
353 // Now that the user is in the DB, set the password on it.
355
356 if ( $mailpassword ) {
357 $this->maybeSendNewAccountEmail( $user, $creator, $req->password );
358 }
359
360 return $mailpassword ? 'byemail' : null;
361 }
362
369 protected function isTimestampValid( $timestamp ) {
370 $time = wfTimestampOrNull( TS_MW, $timestamp );
371 if ( $time !== null ) {
372 $expiry = (int)wfTimestamp( TS_UNIX, $time ) + $this->newPasswordExpiry;
373 if ( time() >= $expiry ) {
374 return false;
375 }
376 }
377 return true;
378 }
379
391 protected function maybeSendNewAccountEmail( User $user, User $creatingUser, $password ): void {
392 // Send email after DB commit (the callback does not run in case of DB rollback)
393 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
394 function () use ( $user, $creatingUser, $password ) {
395 $this->sendNewAccountEmail( $user, $creatingUser, $password );
396 },
397 __METHOD__
398 );
399 }
400
409 protected function sendNewAccountEmail( User $user, User $creatingUser, $password ): void {
410 $ip = $creatingUser->getRequest()->getIP();
411 // @codeCoverageIgnoreStart
412 if ( !$ip ) {
413 return;
414 }
415 // @codeCoverageIgnoreEnd
416
417 $this->getHookRunner()->onUser__mailPasswordInternal( $creatingUser, $ip, $user );
418
419 $mainPageUrl = Title::newMainPage()->getCanonicalURL();
420 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
421 $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
422 $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
423 '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
424 ->inLanguage( $userLanguage );
425
426 $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
427
428 // @codeCoverageIgnoreStart
429 if ( !$status->isGood() ) {
430 $this->logger->warning( 'Could not send account creation email: ' .
431 $status->getWikiText( false, false, 'en' ) );
432 }
433 // @codeCoverageIgnoreEnd
434 }
435
445 // Send email after DB commit (the callback does not run in case of DB rollback)
446 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
447 function () use ( $req ) {
448 $this->sendPasswordResetEmail( $req );
449 },
450 __METHOD__
451 );
452 }
453
461 $user = User::newFromName( $req->username );
462 if ( !$user ) {
463 return;
464 }
465 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
466 $callerIsAnon = IPUtils::isValid( $req->caller );
467 $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
468 $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
469 $req->password )->inLanguage( $userLanguage );
470 $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
471 : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
472 $body = $emailMessage->params( $callerName, $passwordMessage->text(), 1,
473 '<' . Title::newMainPage()->getCanonicalURL() . '>',
474 round( $this->newPasswordExpiry / 86400 ) )->text();
475
476 // Hint that the user can choose to require email address to request a temporary password
477 if (
478 !$this->userOptionsLookup->getBoolOption( $user, 'requireemail' )
479 ) {
480 $url = SpecialPage::getTitleFor( 'Preferences', false, 'mw-prefsection-personal-email' )
481 ->getCanonicalURL();
482 $body .= "\n\n" . wfMessage( 'passwordreset-emailtext-require-email' )
483 ->inLanguage( $userLanguage )
484 ->params( "<$url>" )
485 ->text();
486 }
487
488 $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
489 $user->sendMail( $emailTitle->text(), $body );
490 }
491
508 abstract protected function getTemporaryPassword( string $username, $flags = IDBAccessObject::READ_NORMAL ): array;
509
518 abstract protected function setTemporaryPassword( string $username, Password $tempPassHash, $tempPassTime ): void;
519}
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
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.
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.
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.
sendPasswordResetEmail(TemporaryPasswordAuthenticationRequest $req)
Send an email about the new temporary password.
__construct(IConnectionProvider $dbProvider, UserOptionsLookup $userOptionsLookup, $params=[])
isTimestampValid( $timestamp)
Check that a temporary password is still valid (hasn't expired).
getPasswordResetData( $username, $data)
Get password reset data, if any.to override \stdClass|null { 'hard' => bool, 'msg' => Message }
finishAccountCreation( $user, $creator, AuthenticationResponse $res)
Post-creation callback.Called after the user is added to the database, before secondary authenticatio...
maybeSendPasswordResetEmail(TemporaryPasswordAuthenticationRequest $req)
Wait for the new temporary password to be recorded, and if successful, send an email about it.
setTemporaryPassword(string $username, Password $tempPassHash, $tempPassTime)
Set a temporary password and the time when it was generated.
beginPrimaryAuthentication(array $reqs)
Start an authentication flow.AuthenticationResponse Expected responses:PASS: The user is authenticate...
postInitSetup()
A provider can override this to do any necessary setup after init() is called.
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.passwords)Return StatusValue::newGood( 'ignored' ) if y...
maybeSendNewAccountEmail(User $user, User $creatingUser, $password)
Wait for the new account to be recorded, and if successful, send an email about the new account creat...
beginPrimaryAccountCreation( $user, $creator, array $reqs)
Start an account creation flow.AuthenticationResponse Expected responses:PASS: The user may be create...
testUserCanAuthenticate( $username)
Test whether the named user can authenticate with this provider.Should return true if the provider ha...
getTemporaryPassword(string $username, $flags=IDBAccessObject::READ_NORMAL)
Return a tuple of temporary password and the time when it was generated.
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 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()
Represents an invalid password hash.
Factory class for creating and checking Password objects.
Represents a password hash for use in authentication.
Definition Password.php:66
Parent class for all special pages.
Represents a title within MediaWiki.
Definition Title.php:78
Provides access to user options.
User class for the MediaWiki software.
Definition User.php:123
sendMail( $subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
Definition User.php:2897
getEmail()
Get the user's e-mail address.
Definition User.php:1903
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:1585
Shared interface for rigor levels when dealing with User methods.
Provide primary and replica IDatabase connections.
Interface for database access objects.