LostController.php 12 KB

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