MediaWiki  1.29.1
PasswordReset.php
Go to the documentation of this file.
1 <?php
25 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
28 
36 class PasswordReset implements LoggerAwareInterface {
38  protected $config;
39 
41  protected $authManager;
42 
44  protected $logger;
45 
52 
53  public function __construct( Config $config, AuthManager $authManager ) {
54  $this->config = $config;
55  $this->authManager = $authManager;
56  $this->permissionCache = new HashBagOStuff( [ 'maxKeys' => 1 ] );
57  $this->logger = LoggerFactory::getInstance( 'authentication' );
58  }
59 
66  public function setLogger( LoggerInterface $logger ) {
67  $this->logger = $logger;
68  }
69 
78  public function isAllowed( User $user ) {
79  $status = $this->permissionCache->get( $user->getName() );
80  if ( !$status ) {
81  $resetRoutes = $this->config->get( 'PasswordResetRoutes' );
83 
84  if ( !is_array( $resetRoutes ) ||
85  !in_array( true, array_values( $resetRoutes ), true )
86  ) {
87  // Maybe password resets are disabled, or there are no allowable routes
88  $status = StatusValue::newFatal( 'passwordreset-disabled' );
89  } elseif (
90  ( $providerStatus = $this->authManager->allowsAuthenticationDataChange(
92  && !$providerStatus->isGood()
93  ) {
94  // Maybe the external auth plugin won't allow local password changes
95  $status = StatusValue::newFatal( 'resetpass_forbidden-reason',
96  $providerStatus->getMessage() );
97  } elseif ( !$this->config->get( 'EnableEmail' ) ) {
98  // Maybe email features have been disabled
99  $status = StatusValue::newFatal( 'passwordreset-emaildisabled' );
100  } elseif ( !$user->isAllowed( 'editmyprivateinfo' ) ) {
101  // Maybe not all users have permission to change private data
102  $status = StatusValue::newFatal( 'badaccess' );
103  } elseif ( $user->isBlocked() ) {
104  // Maybe the user is blocked (check this here rather than relying on the parent
105  // method as we have a more specific error message to use here
106  $status = StatusValue::newFatal( 'blocked-mailpassword' );
107  }
108 
109  $this->permissionCache->set( $user->getName(), $status );
110  }
111 
112  return $status;
113  }
114 
131  public function execute(
132  User $performingUser, $username = null, $email = null
133  ) {
134  if ( !$this->isAllowed( $performingUser )->isGood() ) {
135  throw new LogicException( 'User ' . $performingUser->getName()
136  . ' is not allowed to reset passwords' );
137  }
138 
139  $resetRoutes = $this->config->get( 'PasswordResetRoutes' )
140  + [ 'username' => false, 'email' => false ];
141  if ( $resetRoutes['username'] && $username ) {
142  $method = 'username';
143  $users = [ User::newFromName( $username ) ];
144  $email = null;
145  } elseif ( $resetRoutes['email'] && $email ) {
146  if ( !Sanitizer::validateEmail( $email ) ) {
147  return StatusValue::newFatal( 'passwordreset-invalidemail' );
148  }
149  $method = 'email';
150  $users = $this->getUsersByEmail( $email );
151  $username = null;
152  } else {
153  // The user didn't supply any data
154  return StatusValue::newFatal( 'passwordreset-nodata' );
155  }
156 
157  // Check for hooks (captcha etc), and allow them to modify the users list
158  $error = [];
159  $data = [
160  'Username' => $username,
161  'Email' => $email,
162  ];
163  if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
164  return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
165  }
166 
167  if ( !$users ) {
168  if ( $method === 'email' ) {
169  // Don't reveal whether or not an email address is in use
170  return StatusValue::newGood( [] );
171  } else {
172  return StatusValue::newFatal( 'noname' );
173  }
174  }
175 
176  $firstUser = $users[0];
177 
178  if ( !$firstUser instanceof User || !$firstUser->getId() ) {
179  // Don't parse username as wikitext (T67501)
180  return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
181  }
182 
183  // Check against the rate limiter
184  if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
185  return StatusValue::newFatal( 'actionthrottledtext' );
186  }
187 
188  // All the users will have the same email address
189  if ( !$firstUser->getEmail() ) {
190  // This won't be reachable from the email route, so safe to expose the username
191  return StatusValue::newFatal( wfMessage( 'noemail',
192  wfEscapeWikiText( $firstUser->getName() ) ) );
193  }
194 
195  // We need to have a valid IP address for the hook, but per T20347, we should
196  // send the user's name if they're logged in.
197  $ip = $performingUser->getRequest()->getIP();
198  if ( !$ip ) {
199  return StatusValue::newFatal( 'badipaddress' );
200  }
201 
202  Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
203 
205  $reqs = [];
206  foreach ( $users as $user ) {
207  $req = TemporaryPasswordAuthenticationRequest::newRandom();
208  $req->username = $user->getName();
209  $req->mailpassword = true;
210  $req->caller = $performingUser->getName();
211  $status = $this->authManager->allowsAuthenticationDataChange( $req, true );
212  if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
213  $reqs[] = $req;
214  } elseif ( $result->isGood() ) {
215  // only record the first error, to avoid exposing the number of users having the
216  // same email address
217  if ( $status->getValue() === 'ignored' ) {
218  $status = StatusValue::newFatal( 'passwordreset-ignored' );
219  }
220  $result->merge( $status );
221  }
222  }
223 
224  $logContext = [
225  'requestingIp' => $ip,
226  'requestingUser' => $performingUser->getName(),
227  'targetUsername' => $username,
228  'targetEmail' => $email,
229  'actualUser' => $firstUser->getName(),
230  ];
231 
232  if ( !$result->isGood() ) {
233  $this->logger->info(
234  "{requestingUser} attempted password reset of {actualUser} but failed",
235  $logContext + [ 'errors' => $result->getErrors() ]
236  );
237  return $result;
238  }
239 
240  $passwords = [];
241  foreach ( $reqs as $req ) {
242  $this->authManager->changeAuthenticationData( $req );
243  }
244 
245  $this->logger->info(
246  "{requestingUser} did password reset of {actualUser}",
247  $logContext
248  );
249 
250  return StatusValue::newGood( $passwords );
251  }
252 
258  protected function getUsersByEmail( $email ) {
259  $res = wfGetDB( DB_REPLICA )->select(
260  'user',
262  [ 'user_email' => $email ],
263  __METHOD__
264  );
265 
266  if ( !$res ) {
267  // Some sort of database error, probably unreachable
268  throw new MWException( 'Unknown database error in ' . __METHOD__ );
269  }
270 
271  $users = [];
272  foreach ( $res as $row ) {
273  $users[] = User::newFromRow( $row );
274  }
275  return $users;
276  }
277 }
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
User\getId
getId()
Get the user's ID.
Definition: User.php:2200
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
PasswordReset\getUsersByEmail
getUsersByEmail( $email)
Definition: PasswordReset.php:258
PasswordReset\$logger
LoggerInterface $logger
Definition: PasswordReset.php:44
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1954
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$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 account $user
Definition: hooks.txt:246
$req
this hook is for auditing only $req
Definition: hooks.txt:990
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:556
$res
$res
Definition: database.txt:21
User\pingLimiter
pingLimiter( $action='edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
Definition: User.php:1901
User\newFromRow
static newFromRow( $row, $data=null)
Create a new user object from a user row.
Definition: User.php:643
php
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
User\getRequest
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:3587
MWException
MediaWiki exception.
Definition: MWException.php:26
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
PasswordReset\isAllowed
isAllowed(User $user)
Check if a given user has permission to use this functionality.
Definition: PasswordReset.php:78
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:76
PasswordReset\__construct
__construct(Config $config, AuthManager $authManager)
Definition: PasswordReset.php:53
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1657
MediaWiki\Auth\AuthManager
This serves as the entry point to the authentication system.
Definition: AuthManager.php:82
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MediaWiki\Auth\TemporaryPasswordAuthenticationRequest
This represents the intention to set a temporary password for the user.
Definition: TemporaryPasswordAuthenticationRequest.php:31
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
PasswordReset\$permissionCache
HashBagOStuff $permissionCache
In-process cache for isAllowed lookups, by username.
Definition: PasswordReset.php:51
wfMessage
either a unescaped string or a HtmlArmor object 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
User\selectFields
static selectFields()
Return the list of user fields that should be selected to create a new user object.
Definition: User.php:5444
PasswordReset\$authManager
AuthManager $authManager
Definition: PasswordReset.php:41
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
PasswordReset\setLogger
setLogger(LoggerInterface $logger)
Set the logger instance to use.
Definition: PasswordReset.php:66
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:783
PasswordReset\execute
execute(User $performingUser, $username=null, $email=null)
Do a password reset.
Definition: PasswordReset.php:131
PasswordReset
Helper class for the password reset functionality shared by the web UI and the API.
Definition: PasswordReset.php:36
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2225
PasswordReset\$config
Config $config
Definition: PasswordReset.php:38