LostController.php 11 KB

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