Merge "Don't fallback from uk to ru"
[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 HashBagOStuff
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 HashBagOStuff( [ 'maxKeys' => 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 ) ||
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' );
107 }
108
109 $this->permissionCache->set( $user->getName(), $status );
110 }
111
112 return $status;
113 }
114
115 /**
116 * Do a password reset. Authorization is the caller's responsibility.
117 *
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.
121 *
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
130 */
131 public function execute(
132 User $performingUser, $username = null, $email = null
133 ) {
134 if ( !$this->isAllowed( $performingUser )->isGood() ) {
135 throw new LogicException( 'User ' . $performingUser->getName()
136 . ' is not allowed to reset passwords' );
137 }
138
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' );
148 }
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' );
155 }
156
157 // Check for hooks (captcha etc), and allow them to modify the users list
158 $error = [];
159 $data = [
160 'Username' => $username,
161 'Email' => $email,
162 ];
163 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
164 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
165 }
166
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' );
173 }
174 }
175
176 $firstUser = $users[0];
177
178 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
179 // Don't parse username as wikitext (bug 65501)
180 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
181 }
182
183 // Check against the rate limiter
184 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
185 return StatusValue::newFatal( 'actionthrottledtext' );
186 }
187
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() ) ) );
193 }
194
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' );
200 }
201
202 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
203
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' );
219 }
220 $result->merge( $status );
221 }
222 }
223
224 $logContext = [
225 'requestingIp' => $ip,
226 'requestingUser' => $performingUser->getName(),
227 'targetUsername' => $username,
228 'targetEmail' => $email,
229 'actualUser' => $firstUser->getName(),
230 ];
231
232 if ( !$result->isGood() ) {
233 $this->logger->info(
234 "{requestingUser} attempted password reset of {actualUser} but failed",
235 $logContext + [ 'errors' => $result->getErrors() ]
236 );
237 return $result;
238 }
239
240 $passwords = [];
241 foreach ( $reqs as $req ) {
242 $this->authManager->changeAuthenticationData( $req );
243 }
244
245 $this->logger->info(
246 "{requestingUser} did password reset of {actualUser}",
247 $logContext
248 );
249
250 return StatusValue::newGood( $passwords );
251 }
252
253 /**
254 * @param string $email
255 * @return User[]
256 * @throws MWException On unexpected database errors
257 */
258 protected function getUsersByEmail( $email ) {
259 $res = wfGetDB( DB_REPLICA )->select(
260 'user',
261 User::selectFields(),
262 [ 'user_email' => $email ],
263 __METHOD__
264 );
265
266 if ( !$res ) {
267 // Some sort of database error, probably unreachable
268 throw new MWException( 'Unknown database error in ' . __METHOD__ );
269 }
270
271 $users = [];
272 foreach ( $res as $row ) {
273 $users[] = User::newFromRow( $row );
274 }
275 return $users;
276 }
277 }