MediaWiki REL1_27
TemporaryPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1<?php
22namespace MediaWiki\Auth;
23
24use User;
25
39{
41 protected $emailEnabled = null;
42
44 protected $newPasswordExpiry = null;
45
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
92 public function getAuthenticationRequests( $action, array $options ) {
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 ) {
119 $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
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
163 $username = User::getCanonicalName( $username, 'usable' );
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
190 public function testUserExists( $username, $flags = User::READ_NORMAL ) {
191 $username = User::getCanonicalName( $username, 'usable' );
192 if ( $username === false ) {
193 return false;
194 }
195
196 list( $db, $options ) = \DBAccessObjectUtils::getDBOptions( $flags );
197 return (bool)wfGetDB( $db )->selectField(
198 [ 'user' ],
199 [ 'user_id' ],
200 [ 'user_name' => $username ],
201 __METHOD__,
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 &&
284 get_class( $req ) === TemporaryPasswordAuthenticationRequest::class
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 ) {
317 $reqs, TemporaryPasswordAuthenticationRequest::class
318 );
319
320 $ret = \StatusValue::newGood();
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 ) {
340 $reqs, TemporaryPasswordAuthenticationRequest::class
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}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static isValid( $ip)
Validate an IP address.
Definition IP.php:113
Represents an invalid password hash.
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.
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.
beginPrimaryAccountCreation( $user, $creator, array $reqs)
Start an account creation flow.
getAuthenticationRequests( $action, array $options)
Return the applicable list of AuthenticationRequests.
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.
testForAccountCreation( $user, $creator, array $reqs)
Determine whether an account creation may begin.
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
isTimestampValid( $timestamp)
Check that a temporary password is still valid (hasn't expired).
testUserExists( $username, $flags=User::READ_NORMAL)
Test whether the named user exists.
testUserCanAuthenticate( $username)
Test whether the named user can authenticate with this provider.
static newMainPage()
Create a new Title for the Main Page.
Definition Title.php:569
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
getRequest()
Get the WebRequest object to use with this object.
Definition User.php:3468
$res
Definition database.txt:21
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
const DB_MASTER
Definition Defines.php:48
this hook is for auditing only $req
Definition hooks.txt:968
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:1007
the array() calling protocol came about after MediaWiki 1.4rc1.
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:249
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 unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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:1042
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:1810
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2555
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:767
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1615
if( $limit) $timestamp
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:37
Interface for configuration instances.
Definition Config.php:28
$params