1
0

LostController.php 11 KB

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