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 * @param bool $displayPassword If set, also check whether the user is allowed to reset the
74 * password of another user and see the temporary password.
75 * @since 1.29 Second argument for displayPassword removed.
78 public function isAllowed( User
$user ) {
79 $status = $this->permissionCache
->get( $user->getName() );
81 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' );
82 $status = StatusValue
::newGood();
84 if ( !is_array( $resetRoutes ) ||
!in_array( true, $resetRoutes, true ) ) {
85 // Maybe password resets are disabled, or there are no allowable routes
86 $status = StatusValue
::newFatal( 'passwordreset-disabled' );
88 ( $providerStatus = $this->authManager
->allowsAuthenticationDataChange(
89 new TemporaryPasswordAuthenticationRequest(), false ) )
90 && !$providerStatus->isGood()
92 // Maybe the external auth plugin won't allow local password changes
93 $status = StatusValue
::newFatal( 'resetpass_forbidden-reason',
94 $providerStatus->getMessage() );
95 } elseif ( !$this->config
->get( 'EnableEmail' ) ) {
96 // Maybe email features have been disabled
97 $status = StatusValue
::newFatal( 'passwordreset-emaildisabled' );
98 } elseif ( !$user->isAllowed( 'editmyprivateinfo' ) ) {
99 // Maybe not all users have permission to change private data
100 $status = StatusValue
::newFatal( 'badaccess' );
101 } elseif ( $this->isBlocked( $user ) ) {
102 // Maybe the user is blocked (check this here rather than relying on the parent
103 // method as we have a more specific error message to use here and we want to
104 // ignore some types of blocks)
105 $status = StatusValue
::newFatal( 'blocked-mailpassword' );
108 $this->permissionCache
->set( $user->getName(), $status );
115 * Do a password reset. Authorization is the caller's responsibility.
117 * Process the form. At this point we know that the user passes all the criteria in
118 * userCanExecute(), and if the data array contains 'Username', etc, then Username
119 * resets are allowed.
121 * @since 1.29 Fourth argument for displayPassword removed.
122 * @param User $performingUser The user that does the password reset
123 * @param string|null $username The user whose password is reset
124 * @param string|null $email Alternative way to specify the user
125 * @return StatusValue Will contain the passwords as a username => password array if the
126 * $displayPassword flag was set
127 * @throws LogicException When the user is not allowed to perform the action
128 * @throws MWException On unexpected DB errors
130 public function execute(
131 User
$performingUser, $username = null, $email = null
133 if ( !$this->isAllowed( $performingUser )->isGood() ) {
134 throw new LogicException( 'User ' . $performingUser->getName()
135 . ' is not allowed to reset passwords' );
138 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' )
139 +
[ 'username' => false, 'email' => false ];
140 if ( $resetRoutes['username'] && $username ) {
141 $method = 'username';
142 $users = [ User
::newFromName( $username ) ];
144 } elseif ( $resetRoutes['email'] && $email ) {
145 if ( !Sanitizer
::validateEmail( $email ) ) {
146 return StatusValue
::newFatal( 'passwordreset-invalidemail' );
149 $users = $this->getUsersByEmail( $email );
152 // The user didn't supply any data
153 return StatusValue
::newFatal( 'passwordreset-nodata' );
156 // Check for hooks (captcha etc), and allow them to modify the users list
159 'Username' => $username,
162 if ( !Hooks
::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
163 return StatusValue
::newFatal( Message
::newFromSpecifier( $error ) );
167 if ( $method === 'email' ) {
168 // Don't reveal whether or not an email address is in use
169 return StatusValue
::newGood( [] );
171 return StatusValue
::newFatal( 'noname' );
175 $firstUser = $users[0];
177 if ( !$firstUser instanceof User ||
!$firstUser->getId() ) {
178 // Don't parse username as wikitext (T67501)
179 return StatusValue
::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
182 // Check against the rate limiter
183 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
184 return StatusValue
::newFatal( 'actionthrottledtext' );
187 // All the users will have the same email address
188 if ( !$firstUser->getEmail() ) {
189 // This won't be reachable from the email route, so safe to expose the username
190 return StatusValue
::newFatal( wfMessage( 'noemail',
191 wfEscapeWikiText( $firstUser->getName() ) ) );
194 // We need to have a valid IP address for the hook, but per T20347, we should
195 // send the user's name if they're logged in.
196 $ip = $performingUser->getRequest()->getIP();
198 return StatusValue
::newFatal( 'badipaddress' );
201 Hooks
::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
203 $result = StatusValue
::newGood();
205 foreach ( $users as $user ) {
206 $req = TemporaryPasswordAuthenticationRequest
::newRandom();
207 $req->username
= $user->getName();
208 $req->mailpassword
= true;
209 $req->caller
= $performingUser->getName();
210 $status = $this->authManager
->allowsAuthenticationDataChange( $req, true );
211 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
213 } elseif ( $result->isGood() ) {
214 // only record the first error, to avoid exposing the number of users having the
215 // same email address
216 if ( $status->getValue() === 'ignored' ) {
217 $status = StatusValue
::newFatal( 'passwordreset-ignored' );
219 $result->merge( $status );
224 'requestingIp' => $ip,
225 'requestingUser' => $performingUser->getName(),
226 'targetUsername' => $username,
227 'targetEmail' => $email,
228 'actualUser' => $firstUser->getName(),
231 if ( !$result->isGood() ) {
233 "{requestingUser} attempted password reset of {actualUser} but failed",
234 $logContext +
[ 'errors' => $result->getErrors() ]
240 foreach ( $reqs as $req ) {
241 // This is adding a new temporary password, not intentionally changing anything
242 // (even though it might technically invalidate an old temporary password).
243 $this->authManager
->changeAuthenticationData( $req, /* $isAddition */ true );
247 "{requestingUser} did password reset of {actualUser}",
251 return StatusValue
::newGood( $passwords );
255 * Check whether the user is blocked.
256 * Ignores certain types of system blocks that are only meant to force users to log in.
261 protected function isBlocked( User
$user ) {
262 $block = $user->getBlock() ?
: $user->getGlobalBlock();
266 return $block->appliesToPasswordReset();
270 * @param string $email
272 * @throws MWException On unexpected database errors
274 protected function getUsersByEmail( $email ) {
275 $userQuery = User
::getQueryInfo();
276 $res = wfGetDB( DB_REPLICA
)->select(
277 $userQuery['tables'],
278 $userQuery['fields'],
279 [ 'user_email' => $email ],
286 // Some sort of database error, probably unreachable
287 throw new MWException( 'Unknown database error in ' . __METHOD__
);
291 foreach ( $res as $row ) {
292 $users[] = User
::newFromRow( $row );