LostController.php 12 KB

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