LostController.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 OCA\Encryption\Exceptions\PrivateKeyMissingException;
  32. use \OCP\AppFramework\Controller;
  33. use \OCP\AppFramework\Http\TemplateResponse;
  34. use OCP\AppFramework\Utility\ITimeFactory;
  35. use OCP\Encryption\IManager;
  36. use \OCP\IURLGenerator;
  37. use \OCP\IRequest;
  38. use \OCP\IL10N;
  39. use \OCP\IConfig;
  40. use OCP\IUserManager;
  41. use OCP\Mail\IMailer;
  42. use OCP\Security\ICrypto;
  43. use OCP\Security\ISecureRandom;
  44. /**
  45. * Class LostController
  46. *
  47. * Successfully changing a password will emit the post_passwordReset hook.
  48. *
  49. * @package OC\Core\Controller
  50. */
  51. class LostController extends Controller {
  52. /** @var IURLGenerator */
  53. protected $urlGenerator;
  54. /** @var IUserManager */
  55. protected $userManager;
  56. /** @var \OC_Defaults */
  57. protected $defaults;
  58. /** @var IL10N */
  59. protected $l10n;
  60. /** @var string */
  61. protected $from;
  62. /** @var IManager */
  63. protected $encryptionManager;
  64. /** @var IConfig */
  65. protected $config;
  66. /** @var ISecureRandom */
  67. protected $secureRandom;
  68. /** @var IMailer */
  69. protected $mailer;
  70. /** @var ITimeFactory */
  71. protected $timeFactory;
  72. /** @var ICrypto */
  73. protected $crypto;
  74. /**
  75. * @param string $appName
  76. * @param IRequest $request
  77. * @param IURLGenerator $urlGenerator
  78. * @param IUserManager $userManager
  79. * @param \OC_Defaults $defaults
  80. * @param IL10N $l10n
  81. * @param IConfig $config
  82. * @param ISecureRandom $secureRandom
  83. * @param string $defaultMailAddress
  84. * @param IManager $encryptionManager
  85. * @param IMailer $mailer
  86. * @param ITimeFactory $timeFactory
  87. * @param ICrypto $crypto
  88. */
  89. public function __construct($appName,
  90. IRequest $request,
  91. IURLGenerator $urlGenerator,
  92. IUserManager $userManager,
  93. \OC_Defaults $defaults,
  94. IL10N $l10n,
  95. IConfig $config,
  96. ISecureRandom $secureRandom,
  97. $defaultMailAddress,
  98. IManager $encryptionManager,
  99. IMailer $mailer,
  100. ITimeFactory $timeFactory,
  101. ICrypto $crypto) {
  102. parent::__construct($appName, $request);
  103. $this->urlGenerator = $urlGenerator;
  104. $this->userManager = $userManager;
  105. $this->defaults = $defaults;
  106. $this->l10n = $l10n;
  107. $this->secureRandom = $secureRandom;
  108. $this->from = $defaultMailAddress;
  109. $this->encryptionManager = $encryptionManager;
  110. $this->config = $config;
  111. $this->mailer = $mailer;
  112. $this->timeFactory = $timeFactory;
  113. $this->crypto = $crypto;
  114. }
  115. /**
  116. * Someone wants to reset their password:
  117. *
  118. * @PublicPage
  119. * @NoCSRFRequired
  120. *
  121. * @param string $token
  122. * @param string $userId
  123. * @return TemplateResponse
  124. */
  125. public function resetform($token, $userId) {
  126. try {
  127. $this->checkPasswordResetToken($token, $userId);
  128. } catch (\Exception $e) {
  129. return new TemplateResponse(
  130. 'core', 'error', [
  131. "errors" => array(array("error" => $e->getMessage()))
  132. ],
  133. 'guest'
  134. );
  135. }
  136. return new TemplateResponse(
  137. 'core',
  138. 'lostpassword/resetpassword',
  139. array(
  140. 'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
  141. ),
  142. 'guest'
  143. );
  144. }
  145. /**
  146. * @param string $token
  147. * @param string $userId
  148. * @throws \Exception
  149. */
  150. protected function checkPasswordResetToken($token, $userId) {
  151. $user = $this->userManager->get($userId);
  152. if($user === null) {
  153. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  154. }
  155. try {
  156. $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
  157. $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
  158. $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
  159. } catch (\Exception $e) {
  160. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  161. }
  162. $splittedToken = explode(':', $decryptedToken);
  163. if(count($splittedToken) !== 2) {
  164. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  165. }
  166. if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
  167. $user->getLastLogin() > $splittedToken[0]) {
  168. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
  169. }
  170. if (!hash_equals($splittedToken[1], $token)) {
  171. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  172. }
  173. }
  174. /**
  175. * @param $message
  176. * @param array $additional
  177. * @return array
  178. */
  179. private function error($message, array $additional=array()) {
  180. return array_merge(array('status' => 'error', 'msg' => $message), $additional);
  181. }
  182. /**
  183. * @return array
  184. */
  185. private function success() {
  186. return array('status'=>'success');
  187. }
  188. /**
  189. * @PublicPage
  190. * @BruteForceProtection passwordResetEmail
  191. *
  192. * @param string $user
  193. * @return array
  194. */
  195. public function email($user){
  196. // FIXME: use HTTP error codes
  197. try {
  198. $this->sendEmail($user);
  199. } catch (\Exception $e){
  200. return $this->error($e->getMessage());
  201. }
  202. return $this->success();
  203. }
  204. /**
  205. * @PublicPage
  206. * @param string $token
  207. * @param string $userId
  208. * @param string $password
  209. * @param boolean $proceed
  210. * @return array
  211. */
  212. public function setPassword($token, $userId, $password, $proceed) {
  213. if ($this->encryptionManager->isEnabled() && !$proceed) {
  214. return $this->error('', array('encryption' => true));
  215. }
  216. try {
  217. $this->checkPasswordResetToken($token, $userId);
  218. $user = $this->userManager->get($userId);
  219. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
  220. if (!$user->setPassword($password)) {
  221. throw new \Exception();
  222. }
  223. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
  224. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  225. @\OC_User::unsetMagicInCookie();
  226. } catch (\Exception $e){
  227. return $this->error($e->getMessage());
  228. }
  229. return $this->success();
  230. }
  231. /**
  232. * @param string $user
  233. * @throws \Exception
  234. */
  235. protected function sendEmail($user) {
  236. if (!$this->userManager->userExists($user)) {
  237. throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
  238. }
  239. $userObject = $this->userManager->get($user);
  240. $email = $userObject->getEMailAddress();
  241. if (empty($email)) {
  242. throw new \Exception(
  243. $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
  244. );
  245. }
  246. // Generate the token. It is stored encrypted in the database with the
  247. // secret being the users' email address appended with the system secret.
  248. // This makes the token automatically invalidate once the user changes
  249. // their email address.
  250. $token = $this->secureRandom->generate(
  251. 21,
  252. ISecureRandom::CHAR_DIGITS.
  253. ISecureRandom::CHAR_LOWER.
  254. ISecureRandom::CHAR_UPPER
  255. );
  256. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  257. $mailAddress = !is_null($userObject->getEMailAddress()) ? $userObject->getEMailAddress() : '';
  258. $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
  259. $this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
  260. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
  261. $tmpl = new \OC_Template('core', 'lostpassword/email');
  262. $tmpl->assign('link', $link);
  263. $msg = $tmpl->fetchPage();
  264. try {
  265. $message = $this->mailer->createMessage();
  266. $message->setTo([$email => $user]);
  267. $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  268. $message->setPlainBody($msg);
  269. $message->setFrom([$this->from => $this->defaults->getName()]);
  270. $this->mailer->send($message);
  271. } catch (\Exception $e) {
  272. throw new \Exception($this->l10n->t(
  273. 'Couldn\'t send reset email. Please contact your administrator.'
  274. ));
  275. }
  276. }
  277. }