3 * User password reset helper for MediaWiki.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Auth\AuthManager
;
24 use MediaWiki\Auth\TemporaryPasswordAuthenticationRequest
;
25 use MediaWiki\Config\ServiceOptions
;
26 use MediaWiki\Logger\LoggerFactory
;
27 use MediaWiki\MediaWikiServices
;
28 use MediaWiki\Permissions\PermissionManager
;
29 use Psr\Log\LoggerAwareInterface
;
30 use Psr\Log\LoggerAwareTrait
;
31 use Psr\Log\LoggerInterface
;
32 use Wikimedia\Rdbms\ILoadBalancer
;
35 * Helper class for the password reset functionality shared by the web UI and the API.
37 * Requires the TemporaryPasswordPrimaryAuthenticationProvider and the
38 * EmailNotificationSecondaryAuthenticationProvider (or something providing equivalent
39 * functionality) to be enabled.
41 class PasswordReset
implements LoggerAwareInterface
{
44 /** @var ServiceOptions|Config */
47 /** @var AuthManager */
48 protected $authManager;
50 /** @var PermissionManager */
51 protected $permissionManager;
53 /** @var ILoadBalancer */
54 protected $loadBalancer;
57 * In-process cache for isAllowed lookups, by username.
58 * Contains a StatusValue object
61 private $permissionCache;
63 public static $constructorOptions = [
65 'PasswordResetRoutes',
69 * This class is managed by MediaWikiServices, don't instantiate directly.
71 * @param ServiceOptions|Config $config
72 * @param AuthManager $authManager
73 * @param PermissionManager $permissionManager
74 * @param ILoadBalancer|null $loadBalancer
75 * @param LoggerInterface|null $logger
77 public function __construct(
79 AuthManager
$authManager,
80 PermissionManager
$permissionManager,
81 ILoadBalancer
$loadBalancer = null,
82 LoggerInterface
$logger = null
84 $this->config
= $config;
85 $this->authManager
= $authManager;
86 $this->permissionManager
= $permissionManager;
88 if ( !$loadBalancer ) {
89 wfDeprecated( 'Not passing LoadBalancer to ' . __METHOD__
, '1.34' );
90 $loadBalancer = MediaWikiServices
::getInstance()->getDBLoadBalancer();
92 $this->loadBalancer
= $loadBalancer;
95 wfDeprecated( 'Not passing LoggerInterface to ' . __METHOD__
, '1.34' );
96 $logger = LoggerFactory
::getInstance( 'authentication' );
98 $this->logger
= $logger;
100 $this->permissionCache
= new MapCacheLRU( 1 );
104 * Check if a given user has permission to use this functionality.
106 * @since 1.29 Second argument for displayPassword removed.
107 * @return StatusValue
109 public function isAllowed( User
$user ) {
110 $status = $this->permissionCache
->get( $user->getName() );
112 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' );
113 $status = StatusValue
::newGood();
115 if ( !is_array( $resetRoutes ) ||
!in_array( true, $resetRoutes, true ) ) {
116 // Maybe password resets are disabled, or there are no allowable routes
117 $status = StatusValue
::newFatal( 'passwordreset-disabled' );
119 ( $providerStatus = $this->authManager
->allowsAuthenticationDataChange(
120 new TemporaryPasswordAuthenticationRequest(), false ) )
121 && !$providerStatus->isGood()
123 // Maybe the external auth plugin won't allow local password changes
124 $status = StatusValue
::newFatal( 'resetpass_forbidden-reason',
125 $providerStatus->getMessage() );
126 } elseif ( !$this->config
->get( 'EnableEmail' ) ) {
127 // Maybe email features have been disabled
128 $status = StatusValue
::newFatal( 'passwordreset-emaildisabled' );
129 } elseif ( !$this->permissionManager
->userHasRight( $user, 'editmyprivateinfo' ) ) {
130 // Maybe not all users have permission to change private data
131 $status = StatusValue
::newFatal( 'badaccess' );
132 } elseif ( $this->isBlocked( $user ) ) {
133 // Maybe the user is blocked (check this here rather than relying on the parent
134 // method as we have a more specific error message to use here and we want to
135 // ignore some types of blocks)
136 $status = StatusValue
::newFatal( 'blocked-mailpassword' );
139 $this->permissionCache
->set( $user->getName(), $status );
146 * Do a password reset. Authorization is the caller's responsibility.
148 * Process the form. At this point we know that the user passes all the criteria in
149 * userCanExecute(), and if the data array contains 'Username', etc, then Username
150 * resets are allowed.
152 * @since 1.29 Fourth argument for displayPassword removed.
153 * @param User $performingUser The user that does the password reset
154 * @param string|null $username The user whose password is reset
155 * @param string|null $email Alternative way to specify the user
156 * @return StatusValue Will contain the passwords as a username => password array if the
157 * $displayPassword flag was set
158 * @throws LogicException When the user is not allowed to perform the action
159 * @throws MWException On unexpected DB errors
161 public function execute(
162 User
$performingUser, $username = null, $email = null
164 if ( !$this->isAllowed( $performingUser )->isGood() ) {
165 throw new LogicException( 'User ' . $performingUser->getName()
166 . ' is not allowed to reset passwords' );
169 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' )
170 +
[ 'username' => false, 'email' => false ];
171 if ( $resetRoutes['username'] && $username ) {
172 $method = 'username';
173 $users = [ User
::newFromName( $username ) ];
175 } elseif ( $resetRoutes['email'] && $email ) {
176 if ( !Sanitizer
::validateEmail( $email ) ) {
177 return StatusValue
::newFatal( 'passwordreset-invalidemail' );
180 $users = $this->getUsersByEmail( $email );
183 // The user didn't supply any data
184 return StatusValue
::newFatal( 'passwordreset-nodata' );
187 // Check for hooks (captcha etc), and allow them to modify the users list
190 'Username' => $username,
193 if ( !Hooks
::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
194 return StatusValue
::newFatal( Message
::newFromSpecifier( $error ) );
198 if ( $method === 'email' ) {
199 // Don't reveal whether or not an email address is in use
200 return StatusValue
::newGood( [] );
202 return StatusValue
::newFatal( 'noname' );
206 $firstUser = $users[0];
208 if ( !$firstUser instanceof User ||
!$firstUser->getId() ) {
209 // Don't parse username as wikitext (T67501)
210 return StatusValue
::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
213 // Check against the rate limiter
214 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
215 return StatusValue
::newFatal( 'actionthrottledtext' );
218 // All the users will have the same email address
219 if ( !$firstUser->getEmail() ) {
220 // This won't be reachable from the email route, so safe to expose the username
221 return StatusValue
::newFatal( wfMessage( 'noemail',
222 wfEscapeWikiText( $firstUser->getName() ) ) );
225 // We need to have a valid IP address for the hook, but per T20347, we should
226 // send the user's name if they're logged in.
227 $ip = $performingUser->getRequest()->getIP();
229 return StatusValue
::newFatal( 'badipaddress' );
232 Hooks
::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
234 $result = StatusValue
::newGood();
236 foreach ( $users as $user ) {
237 $req = TemporaryPasswordAuthenticationRequest
::newRandom();
238 $req->username
= $user->getName();
239 $req->mailpassword
= true;
240 $req->caller
= $performingUser->getName();
241 $status = $this->authManager
->allowsAuthenticationDataChange( $req, true );
242 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
244 } elseif ( $result->isGood() ) {
245 // only record the first error, to avoid exposing the number of users having the
246 // same email address
247 if ( $status->getValue() === 'ignored' ) {
248 $status = StatusValue
::newFatal( 'passwordreset-ignored' );
250 $result->merge( $status );
255 'requestingIp' => $ip,
256 'requestingUser' => $performingUser->getName(),
257 'targetUsername' => $username,
258 'targetEmail' => $email,
259 'actualUser' => $firstUser->getName(),
262 if ( !$result->isGood() ) {
264 "{requestingUser} attempted password reset of {actualUser} but failed",
265 $logContext +
[ 'errors' => $result->getErrors() ]
271 foreach ( $reqs as $req ) {
272 // This is adding a new temporary password, not intentionally changing anything
273 // (even though it might technically invalidate an old temporary password).
274 $this->authManager
->changeAuthenticationData( $req, /* $isAddition */ true );
278 "{requestingUser} did password reset of {actualUser}",
282 return StatusValue
::newGood( $passwords );
286 * Check whether the user is blocked.
287 * Ignores certain types of system blocks that are only meant to force users to log in.
292 protected function isBlocked( User
$user ) {
293 $block = $user->getBlock() ?
: $user->getGlobalBlock();
297 return $block->appliesToPasswordReset();
301 * @param string $email
303 * @throws MWException On unexpected database errors
305 protected function getUsersByEmail( $email ) {
306 $userQuery = User
::getQueryInfo();
307 $res = $this->loadBalancer
->getConnectionRef( DB_REPLICA
)->select(
308 $userQuery['tables'],
309 $userQuery['fields'],
310 [ 'user_email' => $email ],
317 // Some sort of database error, probably unreachable
318 throw new MWException( 'Unknown database error in ' . __METHOD__
);
322 foreach ( $res as $row ) {
323 $users[] = User
::newFromRow( $row );