Merge "debug: Use __CLASS__ to get the name of the class"
[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 * @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
77 */
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();
83
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' );
87 } elseif (
88 ( $providerStatus = $this->authManager->allowsAuthenticationDataChange(
89 new TemporaryPasswordAuthenticationRequest(), false ) )
90 && !$providerStatus->isGood()
91 ) {
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' );
106 }
107
108 $this->permissionCache->set( $user->getName(), $status );
109 }
110
111 return $status;
112 }
113
114 /**
115 * Do a password reset. Authorization is the caller's responsibility.
116 *
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.
120 *
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
129 */
130 public function execute(
131 User $performingUser, $username = null, $email = null
132 ) {
133 if ( !$this->isAllowed( $performingUser )->isGood() ) {
134 throw new LogicException( 'User ' . $performingUser->getName()
135 . ' is not allowed to reset passwords' );
136 }
137
138 $resetRoutes = $this->config->get( 'PasswordResetRoutes' )
139 + [ 'username' => false, 'email' => false ];
140 if ( $resetRoutes['username'] && $username ) {
141 $method = 'username';
142 $users = [ User::newFromName( $username ) ];
143 $email = null;
144 } elseif ( $resetRoutes['email'] && $email ) {
145 if ( !Sanitizer::validateEmail( $email ) ) {
146 return StatusValue::newFatal( 'passwordreset-invalidemail' );
147 }
148 $method = 'email';
149 $users = $this->getUsersByEmail( $email );
150 $username = null;
151 } else {
152 // The user didn't supply any data
153 return StatusValue::newFatal( 'passwordreset-nodata' );
154 }
155
156 // Check for hooks (captcha etc), and allow them to modify the users list
157 $error = [];
158 $data = [
159 'Username' => $username,
160 'Email' => $email,
161 ];
162 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
163 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
164 }
165
166 if ( !$users ) {
167 if ( $method === 'email' ) {
168 // Don't reveal whether or not an email address is in use
169 return StatusValue::newGood( [] );
170 } else {
171 return StatusValue::newFatal( 'noname' );
172 }
173 }
174
175 $firstUser = $users[0];
176
177 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
178 // Don't parse username as wikitext (T67501)
179 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
180 }
181
182 // Check against the rate limiter
183 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
184 return StatusValue::newFatal( 'actionthrottledtext' );
185 }
186
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() ) ) );
192 }
193
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();
197 if ( !$ip ) {
198 return StatusValue::newFatal( 'badipaddress' );
199 }
200
201 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
202
203 $result = StatusValue::newGood();
204 $reqs = [];
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' ) {
212 $reqs[] = $req;
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' );
218 }
219 $result->merge( $status );
220 }
221 }
222
223 $logContext = [
224 'requestingIp' => $ip,
225 'requestingUser' => $performingUser->getName(),
226 'targetUsername' => $username,
227 'targetEmail' => $email,
228 'actualUser' => $firstUser->getName(),
229 ];
230
231 if ( !$result->isGood() ) {
232 $this->logger->info(
233 "{requestingUser} attempted password reset of {actualUser} but failed",
234 $logContext + [ 'errors' => $result->getErrors() ]
235 );
236 return $result;
237 }
238
239 $passwords = [];
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 );
244 }
245
246 $this->logger->info(
247 "{requestingUser} did password reset of {actualUser}",
248 $logContext
249 );
250
251 return StatusValue::newGood( $passwords );
252 }
253
254 /**
255 * Check whether the user is blocked.
256 * Ignores certain types of system blocks that are only meant to force users to log in.
257 * @param User $user
258 * @return bool
259 * @since 1.30
260 */
261 protected function isBlocked( User $user ) {
262 $block = $user->getBlock() ?: $user->getGlobalBlock();
263 if ( !$block ) {
264 return false;
265 }
266 return $block->appliesToPasswordReset();
267 }
268
269 /**
270 * @param string $email
271 * @return User[]
272 * @throws MWException On unexpected database errors
273 */
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 ],
280 __METHOD__,
281 [],
282 $userQuery['joins']
283 );
284
285 if ( !$res ) {
286 // Some sort of database error, probably unreachable
287 throw new MWException( 'Unknown database error in ' . __METHOD__ );
288 }
289
290 $users = [];
291 foreach ( $res as $row ) {
292 $users[] = User::newFromRow( $row );
293 }
294 return $users;
295 }
296 }