LostController.php 12 KB

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