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
99 protected function getPasswordResetData( $username, $data ) {
100 // Always reset
101 return (object)[
102 'msg' => wfMessage( 'resetpass-temp-emailed' ),
103 'hard' => true,
104 ];
105 }
106
107 public function getAuthenticationRequests( $action, array $options ) {
108 switch ( $action ) {
110 return [ new PasswordAuthenticationRequest() ];
111
114
116 // Allow named users creating a new account to email a temporary password to a given address
117 // in case they are creating an account for somebody else.
118 // This isn't a likely scenario for account creations by anonymous or temporary users
119 // and is therefore disabled for them (T328718).
120 if (
121 isset( $options['username'] ) &&
122 !$this->userNameUtils->isTemp( $options['username'] ) &&
123 $this->emailEnabled
124 ) {
126 } else {
127 return [];
128 }
129
132
133 default:
134 return [];
135 }
136 }
137
138 public function beginPrimaryAuthentication( array $reqs ) {
139 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
140 if ( !$req || $req->username === null || $req->password === null ) {
142 }
143
144 $username = $this->userNameUtils->getCanonical(
145 $req->username, UserRigorOptions::RIGOR_USABLE );
146 if ( $username === false ) {
148 }
149
150 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
151 if ( !$tempPassHash ) {
153 }
154
155 $status = $this->checkPasswordValidity( $username, $req->password );
156 if ( !$status->isOK() ) {
157 return $this->getFatalPasswordErrorResponse( $username, $status );
158 }
159
160 if ( !$tempPassHash->verify( $req->password ) ||
161 !$this->isTimestampValid( $tempPassTime )
162 ) {
163 return $this->failResponse( $req );
164 }
165
166 // Add an extra log entry since a temporary password is
167 // an unusual way to log in, so its important to keep track
168 // of in case of abuse.
169 $this->logger->info( "{user} successfully logged in using temp password",
170 [
171 'provider' => static::class,
172 'user' => $username,
173 'requestIP' => $this->manager->getRequest()->getIP()
174 ]
175 );
176
177 $this->setPasswordResetFlag( $username, $status );
178
179 return AuthenticationResponse::newPass( $username );
180 }
181
182 public function testUserCanAuthenticate( $username ) {
183 $username = $this->userNameUtils->getCanonical( $username, UserRigorOptions::RIGOR_USABLE );
184 if ( $username === false ) {
185 return false;
186 }
187
188 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username );
189 return $tempPassHash &&
190 !( $tempPassHash instanceof InvalidPassword ) &&
191 $this->isTimestampValid( $tempPassTime );
192 }
193
195 AuthenticationRequest $req, $checkData = true
196 ) {
197 if ( get_class( $req ) !== TemporaryPasswordAuthenticationRequest::class ) {
198 // We don't really ignore it, but this is what the caller expects.
199 return \StatusValue::newGood( 'ignored' );
200 }
201
202 if ( !$checkData ) {
203 return \StatusValue::newGood();
204 }
205
206 $username = $this->userNameUtils->getCanonical(
207 $req->username, UserRigorOptions::RIGOR_USABLE );
208 if ( $username === false ) {
209 return \StatusValue::newGood( 'ignored' );
210 }
211
212 [ $tempPassHash, $tempPassTime ] = $this->getTemporaryPassword( $username, IDBAccessObject::READ_LATEST );
213 if ( !$tempPassHash ) {
214 return \StatusValue::newGood( 'ignored' );
215 }
216
217 $sv = \StatusValue::newGood();
218 if ( $req->password !== null ) {
219 $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
220
221 if ( $req->mailpassword ) {
222 if ( !$this->emailEnabled ) {
223 return \StatusValue::newFatal( 'passwordreset-emaildisabled' );
224 }
225
226 // We don't check whether the user has an email address;
227 // that information should not be exposed to the caller.
228
229 // do not allow temporary password creation within
230 // $wgPasswordReminderResendTime from the last attempt
231 if (
232 $this->passwordReminderResendTime
233 && $tempPassTime
234 && time() < (int)wfTimestamp( TS_UNIX, $tempPassTime )
235 + $this->passwordReminderResendTime * 3600
236 ) {
237 // Round the time in hours to 3 d.p., in case someone is specifying
238 // minutes or seconds.
239 return \StatusValue::newFatal( 'throttled-mailpassword',
240 round( $this->passwordReminderResendTime, 3 ) );
241 }
242
243 if ( !$req->caller ) {
244 return \StatusValue::newFatal( 'passwordreset-nocaller' );
245 }
246 if ( !IPUtils::isValid( $req->caller ) ) {
247 $caller = User::newFromName( $req->caller );
248 if ( !$caller ) {
249 return \StatusValue::newFatal( 'passwordreset-nosuchcaller', $req->caller );
250 }
251 }
252 }
253 }
254 return $sv;
255 }
256
258 $username = $req->username !== null ?
259 $this->userNameUtils->getCanonical( $req->username, UserRigorOptions::RIGOR_USABLE ) : false;
260 if ( $username === false ) {
261 return;
262 }
263
264 $sendMail = false;
265 if ( $req->action !== AuthManager::ACTION_REMOVE &&
266 get_class( $req ) === TemporaryPasswordAuthenticationRequest::class
267 ) {
268 $tempPassHash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
269 $tempPassTime = wfTimestampNow();
270 $sendMail = $req->mailpassword;
271 // Prevent other temp password providers from sending duplicate emails
272 $req->mailpassword = false;
273 } else {
274 // Invalidate the temporary password when any other auth is reset, or when removing
275 $tempPassHash = PasswordFactory::newInvalidPassword();
276 $tempPassTime = null;
277 }
278
279 $this->setTemporaryPassword( $username, $tempPassHash, $tempPassTime );
280
281 if ( $sendMail ) {
282 $this->maybeSendPasswordResetEmail( $req );
283 }
284 }
285
286 public function accountCreationType() {
287 return self::TYPE_CREATE;
288 }
289
290 public function testForAccountCreation( $user, $creator, array $reqs ) {
293 $reqs, TemporaryPasswordAuthenticationRequest::class
294 );
295
296 $ret = \StatusValue::newGood();
297 if ( $req ) {
298 if ( $req->mailpassword ) {
299 if ( !$this->emailEnabled ) {
300 $ret->merge( \StatusValue::newFatal( 'emaildisabled' ) );
301 } elseif ( !$user->getEmail() ) {
302 $ret->merge( \StatusValue::newFatal( 'noemailcreate' ) );
303 }
304 }
305
306 $ret->merge(
307 $this->checkPasswordValidity( $user->getName(), $req->password )
308 );
309 }
310 return $ret;
311 }
312
313 public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
316 $reqs, TemporaryPasswordAuthenticationRequest::class
317 );
318 if ( $req && $req->username !== null && $req->password !== null ) {
319 // Nothing we can do yet, because the user isn't in the DB yet
320 if ( $req->username !== $user->getName() ) {
321 $req = clone $req;
322 $req->username = $user->getName();
323 }
324
325 if ( $req->mailpassword ) {
326 // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
327 $this->manager->setAuthenticationSessionData( 'no-email', true );
328 }
329
330 $ret = AuthenticationResponse::newPass( $req->username );
331 $ret->createRequest = $req;
332 return $ret;
333 }
335 }
336
337 public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
339 $req = $res->createRequest;
340 $mailpassword = $req->mailpassword;
341 // Prevent providerChangeAuthenticationData() from sending the wrong email
342 $req->mailpassword = false;
343
344 // Now that the user is in the DB, set the password on it.
346
347 if ( $mailpassword ) {
348 $this->maybeSendNewAccountEmail( $user, $creator, $req->password );
349 }
350
351 return $mailpassword ? 'byemail' : null;
352 }
353
360 protected function isTimestampValid( $timestamp ) {
361 $time = wfTimestampOrNull( TS_MW, $timestamp );
362 if ( $time !== null ) {
363 $expiry = (int)wfTimestamp( TS_UNIX, $time ) + $this->newPasswordExpiry;
364 if ( time() >= $expiry ) {
365 return false;
366 }
367 }
368 return true;
369 }
370
382 protected function maybeSendNewAccountEmail( User $user, User $creatingUser, $password ): void {
383 // Send email after DB commit (the callback does not run in case of DB rollback)
384 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
385 function () use ( $user, $creatingUser, $password ) {
386 $this->sendNewAccountEmail( $user, $creatingUser, $password );
387 },
388 __METHOD__
389 );
390 }
391
400 protected function sendNewAccountEmail( User $user, User $creatingUser, $password ): void {
401 $ip = $creatingUser->getRequest()->getIP();
402 // @codeCoverageIgnoreStart
403 if ( !$ip ) {
404 return;
405 }
406 // @codeCoverageIgnoreEnd
407
408 $this->getHookRunner()->onUser__mailPasswordInternal( $creatingUser, $ip, $user );
409
410 $mainPageUrl = Title::newMainPage()->getCanonicalURL();
411 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
412 $subjectMessage = wfMessage( 'createaccount-title' )->inLanguage( $userLanguage );
413 $bodyMessage = wfMessage( 'createaccount-text', $ip, $user->getName(), $password,
414 '<' . $mainPageUrl . '>', round( $this->newPasswordExpiry / 86400 ) )
415 ->inLanguage( $userLanguage );
416
417 $status = $user->sendMail( $subjectMessage->text(), $bodyMessage->text() );
418
419 // @codeCoverageIgnoreStart
420 if ( !$status->isGood() ) {
421 $this->logger->warning( 'Could not send account creation email: ' .
422 $status->getWikiText( false, false, 'en' ) );
423 }
424 // @codeCoverageIgnoreEnd
425 }
426
436 // Send email after DB commit (the callback does not run in case of DB rollback)
437 $this->dbProvider->getPrimaryDatabase()->onTransactionCommitOrIdle(
438 function () use ( $req ) {
439 $this->sendPasswordResetEmail( $req );
440 },
441 __METHOD__
442 );
443 }
444
452 $user = User::newFromName( $req->username );
453 if ( !$user ) {
454 return;
455 }
456 $userLanguage = $this->userOptionsLookup->getOption( $user, 'language' );
457 $callerIsAnon = IPUtils::isValid( $req->caller );
458 $callerName = $callerIsAnon ? $req->caller : User::newFromName( $req->caller )->getName();
459 $passwordMessage = wfMessage( 'passwordreset-emailelement', $user->getName(),
460 $req->password )->inLanguage( $userLanguage );
461 $emailMessage = wfMessage( $callerIsAnon ? 'passwordreset-emailtext-ip'
462 : 'passwordreset-emailtext-user' )->inLanguage( $userLanguage );
463 $body = $emailMessage->params( $callerName, $passwordMessage->text(), 1,
464 '<' . Title::newMainPage()->getCanonicalURL() . '>',
465 round( $this->newPasswordExpiry / 86400 ) )->text();
466
467 // Hint that the user can choose to require email address to request a temporary password
468 if (
469 !$this->userOptionsLookup->getBoolOption( $user, 'requireemail' )
470 ) {
471 $url = SpecialPage::getTitleFor( 'Preferences', false, 'mw-prefsection-personal-email' )
472 ->getCanonicalURL();
473 $body .= "\n\n" . wfMessage( 'passwordreset-emailtext-require-email' )
474 ->inLanguage( $userLanguage )
475 ->params( "<$url>" )
476 ->text();
477 }
478
479 $emailTitle = wfMessage( 'passwordreset-emailtitle' )->inLanguage( $userLanguage );
480 $user->sendMail( $emailTitle->text(), $body );
481 }
482
499 abstract protected function getTemporaryPassword( string $username, $flags = IDBAccessObject::READ_NORMAL ): array;
500
509 abstract protected function setTemporaryPassword( string $username, Password $tempPassHash, $tempPassTime ): void;
510}
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.
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.
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).
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.
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.
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...
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.
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:2863
getEmail()
Get the user's e-mail address.
Definition User.php:1884
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:1566
Shared interface for rigor levels when dealing with User methods.
Provide primary and replica IDatabase connections.
Interface for database access objects.