Merge "Use IDatabase::buildStringCast in Special:MediaStatistics"
[lhc/web/wiklou.git] / includes / user / PasswordReset.php
1 <?php
2 /**
3 * User password reset helper for MediaWiki.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
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;
28
29 /**
30 * Helper class for the password reset functionality shared by the web UI and the API.
31 *
32 * Requires the TemporaryPasswordPrimaryAuthenticationProvider and the
33 * EmailNotificationSecondaryAuthenticationProvider (or something providing equivalent
34 * functionality) to be enabled.
35 */
36 class PasswordReset implements LoggerAwareInterface {
37 /** @var Config */
38 protected $config;
39
40 /** @var AuthManager */
41 protected $authManager;
42
43 /** @var LoggerInterface */
44 protected $logger;
45
46 /**
47 * In-process cache for isAllowed lookups, by username.
48 * Contains a StatusValue object
49 * @var MapCacheLRU
50 */
51 private $permissionCache;
52
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' );
58 }
59
60 /**
61 * Set the logger instance to use.
62 *
63 * @param LoggerInterface $logger
64 * @since 1.29
65 */
66 public function setLogger( LoggerInterface $logger ) {
67 $this->logger = $logger;
68 }
69
70 /**
71 * Check if a given user has permission to use this functionality.
72 * @param User $user
73 * @since 1.29 Second argument for displayPassword removed.
74 * @return StatusValue
75 */
76 public function isAllowed( User $user ) {
77 $status = $this->permissionCache->get( $user->getName() );
78 if ( !$status ) {
79 $resetRoutes = $this->config->get( 'PasswordResetRoutes' );
80 $status = StatusValue::newGood();
81
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' );
85 } elseif (
86 ( $providerStatus = $this->authManager->allowsAuthenticationDataChange(
87 new TemporaryPasswordAuthenticationRequest(), false ) )
88 && !$providerStatus->isGood()
89 ) {
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' );
104 }
105
106 $this->permissionCache->set( $user->getName(), $status );
107 }
108
109 return $status;
110 }
111
112 /**
113 * Do a password reset. Authorization is the caller's responsibility.
114 *
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.
118 *
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
127 */
128 public function execute(
129 User $performingUser, $username = null, $email = null
130 ) {
131 if ( !$this->isAllowed( $performingUser )->isGood() ) {
132 throw new LogicException( 'User ' . $performingUser->getName()
133 . ' is not allowed to reset passwords' );
134 }
135
136 $resetRoutes = $this->config->get( 'PasswordResetRoutes' )
137 + [ 'username' => false, 'email' => false ];
138 if ( $resetRoutes['username'] && $username ) {
139 $method = 'username';
140 $users = [ User::newFromName( $username ) ];
141 $email = null;
142 } elseif ( $resetRoutes['email'] && $email ) {
143 if ( !Sanitizer::validateEmail( $email ) ) {
144 return StatusValue::newFatal( 'passwordreset-invalidemail' );
145 }
146 $method = 'email';
147 $users = $this->getUsersByEmail( $email );
148 $username = null;
149 } else {
150 // The user didn't supply any data
151 return StatusValue::newFatal( 'passwordreset-nodata' );
152 }
153
154 // Check for hooks (captcha etc), and allow them to modify the users list
155 $error = [];
156 $data = [
157 'Username' => $username,
158 'Email' => $email,
159 ];
160 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
161 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
162 }
163
164 if ( !$users ) {
165 if ( $method === 'email' ) {
166 // Don't reveal whether or not an email address is in use
167 return StatusValue::newGood( [] );
168 } else {
169 return StatusValue::newFatal( 'noname' );
170 }
171 }
172
173 $firstUser = $users[0];
174
175 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
176 // Don't parse username as wikitext (T67501)
177 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
178 }
179
180 // Check against the rate limiter
181 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
182 return StatusValue::newFatal( 'actionthrottledtext' );
183 }
184
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() ) ) );
190 }
191
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();
195 if ( !$ip ) {
196 return StatusValue::newFatal( 'badipaddress' );
197 }
198
199 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
200
201 $result = StatusValue::newGood();
202 $reqs = [];
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' ) {
210 $reqs[] = $req;
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' );
216 }
217 $result->merge( $status );
218 }
219 }
220
221 $logContext = [
222 'requestingIp' => $ip,
223 'requestingUser' => $performingUser->getName(),
224 'targetUsername' => $username,
225 'targetEmail' => $email,
226 'actualUser' => $firstUser->getName(),
227 ];
228
229 if ( !$result->isGood() ) {
230 $this->logger->info(
231 "{requestingUser} attempted password reset of {actualUser} but failed",
232 $logContext + [ 'errors' => $result->getErrors() ]
233 );
234 return $result;
235 }
236
237 $passwords = [];
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 );
242 }
243
244 $this->logger->info(
245 "{requestingUser} did password reset of {actualUser}",
246 $logContext
247 );
248
249 return StatusValue::newGood( $passwords );
250 }
251
252 /**
253 * Check whether the user is blocked.
254 * Ignores certain types of system blocks that are only meant to force users to log in.
255 * @param User $user
256 * @return bool
257 * @since 1.30
258 */
259 protected function isBlocked( User $user ) {
260 $block = $user->getBlock() ?: $user->getGlobalBlock();
261 if ( !$block ) {
262 return false;
263 }
264 return $block->appliesToPasswordReset();
265 }
266
267 /**
268 * @param string $email
269 * @return User[]
270 * @throws MWException On unexpected database errors
271 */
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 ],
278 __METHOD__,
279 [],
280 $userQuery['joins']
281 );
282
283 if ( !$res ) {
284 // Some sort of database error, probably unreachable
285 throw new MWException( 'Unknown database error in ' . __METHOD__ );
286 }
287
288 $users = [];
289 foreach ( $res as $row ) {
290 $users[] = User::newFromRow( $row );
291 }
292 return $users;
293 }
294 }