LostController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Julius Haertl <jus@bitgrid.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC\Core\Controller;
  32. use OC\Authentication\TwoFactorAuth\Manager;
  33. use OC\HintException;
  34. use \OCP\AppFramework\Controller;
  35. use OCP\AppFramework\Http\JSONResponse;
  36. use \OCP\AppFramework\Http\TemplateResponse;
  37. use OCP\AppFramework\Utility\ITimeFactory;
  38. use OCP\Defaults;
  39. use OCP\Encryption\IEncryptionModule;
  40. use OCP\Encryption\IManager;
  41. use \OCP\IURLGenerator;
  42. use \OCP\IRequest;
  43. use \OCP\IL10N;
  44. use \OCP\IConfig;
  45. use OCP\IUser;
  46. use OCP\IUserManager;
  47. use OCP\Mail\IMailer;
  48. use OCP\Security\ICrypto;
  49. use OCP\Security\ISecureRandom;
  50. use function array_filter;
  51. use function count;
  52. use function reset;
  53. /**
  54. * Class LostController
  55. *
  56. * Successfully changing a password will emit the post_passwordReset hook.
  57. *
  58. * @package OC\Core\Controller
  59. */
  60. class LostController extends Controller {
  61. /** @var IURLGenerator */
  62. protected $urlGenerator;
  63. /** @var IUserManager */
  64. protected $userManager;
  65. /** @var Defaults */
  66. protected $defaults;
  67. /** @var IL10N */
  68. protected $l10n;
  69. /** @var string */
  70. protected $from;
  71. /** @var IManager */
  72. protected $encryptionManager;
  73. /** @var IConfig */
  74. protected $config;
  75. /** @var ISecureRandom */
  76. protected $secureRandom;
  77. /** @var IMailer */
  78. protected $mailer;
  79. /** @var ITimeFactory */
  80. protected $timeFactory;
  81. /** @var ICrypto */
  82. protected $crypto;
  83. /** @var Manager */
  84. private $twoFactorManager;
  85. /**
  86. * @param string $appName
  87. * @param IRequest $request
  88. * @param IURLGenerator $urlGenerator
  89. * @param IUserManager $userManager
  90. * @param Defaults $defaults
  91. * @param IL10N $l10n
  92. * @param IConfig $config
  93. * @param ISecureRandom $secureRandom
  94. * @param string $defaultMailAddress
  95. * @param IManager $encryptionManager
  96. * @param IMailer $mailer
  97. * @param ITimeFactory $timeFactory
  98. * @param ICrypto $crypto
  99. */
  100. public function __construct($appName,
  101. IRequest $request,
  102. IURLGenerator $urlGenerator,
  103. IUserManager $userManager,
  104. Defaults $defaults,
  105. IL10N $l10n,
  106. IConfig $config,
  107. ISecureRandom $secureRandom,
  108. $defaultMailAddress,
  109. IManager $encryptionManager,
  110. IMailer $mailer,
  111. ITimeFactory $timeFactory,
  112. ICrypto $crypto,
  113. Manager $twoFactorManager) {
  114. parent::__construct($appName, $request);
  115. $this->urlGenerator = $urlGenerator;
  116. $this->userManager = $userManager;
  117. $this->defaults = $defaults;
  118. $this->l10n = $l10n;
  119. $this->secureRandom = $secureRandom;
  120. $this->from = $defaultMailAddress;
  121. $this->encryptionManager = $encryptionManager;
  122. $this->config = $config;
  123. $this->mailer = $mailer;
  124. $this->timeFactory = $timeFactory;
  125. $this->crypto = $crypto;
  126. $this->twoFactorManager = $twoFactorManager;
  127. }
  128. /**
  129. * Someone wants to reset their password:
  130. *
  131. * @PublicPage
  132. * @NoCSRFRequired
  133. *
  134. * @param string $token
  135. * @param string $userId
  136. * @return TemplateResponse
  137. */
  138. public function resetform($token, $userId) {
  139. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  140. return new TemplateResponse('core', 'error', [
  141. 'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
  142. ],
  143. 'guest'
  144. );
  145. }
  146. try {
  147. $this->checkPasswordResetToken($token, $userId);
  148. } catch (\Exception $e) {
  149. return new TemplateResponse(
  150. 'core', 'error', [
  151. "errors" => array(array("error" => $e->getMessage()))
  152. ],
  153. 'guest'
  154. );
  155. }
  156. return new TemplateResponse(
  157. 'core',
  158. 'lostpassword/resetpassword',
  159. array(
  160. 'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
  161. ),
  162. 'guest'
  163. );
  164. }
  165. /**
  166. * @param string $token
  167. * @param string $userId
  168. * @throws \Exception
  169. */
  170. protected function checkPasswordResetToken($token, $userId) {
  171. $user = $this->userManager->get($userId);
  172. if($user === null || !$user->isEnabled()) {
  173. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  174. }
  175. try {
  176. $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
  177. $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
  178. $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
  179. } catch (\Exception $e) {
  180. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  181. }
  182. $splittedToken = explode(':', $decryptedToken);
  183. if(count($splittedToken) !== 2) {
  184. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  185. }
  186. if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
  187. $user->getLastLogin() > $splittedToken[0]) {
  188. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
  189. }
  190. if (!hash_equals($splittedToken[1], $token)) {
  191. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  192. }
  193. }
  194. /**
  195. * @param $message
  196. * @param array $additional
  197. * @return array
  198. */
  199. private function error($message, array $additional=array()) {
  200. return array_merge(array('status' => 'error', 'msg' => $message), $additional);
  201. }
  202. /**
  203. * @param array $data
  204. * @return array
  205. */
  206. private function success($data = []) {
  207. return array_merge($data, ['status'=>'success']);
  208. }
  209. /**
  210. * @PublicPage
  211. * @BruteForceProtection(action=passwordResetEmail)
  212. * @AnonRateThrottle(limit=10, period=300)
  213. *
  214. * @param string $user
  215. * @return JSONResponse
  216. */
  217. public function email($user){
  218. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  219. return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
  220. }
  221. \OCP\Util::emitHook(
  222. '\OCA\Files_Sharing\API\Server2Server',
  223. 'preLoginNameUsedAsUserName',
  224. ['uid' => &$user]
  225. );
  226. // FIXME: use HTTP error codes
  227. try {
  228. $this->sendEmail($user);
  229. } catch (\Exception $e){
  230. $response = new JSONResponse($this->error($e->getMessage()));
  231. $response->throttle();
  232. return $response;
  233. }
  234. $response = new JSONResponse($this->success());
  235. $response->throttle();
  236. return $response;
  237. }
  238. /**
  239. * @PublicPage
  240. * @param string $token
  241. * @param string $userId
  242. * @param string $password
  243. * @param boolean $proceed
  244. * @return array
  245. */
  246. public function setPassword($token, $userId, $password, $proceed) {
  247. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  248. return $this->error($this->l10n->t('Password reset is disabled'));
  249. }
  250. if ($this->encryptionManager->isEnabled() && !$proceed) {
  251. $encryptionModules = $this->encryptionManager->getEncryptionModules();
  252. foreach ($encryptionModules as $module) {
  253. /** @var IEncryptionModule $instance */
  254. $instance = call_user_func($module['callback']);
  255. // this way we can find out whether per-user keys are used or a system wide encryption key
  256. if ($instance->needDetailedAccessList()) {
  257. return $this->error('', array('encryption' => true));
  258. }
  259. }
  260. }
  261. try {
  262. $this->checkPasswordResetToken($token, $userId);
  263. $user = $this->userManager->get($userId);
  264. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
  265. if (!$user->setPassword($password)) {
  266. throw new \Exception();
  267. }
  268. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
  269. $this->twoFactorManager->clearTwoFactorPending($userId);
  270. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  271. @\OC::$server->getUserSession()->unsetMagicInCookie();
  272. } catch (HintException $e){
  273. return $this->error($e->getHint());
  274. } catch (\Exception $e){
  275. return $this->error($e->getMessage());
  276. }
  277. return $this->success(['user' => $userId]);
  278. }
  279. /**
  280. * @param string $input
  281. * @throws \Exception
  282. */
  283. protected function sendEmail($input) {
  284. $user = $this->findUserByIdOrMail($input);
  285. $email = $user->getEMailAddress();
  286. if (empty($email)) {
  287. throw new \Exception(
  288. $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
  289. );
  290. }
  291. // Generate the token. It is stored encrypted in the database with the
  292. // secret being the users' email address appended with the system secret.
  293. // This makes the token automatically invalidate once the user changes
  294. // their email address.
  295. $token = $this->secureRandom->generate(
  296. 21,
  297. ISecureRandom::CHAR_DIGITS.
  298. ISecureRandom::CHAR_LOWER.
  299. ISecureRandom::CHAR_UPPER
  300. );
  301. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  302. $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
  303. $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
  304. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
  305. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  306. 'link' => $link,
  307. ]);
  308. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  309. $emailTemplate->addHeader();
  310. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  311. $emailTemplate->addBodyText(
  312. htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
  313. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  314. );
  315. $emailTemplate->addBodyButton(
  316. htmlspecialchars($this->l10n->t('Reset your password')),
  317. $link,
  318. false
  319. );
  320. $emailTemplate->addFooter();
  321. try {
  322. $message = $this->mailer->createMessage();
  323. $message->setTo([$email => $user->getUID()]);
  324. $message->setFrom([$this->from => $this->defaults->getName()]);
  325. $message->useTemplate($emailTemplate);
  326. $this->mailer->send($message);
  327. } catch (\Exception $e) {
  328. throw new \Exception($this->l10n->t(
  329. 'Couldn\'t send reset email. Please contact your administrator.'
  330. ));
  331. }
  332. }
  333. /**
  334. * @param string $input
  335. * @return IUser
  336. * @throws \InvalidArgumentException
  337. */
  338. protected function findUserByIdOrMail($input) {
  339. $userNotFound = new \InvalidArgumentException(
  340. $this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.')
  341. );
  342. $user = $this->userManager->get($input);
  343. if ($user instanceof IUser) {
  344. if (!$user->isEnabled()) {
  345. throw $userNotFound;
  346. }
  347. return $user;
  348. }
  349. $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
  350. return $user->isEnabled();
  351. });
  352. if (count($users) === 1) {
  353. return reset($users);
  354. }
  355. throw $userNotFound;
  356. }
  357. }