You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LostController.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Haertl <jus@bitgrid.net>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Rémy Jacquin <remy@remyj.fr>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Roeland Jago Douma <roeland@famdouma.nl>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  20. * @author Kate Döen <kate.doeen@nextcloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Core\Controller;
  38. use Exception;
  39. use OC\Authentication\TwoFactorAuth\Manager;
  40. use OC\Core\Events\BeforePasswordResetEvent;
  41. use OC\Core\Events\PasswordResetEvent;
  42. use OC\Core\Exception\ResetPasswordException;
  43. use OC\Security\RateLimiting\Exception\RateLimitExceededException;
  44. use OC\Security\RateLimiting\Limiter;
  45. use OCP\AppFramework\Controller;
  46. use OCP\AppFramework\Http\Attribute\OpenAPI;
  47. use OCP\AppFramework\Http\JSONResponse;
  48. use OCP\AppFramework\Http\TemplateResponse;
  49. use OCP\AppFramework\Services\IInitialState;
  50. use OCP\Defaults;
  51. use OCP\Encryption\IEncryptionModule;
  52. use OCP\Encryption\IManager;
  53. use OCP\EventDispatcher\IEventDispatcher;
  54. use OCP\HintException;
  55. use OCP\IConfig;
  56. use OCP\IL10N;
  57. use OCP\IRequest;
  58. use OCP\IURLGenerator;
  59. use OCP\IUser;
  60. use OCP\IUserManager;
  61. use OCP\Mail\IMailer;
  62. use OCP\Security\VerificationToken\InvalidTokenException;
  63. use OCP\Security\VerificationToken\IVerificationToken;
  64. use Psr\Log\LoggerInterface;
  65. use function array_filter;
  66. use function count;
  67. use function reset;
  68. /**
  69. * Class LostController
  70. *
  71. * Successfully changing a password will emit the post_passwordReset hook.
  72. *
  73. * @package OC\Core\Controller
  74. */
  75. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  76. class LostController extends Controller {
  77. protected string $from;
  78. public function __construct(
  79. string $appName,
  80. IRequest $request,
  81. private IURLGenerator $urlGenerator,
  82. private IUserManager $userManager,
  83. private Defaults $defaults,
  84. private IL10N $l10n,
  85. private IConfig $config,
  86. string $defaultMailAddress,
  87. private IManager $encryptionManager,
  88. private IMailer $mailer,
  89. private LoggerInterface $logger,
  90. private Manager $twoFactorManager,
  91. private IInitialState $initialState,
  92. private IVerificationToken $verificationToken,
  93. private IEventDispatcher $eventDispatcher,
  94. private Limiter $limiter,
  95. ) {
  96. parent::__construct($appName, $request);
  97. $this->from = $defaultMailAddress;
  98. }
  99. /**
  100. * Someone wants to reset their password:
  101. *
  102. * @PublicPage
  103. * @NoCSRFRequired
  104. * @BruteForceProtection(action=passwordResetEmail)
  105. * @AnonRateThrottle(limit=10, period=300)
  106. */
  107. public function resetform(string $token, string $userId): TemplateResponse {
  108. try {
  109. $this->checkPasswordResetToken($token, $userId);
  110. } catch (Exception $e) {
  111. if ($this->config->getSystemValue('lost_password_link', '') !== 'disabled'
  112. || ($e instanceof InvalidTokenException
  113. && !in_array($e->getCode(), [InvalidTokenException::TOKEN_NOT_FOUND, InvalidTokenException::USER_UNKNOWN]))
  114. ) {
  115. $response = new TemplateResponse(
  116. 'core', 'error', [
  117. "errors" => [["error" => $e->getMessage()]]
  118. ],
  119. TemplateResponse::RENDER_AS_GUEST
  120. );
  121. $response->throttle();
  122. return $response;
  123. }
  124. return new TemplateResponse('core', 'error', [
  125. 'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
  126. ],
  127. TemplateResponse::RENDER_AS_GUEST
  128. );
  129. }
  130. $this->initialState->provideInitialState('resetPasswordUser', $userId);
  131. $this->initialState->provideInitialState('resetPasswordTarget',
  132. $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token])
  133. );
  134. return new TemplateResponse(
  135. 'core',
  136. 'login',
  137. [],
  138. 'guest'
  139. );
  140. }
  141. /**
  142. * @throws Exception
  143. */
  144. protected function checkPasswordResetToken(string $token, string $userId): void {
  145. try {
  146. $user = $this->userManager->get($userId);
  147. $this->verificationToken->check($token, $user, 'lostpassword', $user ? $user->getEMailAddress() : '', true);
  148. } catch (InvalidTokenException $e) {
  149. $error = $e->getCode() === InvalidTokenException::TOKEN_EXPIRED
  150. ? $this->l10n->t('Could not reset password because the token is expired')
  151. : $this->l10n->t('Could not reset password because the token is invalid');
  152. throw new Exception($error, (int)$e->getCode(), $e);
  153. }
  154. }
  155. private function error(string $message, array $additional = []): array {
  156. return array_merge(['status' => 'error', 'msg' => $message], $additional);
  157. }
  158. private function success(array $data = []): array {
  159. return array_merge($data, ['status' => 'success']);
  160. }
  161. /**
  162. * @PublicPage
  163. * @BruteForceProtection(action=passwordResetEmail)
  164. * @AnonRateThrottle(limit=10, period=300)
  165. */
  166. public function email(string $user): JSONResponse {
  167. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  168. return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
  169. }
  170. $user = trim($user);
  171. \OCP\Util::emitHook(
  172. '\OCA\Files_Sharing\API\Server2Server',
  173. 'preLoginNameUsedAsUserName',
  174. ['uid' => &$user]
  175. );
  176. // FIXME: use HTTP error codes
  177. try {
  178. $this->sendEmail($user);
  179. } catch (ResetPasswordException $e) {
  180. // Ignore the error since we do not want to leak this info
  181. $this->logger->warning('Could not send password reset email: ' . $e->getMessage());
  182. } catch (Exception $e) {
  183. $this->logger->error($e->getMessage(), ['exception' => $e]);
  184. }
  185. $response = new JSONResponse($this->success());
  186. $response->throttle();
  187. return $response;
  188. }
  189. /**
  190. * @PublicPage
  191. * @BruteForceProtection(action=passwordResetEmail)
  192. * @AnonRateThrottle(limit=10, period=300)
  193. */
  194. public function setPassword(string $token, string $userId, string $password, bool $proceed): JSONResponse {
  195. if ($this->encryptionManager->isEnabled() && !$proceed) {
  196. $encryptionModules = $this->encryptionManager->getEncryptionModules();
  197. foreach ($encryptionModules as $module) {
  198. /** @var IEncryptionModule $instance */
  199. $instance = call_user_func($module['callback']);
  200. // this way we can find out whether per-user keys are used or a system wide encryption key
  201. if ($instance->needDetailedAccessList()) {
  202. return new JSONResponse($this->error('', ['encryption' => true]));
  203. }
  204. }
  205. }
  206. try {
  207. $this->checkPasswordResetToken($token, $userId);
  208. $user = $this->userManager->get($userId);
  209. $this->eventDispatcher->dispatchTyped(new BeforePasswordResetEvent($user, $password));
  210. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
  211. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  212. throw new HintException('Password too long', $this->l10n->t('Password is too long. Maximum allowed length is 469 characters.'));
  213. }
  214. if (!$user->setPassword($password)) {
  215. throw new Exception();
  216. }
  217. $this->eventDispatcher->dispatchTyped(new PasswordResetEvent($user, $password));
  218. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
  219. $this->twoFactorManager->clearTwoFactorPending($userId);
  220. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  221. @\OC::$server->getUserSession()->unsetMagicInCookie();
  222. } catch (HintException $e) {
  223. $response = new JSONResponse($this->error($e->getHint()));
  224. $response->throttle();
  225. return $response;
  226. } catch (Exception $e) {
  227. $response = new JSONResponse($this->error($e->getMessage()));
  228. $response->throttle();
  229. return $response;
  230. }
  231. return new JSONResponse($this->success(['user' => $userId]));
  232. }
  233. /**
  234. * @throws ResetPasswordException
  235. * @throws \OCP\PreConditionNotMetException
  236. */
  237. protected function sendEmail(string $input): void {
  238. $user = $this->findUserByIdOrMail($input);
  239. $email = $user->getEMailAddress();
  240. if (empty($email)) {
  241. throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
  242. }
  243. try {
  244. $this->limiter->registerUserRequest('lostpasswordemail', 5, 1800, $user);
  245. } catch (RateLimitExceededException $e) {
  246. throw new ResetPasswordException('Could not send reset e-mail, 5 of them were already sent in the last 30 minutes', 0, $e);
  247. }
  248. // Generate the token. It is stored encrypted in the database with the
  249. // secret being the users' email address appended with the system secret.
  250. // This makes the token automatically invalidate once the user changes
  251. // their email address.
  252. $token = $this->verificationToken->create($user, 'lostpassword', $email);
  253. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
  254. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  255. 'link' => $link,
  256. ]);
  257. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  258. $emailTemplate->addHeader();
  259. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  260. $emailTemplate->addBodyText(
  261. htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
  262. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  263. );
  264. $emailTemplate->addBodyButton(
  265. htmlspecialchars($this->l10n->t('Reset your password')),
  266. $link,
  267. false
  268. );
  269. $emailTemplate->addFooter();
  270. try {
  271. $message = $this->mailer->createMessage();
  272. $message->setTo([$email => $user->getDisplayName()]);
  273. $message->setFrom([$this->from => $this->defaults->getName()]);
  274. $message->useTemplate($emailTemplate);
  275. $this->mailer->send($message);
  276. } catch (Exception $e) {
  277. // Log the exception and continue
  278. $this->logger->error($e->getMessage(), ['app' => 'core', 'exception' => $e]);
  279. }
  280. }
  281. /**
  282. * @throws ResetPasswordException
  283. */
  284. protected function findUserByIdOrMail(string $input): IUser {
  285. $user = $this->userManager->get($input);
  286. if ($user instanceof IUser) {
  287. if (!$user->isEnabled()) {
  288. throw new ResetPasswordException('User ' . $user->getUID() . ' is disabled');
  289. }
  290. return $user;
  291. }
  292. $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
  293. return $user->isEnabled();
  294. });
  295. if (count($users) === 1) {
  296. return reset($users);
  297. }
  298. throw new ResetPasswordException('Could not find user ' . $input);
  299. }
  300. }