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. Contains pairs of StatusValue objects
48 * (for false and true value of $displayPassword, respectively).
51 private $permissionCache;
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' );
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.
77 public function isAllowed( User
$user, $displayPassword = false ) {
78 $statuses = $this->permissionCache
->get( $user->getName() );
80 list ( $status, $status2 ) = $statuses;
82 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' );
83 $status = StatusValue
::newGood();
85 if ( !is_array( $resetRoutes ) ||
86 !in_array( true, array_values( $resetRoutes ), true )
88 // Maybe password resets are disabled, or there are no allowable routes
89 $status = StatusValue
::newFatal( 'passwordreset-disabled' );
91 ( $providerStatus = $this->authManager
->allowsAuthenticationDataChange(
92 new TemporaryPasswordAuthenticationRequest(), false ) )
93 && !$providerStatus->isGood()
95 // Maybe the external auth plugin won't allow local password changes
96 $status = StatusValue
::newFatal( 'resetpass_forbidden-reason',
97 $providerStatus->getMessage() );
98 } elseif ( !$this->config
->get( 'EnableEmail' ) ) {
99 // Maybe email features have been disabled
100 $status = StatusValue
::newFatal( 'passwordreset-emaildisabled' );
101 } elseif ( !$user->isAllowed( 'editmyprivateinfo' ) ) {
102 // Maybe not all users have permission to change private data
103 $status = StatusValue
::newFatal( 'badaccess' );
104 } elseif ( $user->isBlocked() ) {
105 // Maybe the user is blocked (check this here rather than relying on the parent
106 // method as we have a more specific error message to use here
107 $status = StatusValue
::newFatal( 'blocked-mailpassword' );
110 $status2 = StatusValue
::newGood();
111 if ( !$user->isAllowed( 'passwordreset' ) ) {
112 $status2 = StatusValue
::newFatal( 'badaccess' );
115 $this->permissionCache
->set( $user->getName(), [ $status, $status2 ] );
118 if ( !$displayPassword ||
!$status->isGood() ) {
126 * Do a password reset. Authorization is the caller's responsibility.
128 * Process the form. At this point we know that the user passes all the criteria in
129 * userCanExecute(), and if the data array contains 'Username', etc, then Username
130 * resets are allowed.
131 * @param User $performingUser The user that does the password reset
132 * @param string $username The user whose password is reset
133 * @param string $email Alternative way to specify the user
134 * @param bool $displayPassword Whether to display the password
135 * @return StatusValue Will contain the passwords as a username => password array if the
136 * $displayPassword flag was set
137 * @throws LogicException When the user is not allowed to perform the action
138 * @throws MWException On unexpected DB errors
140 public function execute(
141 User
$performingUser, $username = null, $email = null, $displayPassword = false
143 if ( !$this->isAllowed( $performingUser, $displayPassword )->isGood() ) {
144 $action = $this->isAllowed( $performingUser )->isGood() ?
'display' : 'reset';
145 throw new LogicException( 'User ' . $performingUser->getName()
146 . ' is not allowed to ' . $action . ' passwords' );
149 $resetRoutes = $this->config
->get( 'PasswordResetRoutes' )
150 +
[ 'username' => false, 'email' => false ];
151 if ( $resetRoutes['username'] && $username ) {
152 $method = 'username';
153 $users = [ User
::newFromName( $username ) ];
155 } elseif ( $resetRoutes['email'] && $email ) {
156 if ( !Sanitizer
::validateEmail( $email ) ) {
157 return StatusValue
::newFatal( 'passwordreset-invalidemail' );
160 $users = $this->getUsersByEmail( $email );
163 // The user didn't supply any data
164 return StatusValue
::newFatal( 'passwordreset-nodata' );
167 // Check for hooks (captcha etc), and allow them to modify the users list
170 'Username' => $username,
172 'Capture' => $displayPassword ?
'1' : null,
174 if ( !Hooks
::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
175 return StatusValue
::newFatal( Message
::newFromSpecifier( $error ) );
179 if ( $method === 'email' ) {
180 // Don't reveal whether or not an email address is in use
181 return StatusValue
::newGood( [] );
183 return StatusValue
::newFatal( 'noname' );
187 $firstUser = $users[0];
189 if ( !$firstUser instanceof User ||
!$firstUser->getId() ) {
190 // Don't parse username as wikitext (bug 65501)
191 return StatusValue
::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
194 // Check against the rate limiter
195 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
196 return StatusValue
::newFatal( 'actionthrottledtext' );
199 // All the users will have the same email address
200 if ( !$firstUser->getEmail() ) {
201 // This won't be reachable from the email route, so safe to expose the username
202 return StatusValue
::newFatal( wfMessage( 'noemail',
203 wfEscapeWikiText( $firstUser->getName() ) ) );
206 // We need to have a valid IP address for the hook, but per bug 18347, we should
207 // send the user's name if they're logged in.
208 $ip = $performingUser->getRequest()->getIP();
210 return StatusValue
::newFatal( 'badipaddress' );
213 Hooks
::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
215 $result = StatusValue
::newGood();
217 foreach ( $users as $user ) {
218 $req = TemporaryPasswordAuthenticationRequest
::newRandom();
219 $req->username
= $user->getName();
220 $req->mailpassword
= true;
221 $req->hasBackchannel
= $displayPassword;
222 $req->caller
= $performingUser->getName();
223 $status = $this->authManager
->allowsAuthenticationDataChange( $req, true );
224 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
226 } elseif ( $result->isGood() ) {
227 // only record the first error, to avoid exposing the number of users having the
228 // same email address
229 if ( $status->getValue() === 'ignored' ) {
230 $status = StatusValue
::newFatal( 'passwordreset-ignored' );
232 $result->merge( $status );
237 'requestingIp' => $ip,
238 'requestingUser' => $performingUser->getName(),
239 'targetUsername' => $username,
240 'targetEmail' => $email,
241 'actualUser' => $firstUser->getName(),
242 'capture' => $displayPassword,
245 if ( !$result->isGood() ) {
247 "{requestingUser} attempted password reset of {actualUser} but failed",
248 $logContext +
[ 'errors' => $result->getErrors() ]
254 foreach ( $reqs as $req ) {
255 $this->authManager
->changeAuthenticationData( $req );
256 // TODO record mail sending errors
257 if ( $displayPassword ) {
258 $passwords[$req->username
] = $req->password
;
262 if ( $displayPassword ) {
263 // The password capture thing is scary, so log
264 // at a higher warning level.
265 $this->logger
->warning(
266 "{requestingUser} did password reset of {actualUser} with password capturing!",
271 "{requestingUser} did password reset of {actualUser}",
276 return StatusValue
::newGood( $passwords );
280 * @param string $email
282 * @throws MWException On unexpected database errors
284 protected function getUsersByEmail( $email ) {
285 $res = wfGetDB( DB_REPLICA
)->select(
287 User
::selectFields(),
288 [ 'user_email' => $email ],
293 // Some sort of database error, probably unreachable
294 throw new MWException( 'Unknown database error in ' . __METHOD__
);
298 foreach ( $res as $row ) {
299 $users[] = User
::newFromRow( $row );