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