LostController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Core\Controller;
  8. use Exception;
  9. use OC\Authentication\TwoFactorAuth\Manager;
  10. use OC\Core\Events\BeforePasswordResetEvent;
  11. use OC\Core\Events\PasswordResetEvent;
  12. use OC\Core\Exception\ResetPasswordException;
  13. use OC\Security\RateLimiting\Exception\RateLimitExceededException;
  14. use OC\Security\RateLimiting\Limiter;
  15. use OCP\AppFramework\Controller;
  16. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  17. use OCP\AppFramework\Http\Attribute\OpenAPI;
  18. use OCP\AppFramework\Http\JSONResponse;
  19. use OCP\AppFramework\Http\TemplateResponse;
  20. use OCP\AppFramework\Services\IInitialState;
  21. use OCP\Defaults;
  22. use OCP\Encryption\IEncryptionModule;
  23. use OCP\Encryption\IManager;
  24. use OCP\EventDispatcher\IEventDispatcher;
  25. use OCP\HintException;
  26. use OCP\IConfig;
  27. use OCP\IL10N;
  28. use OCP\IRequest;
  29. use OCP\IURLGenerator;
  30. use OCP\IUser;
  31. use OCP\IUserManager;
  32. use OCP\Mail\IMailer;
  33. use OCP\Security\VerificationToken\InvalidTokenException;
  34. use OCP\Security\VerificationToken\IVerificationToken;
  35. use Psr\Log\LoggerInterface;
  36. use function array_filter;
  37. use function count;
  38. use function reset;
  39. /**
  40. * Class LostController
  41. *
  42. * Successfully changing a password will emit the post_passwordReset hook.
  43. *
  44. * @package OC\Core\Controller
  45. */
  46. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  47. class LostController extends Controller {
  48. protected string $from;
  49. public function __construct(
  50. string $appName,
  51. IRequest $request,
  52. private IURLGenerator $urlGenerator,
  53. private IUserManager $userManager,
  54. private Defaults $defaults,
  55. private IL10N $l10n,
  56. private IConfig $config,
  57. string $defaultMailAddress,
  58. private IManager $encryptionManager,
  59. private IMailer $mailer,
  60. private LoggerInterface $logger,
  61. private Manager $twoFactorManager,
  62. private IInitialState $initialState,
  63. private IVerificationToken $verificationToken,
  64. private IEventDispatcher $eventDispatcher,
  65. private Limiter $limiter,
  66. ) {
  67. parent::__construct($appName, $request);
  68. $this->from = $defaultMailAddress;
  69. }
  70. /**
  71. * Someone wants to reset their password:
  72. *
  73. * @PublicPage
  74. * @NoCSRFRequired
  75. * @BruteForceProtection(action=passwordResetEmail)
  76. * @AnonRateThrottle(limit=10, period=300)
  77. */
  78. #[FrontpageRoute(verb: 'GET', url: '/lostpassword/reset/form/{token}/{userId}')]
  79. public function resetform(string $token, string $userId): TemplateResponse {
  80. try {
  81. $this->checkPasswordResetToken($token, $userId);
  82. } catch (Exception $e) {
  83. if ($this->config->getSystemValue('lost_password_link', '') !== 'disabled'
  84. || ($e instanceof InvalidTokenException
  85. && !in_array($e->getCode(), [InvalidTokenException::TOKEN_NOT_FOUND, InvalidTokenException::USER_UNKNOWN]))
  86. ) {
  87. $response = new TemplateResponse(
  88. 'core', 'error', [
  89. "errors" => [["error" => $e->getMessage()]]
  90. ],
  91. TemplateResponse::RENDER_AS_GUEST
  92. );
  93. $response->throttle();
  94. return $response;
  95. }
  96. return new TemplateResponse('core', 'error', [
  97. 'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
  98. ],
  99. TemplateResponse::RENDER_AS_GUEST
  100. );
  101. }
  102. $this->initialState->provideInitialState('resetPasswordUser', $userId);
  103. $this->initialState->provideInitialState('resetPasswordTarget',
  104. $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token])
  105. );
  106. return new TemplateResponse(
  107. 'core',
  108. 'login',
  109. [],
  110. 'guest'
  111. );
  112. }
  113. /**
  114. * @throws Exception
  115. */
  116. protected function checkPasswordResetToken(string $token, string $userId): void {
  117. try {
  118. $user = $this->userManager->get($userId);
  119. $this->verificationToken->check($token, $user, 'lostpassword', $user ? $user->getEMailAddress() : '', true);
  120. } catch (InvalidTokenException $e) {
  121. $error = $e->getCode() === InvalidTokenException::TOKEN_EXPIRED
  122. ? $this->l10n->t('Could not reset password because the token is expired')
  123. : $this->l10n->t('Could not reset password because the token is invalid');
  124. throw new Exception($error, (int)$e->getCode(), $e);
  125. }
  126. }
  127. private function error(string $message, array $additional = []): array {
  128. return array_merge(['status' => 'error', 'msg' => $message], $additional);
  129. }
  130. private function success(array $data = []): array {
  131. return array_merge($data, ['status' => 'success']);
  132. }
  133. /**
  134. * @PublicPage
  135. * @BruteForceProtection(action=passwordResetEmail)
  136. * @AnonRateThrottle(limit=10, period=300)
  137. */
  138. #[FrontpageRoute(verb: 'POST', url: '/lostpassword/email')]
  139. public function email(string $user): JSONResponse {
  140. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  141. return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
  142. }
  143. $user = trim($user);
  144. if (strlen($user) > 255) {
  145. return new JSONResponse($this->error($this->l10n->t('Unsupported email length (>255)')));
  146. }
  147. \OCP\Util::emitHook(
  148. '\OCA\Files_Sharing\API\Server2Server',
  149. 'preLoginNameUsedAsUserName',
  150. ['uid' => &$user]
  151. );
  152. // FIXME: use HTTP error codes
  153. try {
  154. $this->sendEmail($user);
  155. } catch (ResetPasswordException $e) {
  156. // Ignore the error since we do not want to leak this info
  157. $this->logger->warning('Could not send password reset email: ' . $e->getMessage());
  158. } catch (Exception $e) {
  159. $this->logger->error($e->getMessage(), ['exception' => $e]);
  160. }
  161. $response = new JSONResponse($this->success());
  162. $response->throttle();
  163. return $response;
  164. }
  165. /**
  166. * @PublicPage
  167. * @BruteForceProtection(action=passwordResetEmail)
  168. * @AnonRateThrottle(limit=10, period=300)
  169. */
  170. #[FrontpageRoute(verb: 'POST', url: '/lostpassword/set/{token}/{userId}')]
  171. public function setPassword(string $token, string $userId, string $password, bool $proceed): JSONResponse {
  172. if ($this->encryptionManager->isEnabled() && !$proceed) {
  173. $encryptionModules = $this->encryptionManager->getEncryptionModules();
  174. foreach ($encryptionModules as $module) {
  175. /** @var IEncryptionModule $instance */
  176. $instance = call_user_func($module['callback']);
  177. // this way we can find out whether per-user keys are used or a system wide encryption key
  178. if ($instance->needDetailedAccessList()) {
  179. return new JSONResponse($this->error('', ['encryption' => true]));
  180. }
  181. }
  182. }
  183. try {
  184. $this->checkPasswordResetToken($token, $userId);
  185. $user = $this->userManager->get($userId);
  186. $this->eventDispatcher->dispatchTyped(new BeforePasswordResetEvent($user, $password));
  187. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
  188. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  189. throw new HintException('Password too long', $this->l10n->t('Password is too long. Maximum allowed length is 469 characters.'));
  190. }
  191. if (!$user->setPassword($password)) {
  192. throw new Exception();
  193. }
  194. $this->eventDispatcher->dispatchTyped(new PasswordResetEvent($user, $password));
  195. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
  196. $this->twoFactorManager->clearTwoFactorPending($userId);
  197. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  198. @\OC::$server->getUserSession()->unsetMagicInCookie();
  199. } catch (HintException $e) {
  200. $response = new JSONResponse($this->error($e->getHint()));
  201. $response->throttle();
  202. return $response;
  203. } catch (Exception $e) {
  204. $response = new JSONResponse($this->error($e->getMessage()));
  205. $response->throttle();
  206. return $response;
  207. }
  208. return new JSONResponse($this->success(['user' => $userId]));
  209. }
  210. /**
  211. * @throws ResetPasswordException
  212. * @throws \OCP\PreConditionNotMetException
  213. */
  214. protected function sendEmail(string $input): void {
  215. $user = $this->findUserByIdOrMail($input);
  216. $email = $user->getEMailAddress();
  217. if (empty($email)) {
  218. throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
  219. }
  220. try {
  221. $this->limiter->registerUserRequest('lostpasswordemail', 5, 1800, $user);
  222. } catch (RateLimitExceededException $e) {
  223. throw new ResetPasswordException('Could not send reset e-mail, 5 of them were already sent in the last 30 minutes', 0, $e);
  224. }
  225. // Generate the token. It is stored encrypted in the database with the
  226. // secret being the users' email address appended with the system secret.
  227. // This makes the token automatically invalidate once the user changes
  228. // their email address.
  229. $token = $this->verificationToken->create($user, 'lostpassword', $email);
  230. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
  231. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  232. 'link' => $link,
  233. ]);
  234. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  235. $emailTemplate->addHeader();
  236. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  237. $emailTemplate->addBodyText(
  238. htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
  239. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  240. );
  241. $emailTemplate->addBodyButton(
  242. htmlspecialchars($this->l10n->t('Reset your password')),
  243. $link,
  244. false
  245. );
  246. $emailTemplate->addFooter();
  247. try {
  248. $message = $this->mailer->createMessage();
  249. $message->setTo([$email => $user->getDisplayName()]);
  250. $message->setFrom([$this->from => $this->defaults->getName()]);
  251. $message->useTemplate($emailTemplate);
  252. $this->mailer->send($message);
  253. } catch (Exception $e) {
  254. // Log the exception and continue
  255. $this->logger->error($e->getMessage(), ['app' => 'core', 'exception' => $e]);
  256. }
  257. }
  258. /**
  259. * @throws ResetPasswordException
  260. */
  261. protected function findUserByIdOrMail(string $input): IUser {
  262. $user = $this->userManager->get($input);
  263. if ($user instanceof IUser) {
  264. if (!$user->isEnabled()) {
  265. throw new ResetPasswordException('Account ' . $user->getUID() . ' is disabled');
  266. }
  267. return $user;
  268. }
  269. $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
  270. return $user->isEnabled();
  271. });
  272. if (count($users) === 1) {
  273. return reset($users);
  274. }
  275. throw new ResetPasswordException('Could not find user ' . $input);
  276. }
  277. }