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 Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
27 use MediaWiki\Logger\LoggerFactory
;
30 * Helper class for the password reset functionality shared by the web UI and the API.
32 * Requires the TemporaryPasswordPrimaryAuthenticationProvider and the
33 * EmailNotificationSecondaryAuthenticationProvider (or something providing equivalent
34 * functionality) to be enabled.
36 class PasswordReset
implements LoggerAwareInterface
{
40 /** @var AuthManager */
41 protected $authManager;
43 /** @var LoggerInterface */
47 * In-process cache for isAllowed lookups, by username.
48 * Contains a StatusValue object
51 private $permissionCache;
53 public function __construct( Config
$config, AuthManager
$authManager ) {
54 $this->config
= $config;
55 $this->authManager
= $authManager;
56 $this->permissionCache
= new MapCacheLRU( 1 );
57 $this->logger
= LoggerFactory
::getInstance( 'authentication' );
61 * Set the logger instance to use.
63 * @param LoggerInterface $logger
66 public function setLogger( LoggerInterface
$logger ) {
67 $this->logger
= $logger;
71 * Check if a given user has permission to use this functionality.
73 * @since 1.29 Second argument for displayPassword removed.
76 public function isAllowed( User
$user ) {
77 $status = $this->permissionCache
->get( $user->getName() );
79 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' );
80 $status = StatusValue
::newGood();
82 if ( !is_array( $resetRoutes ) ||
!in_array( true, $resetRoutes, true ) ) {
83 // Maybe password resets are disabled, or there are no allowable routes
84 $status = StatusValue
::newFatal( 'passwordreset-disabled' );
86 ( $providerStatus = $this->authManager
->allowsAuthenticationDataChange(
87 new TemporaryPasswordAuthenticationRequest(), false ) )
88 && !$providerStatus->isGood()
90 // Maybe the external auth plugin won't allow local password changes
91 $status = StatusValue
::newFatal( 'resetpass_forbidden-reason',
92 $providerStatus->getMessage() );
93 } elseif ( !$this->config
->get( 'EnableEmail' ) ) {
94 // Maybe email features have been disabled
95 $status = StatusValue
::newFatal( 'passwordreset-emaildisabled' );
96 } elseif ( !$user->isAllowed( 'editmyprivateinfo' ) ) {
97 // Maybe not all users have permission to change private data
98 $status = StatusValue
::newFatal( 'badaccess' );
99 } elseif ( $this->isBlocked( $user ) ) {
100 // Maybe the user is blocked (check this here rather than relying on the parent
101 // method as we have a more specific error message to use here and we want to
102 // ignore some types of blocks)
103 $status = StatusValue
::newFatal( 'blocked-mailpassword' );
106 $this->permissionCache
->set( $user->getName(), $status );
113 * Do a password reset. Authorization is the caller's responsibility.
115 * Process the form. At this point we know that the user passes all the criteria in
116 * userCanExecute(), and if the data array contains 'Username', etc, then Username
117 * resets are allowed.
119 * @since 1.29 Fourth argument for displayPassword removed.
120 * @param User $performingUser The user that does the password reset
121 * @param string|null $username The user whose password is reset
122 * @param string|null $email Alternative way to specify the user
123 * @return StatusValue Will contain the passwords as a username => password array if the
124 * $displayPassword flag was set
125 * @throws LogicException When the user is not allowed to perform the action
126 * @throws MWException On unexpected DB errors
128 public function execute(
129 User
$performingUser, $username = null, $email = null
131 if ( !$this->isAllowed( $performingUser )->isGood() ) {
132 throw new LogicException( 'User ' . $performingUser->getName()
133 . ' is not allowed to reset passwords' );
136 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' )
137 +
[ 'username' => false, 'email' => false ];
138 if ( $resetRoutes['username'] && $username ) {
139 $method = 'username';
140 $users = [ User
::newFromName( $username ) ];
142 } elseif ( $resetRoutes['email'] && $email ) {
143 if ( !Sanitizer
::validateEmail( $email ) ) {
144 return StatusValue
::newFatal( 'passwordreset-invalidemail' );
147 $users = $this->getUsersByEmail( $email );
150 // The user didn't supply any data
151 return StatusValue
::newFatal( 'passwordreset-nodata' );
154 // Check for hooks (captcha etc), and allow them to modify the users list
157 'Username' => $username,
160 if ( !Hooks
::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
161 return StatusValue
::newFatal( Message
::newFromSpecifier( $error ) );
165 if ( $method === 'email' ) {
166 // Don't reveal whether or not an email address is in use
167 return StatusValue
::newGood( [] );
169 return StatusValue
::newFatal( 'noname' );
173 $firstUser = $users[0];
175 if ( !$firstUser instanceof User ||
!$firstUser->getId() ) {
176 // Don't parse username as wikitext (T67501)
177 return StatusValue
::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
180 // Check against the rate limiter
181 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
182 return StatusValue
::newFatal( 'actionthrottledtext' );
185 // All the users will have the same email address
186 if ( !$firstUser->getEmail() ) {
187 // This won't be reachable from the email route, so safe to expose the username
188 return StatusValue
::newFatal( wfMessage( 'noemail',
189 wfEscapeWikiText( $firstUser->getName() ) ) );
192 // We need to have a valid IP address for the hook, but per T20347, we should
193 // send the user's name if they're logged in.
194 $ip = $performingUser->getRequest()->getIP();
196 return StatusValue
::newFatal( 'badipaddress' );
199 Hooks
::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
201 $result = StatusValue
::newGood();
203 foreach ( $users as $user ) {
204 $req = TemporaryPasswordAuthenticationRequest
::newRandom();
205 $req->username
= $user->getName();
206 $req->mailpassword
= true;
207 $req->caller
= $performingUser->getName();
208 $status = $this->authManager
->allowsAuthenticationDataChange( $req, true );
209 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
211 } elseif ( $result->isGood() ) {
212 // only record the first error, to avoid exposing the number of users having the
213 // same email address
214 if ( $status->getValue() === 'ignored' ) {
215 $status = StatusValue
::newFatal( 'passwordreset-ignored' );
217 $result->merge( $status );
222 'requestingIp' => $ip,
223 'requestingUser' => $performingUser->getName(),
224 'targetUsername' => $username,
225 'targetEmail' => $email,
226 'actualUser' => $firstUser->getName(),
229 if ( !$result->isGood() ) {
231 "{requestingUser} attempted password reset of {actualUser} but failed",
232 $logContext +
[ 'errors' => $result->getErrors() ]
238 foreach ( $reqs as $req ) {
239 // This is adding a new temporary password, not intentionally changing anything
240 // (even though it might technically invalidate an old temporary password).
241 $this->authManager
->changeAuthenticationData( $req, /* $isAddition */ true );
245 "{requestingUser} did password reset of {actualUser}",
249 return StatusValue
::newGood( $passwords );
253 * Check whether the user is blocked.
254 * Ignores certain types of system blocks that are only meant to force users to log in.
259 protected function isBlocked( User
$user ) {
260 $block = $user->getBlock() ?
: $user->getGlobalBlock();
264 return $block->appliesToPasswordReset();
268 * @param string $email
270 * @throws MWException On unexpected database errors
272 protected function getUsersByEmail( $email ) {
273 $userQuery = User
::getQueryInfo();
274 $res = wfGetDB( DB_REPLICA
)->select(
275 $userQuery['tables'],
276 $userQuery['fields'],
277 [ 'user_email' => $email ],
284 // Some sort of database error, probably unreachable
285 throw new MWException( 'Unknown database error in ' . __METHOD__
);
289 foreach ( $res as $row ) {
290 $users[] = User
::newFromRow( $row );