You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LostController.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 \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 || !$user->isEnabled()) {
  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::$server->getUserSession()->unsetMagicInCookie();
  252. } catch (\Exception $e){
  253. return $this->error($e->getMessage());
  254. }
  255. return $this->success();
  256. }
  257. /**
  258. * @param string $input
  259. * @throws \Exception
  260. */
  261. protected function sendEmail($input) {
  262. $user = $this->findUserByIdOrMail($input);
  263. $email = $user->getEMailAddress();
  264. if (empty($email)) {
  265. throw new \Exception(
  266. $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
  267. );
  268. }
  269. // Generate the token. It is stored encrypted in the database with the
  270. // secret being the users' email address appended with the system secret.
  271. // This makes the token automatically invalidate once the user changes
  272. // their email address.
  273. $token = $this->secureRandom->generate(
  274. 21,
  275. ISecureRandom::CHAR_DIGITS.
  276. ISecureRandom::CHAR_LOWER.
  277. ISecureRandom::CHAR_UPPER
  278. );
  279. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  280. $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
  281. $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
  282. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
  283. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  284. 'link' => $link,
  285. ]);
  286. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  287. $emailTemplate->addHeader();
  288. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  289. $emailTemplate->addBodyText(
  290. $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
  291. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  292. );
  293. $emailTemplate->addBodyButton(
  294. $this->l10n->t('Reset your password'),
  295. $link,
  296. false
  297. );
  298. $emailTemplate->addFooter();
  299. try {
  300. $message = $this->mailer->createMessage();
  301. $message->setTo([$email => $user->getUID()]);
  302. $message->setFrom([$this->from => $this->defaults->getName()]);
  303. $message->useTemplate($emailTemplate);
  304. $this->mailer->send($message);
  305. } catch (\Exception $e) {
  306. throw new \Exception($this->l10n->t(
  307. 'Couldn\'t send reset email. Please contact your administrator.'
  308. ));
  309. }
  310. }
  311. /**
  312. * @param string $input
  313. * @return IUser
  314. * @throws \InvalidArgumentException
  315. */
  316. protected function findUserByIdOrMail($input) {
  317. $user = $this->userManager->get($input);
  318. if ($user instanceof IUser) {
  319. if (!$user->isEnabled()) {
  320. throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
  321. }
  322. return $user;
  323. }
  324. $users = $this->userManager->getByEmail($input);
  325. if (count($users) === 1) {
  326. $user = $users[0];
  327. if (!$user->isEnabled()) {
  328. throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
  329. }
  330. return $user;
  331. }
  332. throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
  333. }
  334. }