You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

333 lines
11 KiB

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