LostController.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. *
  191. * @param string $user
  192. * @return array
  193. */
  194. public function email($user){
  195. // FIXME: use HTTP error codes
  196. try {
  197. $this->sendEmail($user);
  198. } catch (\Exception $e){
  199. return $this->error($e->getMessage());
  200. }
  201. return $this->success();
  202. }
  203. /**
  204. * @PublicPage
  205. * @param string $token
  206. * @param string $userId
  207. * @param string $password
  208. * @param boolean $proceed
  209. * @return array
  210. */
  211. public function setPassword($token, $userId, $password, $proceed) {
  212. if ($this->encryptionManager->isEnabled() && !$proceed) {
  213. return $this->error('', array('encryption' => true));
  214. }
  215. try {
  216. $this->checkPasswordResetToken($token, $userId);
  217. $user = $this->userManager->get($userId);
  218. if (!$user->setPassword($password)) {
  219. throw new \Exception();
  220. }
  221. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
  222. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  223. @\OC_User::unsetMagicInCookie();
  224. } catch (PrivateKeyMissingException $e) {
  225. // in this case it is OK if we couldn't reset the users private key
  226. // They chose explicitely to continue at the password reset dialog
  227. // (see $proceed flag)
  228. return $this->success();
  229. } catch (\Exception $e){
  230. return $this->error($e->getMessage());
  231. }
  232. return $this->success();
  233. }
  234. /**
  235. * @param string $user
  236. * @throws \Exception
  237. */
  238. protected function sendEmail($user) {
  239. if (!$this->userManager->userExists($user)) {
  240. throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
  241. }
  242. $userObject = $this->userManager->get($user);
  243. $email = $userObject->getEMailAddress();
  244. if (empty($email)) {
  245. throw new \Exception(
  246. $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
  247. );
  248. }
  249. // Generate the token. It is stored encrypted in the database with the
  250. // secret being the users' email address appended with the system secret.
  251. // This makes the token automatically invalidate once the user changes
  252. // their email address.
  253. $token = $this->secureRandom->generate(
  254. 21,
  255. ISecureRandom::CHAR_DIGITS.
  256. ISecureRandom::CHAR_LOWER.
  257. ISecureRandom::CHAR_UPPER
  258. );
  259. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  260. $mailAddress = !is_null($userObject->getEMailAddress()) ? $userObject->getEMailAddress() : '';
  261. $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
  262. $this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
  263. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
  264. $tmpl = new \OC_Template('core', 'lostpassword/email');
  265. $tmpl->assign('link', $link);
  266. $msg = $tmpl->fetchPage();
  267. try {
  268. $message = $this->mailer->createMessage();
  269. $message->setTo([$email => $user]);
  270. $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  271. $message->setPlainBody($msg);
  272. $message->setFrom([$this->from => $this->defaults->getName()]);
  273. $this->mailer->send($message);
  274. } catch (\Exception $e) {
  275. throw new \Exception($this->l10n->t(
  276. 'Couldn\'t send reset email. Please contact your administrator.'
  277. ));
  278. }
  279. }
  280. }