Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / user / PasswordReset.php
blobc1aef22ba19f910a06372af51f658ad4744594ac
1 <?php
2 /**
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
20 * @file
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;
29 /**
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 {
37 /** @var Config */
38 protected $config;
40 /** @var AuthManager */
41 protected $authManager;
43 /** @var LoggerInterface */
44 protected $logger;
46 /**
47 * In-process cache for isAllowed lookups, by username.
48 * Contains a StatusValue object
49 * @var HashBagOStuff
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' );
60 /**
61 * Set the logger instance to use.
63 * @param LoggerInterface $logger
64 * @since 1.29
66 public function setLogger( LoggerInterface $logger ) {
67 $this->logger = $logger;
70 /**
71 * Check if a given user has permission to use this functionality.
72 * @param User $user
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.
76 * @return StatusValue
78 public function isAllowed( User $user ) {
79 $status = $this->permissionCache->get( $user->getName() );
80 if ( !$status ) {
81 $resetRoutes = $this->config->get( 'PasswordResetRoutes' );
82 $status = StatusValue::newGood();
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(
91 new TemporaryPasswordAuthenticationRequest(), false ) )
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' );
109 $this->permissionCache->set( $user->getName(), $status );
112 return $status;
116 * Do a password reset. Authorization is the caller's responsibility.
118 * Process the form. At this point we know that the user passes all the criteria in
119 * userCanExecute(), and if the data array contains 'Username', etc, then Username
120 * resets are allowed.
122 * @since 1.29 Fourth argument for displayPassword removed.
123 * @param User $performingUser The user that does the password reset
124 * @param string $username The user whose password is reset
125 * @param string $email Alternative way to specify the user
126 * @return StatusValue Will contain the passwords as a username => password array if the
127 * $displayPassword flag was set
128 * @throws LogicException When the user is not allowed to perform the action
129 * @throws MWException On unexpected DB errors
131 public function execute(
132 User $performingUser, $username = null, $email = null
134 if ( !$this->isAllowed( $performingUser )->isGood() ) {
135 throw new LogicException( 'User ' . $performingUser->getName()
136 . ' is not allowed to reset passwords' );
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' );
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' );
157 // Check for hooks (captcha etc), and allow them to modify the users list
158 $error = [];
159 $data = [
160 'Username' => $username,
161 'Email' => $email,
163 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
164 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
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' );
176 $firstUser = $users[0];
178 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
179 // Don't parse username as wikitext (bug 65501)
180 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
183 // Check against the rate limiter
184 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
185 return StatusValue::newFatal( 'actionthrottledtext' );
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() ) ) );
195 // We need to have a valid IP address for the hook, but per bug 18347, 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' );
202 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
204 $result = StatusValue::newGood();
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' );
220 $result->merge( $status );
224 $logContext = [
225 'requestingIp' => $ip,
226 'requestingUser' => $performingUser->getName(),
227 'targetUsername' => $username,
228 'targetEmail' => $email,
229 'actualUser' => $firstUser->getName(),
232 if ( !$result->isGood() ) {
233 $this->logger->info(
234 "{requestingUser} attempted password reset of {actualUser} but failed",
235 $logContext + [ 'errors' => $result->getErrors() ]
237 return $result;
240 $passwords = [];
241 foreach ( $reqs as $req ) {
242 $this->authManager->changeAuthenticationData( $req );
245 $this->logger->info(
246 "{requestingUser} did password reset of {actualUser}",
247 $logContext
250 return StatusValue::newGood( $passwords );
254 * @param string $email
255 * @return User[]
256 * @throws MWException On unexpected database errors
258 protected function getUsersByEmail( $email ) {
259 $res = wfGetDB( DB_REPLICA )->select(
260 'user',
261 User::selectFields(),
262 [ 'user_email' => $email ],
263 __METHOD__
266 if ( !$res ) {
267 // Some sort of database error, probably unreachable
268 throw new MWException( 'Unknown database error in ' . __METHOD__ );
271 $users = [];
272 foreach ( $res as $row ) {
273 $users[] = User::newFromRow( $row );
275 return $users;