LostController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. if (strlen($user) > 255) {
  175. return new JSONResponse($this->error($this->l10n->t('Unsupported email length (>255)')));
  176. }
  177. \OCP\Util::emitHook(
  178. '\OCA\Files_Sharing\API\Server2Server',
  179. 'preLoginNameUsedAsUserName',
  180. ['uid' => &$user]
  181. );
  182. // FIXME: use HTTP error codes
  183. try {
  184. $this->sendEmail($user);
  185. } catch (ResetPasswordException $e) {
  186. // Ignore the error since we do not want to leak this info
  187. $this->logger->warning('Could not send password reset email: ' . $e->getMessage());
  188. } catch (Exception $e) {
  189. $this->logger->error($e->getMessage(), ['exception' => $e]);
  190. }
  191. $response = new JSONResponse($this->success());
  192. $response->throttle();
  193. return $response;
  194. }
  195. /**
  196. * @PublicPage
  197. * @BruteForceProtection(action=passwordResetEmail)
  198. * @AnonRateThrottle(limit=10, period=300)
  199. */
  200. #[FrontpageRoute(verb: 'POST', url: '/lostpassword/set/{token}/{userId}')]
  201. public function setPassword(string $token, string $userId, string $password, bool $proceed): JSONResponse {
  202. if ($this->encryptionManager->isEnabled() && !$proceed) {
  203. $encryptionModules = $this->encryptionManager->getEncryptionModules();
  204. foreach ($encryptionModules as $module) {
  205. /** @var IEncryptionModule $instance */
  206. $instance = call_user_func($module['callback']);
  207. // this way we can find out whether per-user keys are used or a system wide encryption key
  208. if ($instance->needDetailedAccessList()) {
  209. return new JSONResponse($this->error('', ['encryption' => true]));
  210. }
  211. }
  212. }
  213. try {
  214. $this->checkPasswordResetToken($token, $userId);
  215. $user = $this->userManager->get($userId);
  216. $this->eventDispatcher->dispatchTyped(new BeforePasswordResetEvent($user, $password));
  217. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
  218. if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
  219. throw new HintException('Password too long', $this->l10n->t('Password is too long. Maximum allowed length is 469 characters.'));
  220. }
  221. if (!$user->setPassword($password)) {
  222. throw new Exception();
  223. }
  224. $this->eventDispatcher->dispatchTyped(new PasswordResetEvent($user, $password));
  225. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
  226. $this->twoFactorManager->clearTwoFactorPending($userId);
  227. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  228. @\OC::$server->getUserSession()->unsetMagicInCookie();
  229. } catch (HintException $e) {
  230. $response = new JSONResponse($this->error($e->getHint()));
  231. $response->throttle();
  232. return $response;
  233. } catch (Exception $e) {
  234. $response = new JSONResponse($this->error($e->getMessage()));
  235. $response->throttle();
  236. return $response;
  237. }
  238. return new JSONResponse($this->success(['user' => $userId]));
  239. }
  240. /**
  241. * @throws ResetPasswordException
  242. * @throws \OCP\PreConditionNotMetException
  243. */
  244. protected function sendEmail(string $input): void {
  245. $user = $this->findUserByIdOrMail($input);
  246. $email = $user->getEMailAddress();
  247. if (empty($email)) {
  248. throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
  249. }
  250. try {
  251. $this->limiter->registerUserRequest('lostpasswordemail', 5, 1800, $user);
  252. } catch (RateLimitExceededException $e) {
  253. throw new ResetPasswordException('Could not send reset e-mail, 5 of them were already sent in the last 30 minutes', 0, $e);
  254. }
  255. // Generate the token. It is stored encrypted in the database with the
  256. // secret being the users' email address appended with the system secret.
  257. // This makes the token automatically invalidate once the user changes
  258. // their email address.
  259. $token = $this->verificationToken->create($user, 'lostpassword', $email);
  260. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
  261. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  262. 'link' => $link,
  263. ]);
  264. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  265. $emailTemplate->addHeader();
  266. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  267. $emailTemplate->addBodyText(
  268. htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
  269. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  270. );
  271. $emailTemplate->addBodyButton(
  272. htmlspecialchars($this->l10n->t('Reset your password')),
  273. $link,
  274. false
  275. );
  276. $emailTemplate->addFooter();
  277. try {
  278. $message = $this->mailer->createMessage();
  279. $message->setTo([$email => $user->getDisplayName()]);
  280. $message->setFrom([$this->from => $this->defaults->getName()]);
  281. $message->useTemplate($emailTemplate);
  282. $this->mailer->send($message);
  283. } catch (Exception $e) {
  284. // Log the exception and continue
  285. $this->logger->error($e->getMessage(), ['app' => 'core', 'exception' => $e]);
  286. }
  287. }
  288. /**
  289. * @throws ResetPasswordException
  290. */
  291. protected function findUserByIdOrMail(string $input): IUser {
  292. $user = $this->userManager->get($input);
  293. if ($user instanceof IUser) {
  294. if (!$user->isEnabled()) {
  295. throw new ResetPasswordException('Account ' . $user->getUID() . ' is disabled');
  296. }
  297. return $user;
  298. }
  299. $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
  300. return $user->isEnabled();
  301. });
  302. if (count($users) === 1) {
  303. return reset($users);
  304. }
  305. throw new ResetPasswordException('Could not find user ' . $input);
  306. }
  307. }