LostController.php 11 KB

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