Controller.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. /**
  3. * @package Grav\Plugin\Login
  4. *
  5. * @copyright Copyright (C) 2014 - 2017 RocketTheme, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Plugin\Login;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Language\Language;
  11. use Grav\Common\Uri;
  12. use Grav\Common\User\User;
  13. use Grav\Common\Utils;
  14. use Grav\Plugin\Email\Utils as EmailUtils;
  15. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  16. use Grav\Plugin\LoginPlugin;
  17. use RocketTheme\Toolbox\Session\Message;
  18. /**
  19. * Class Controller
  20. * @package Grav\Plugin\Login
  21. */
  22. class Controller
  23. {
  24. /**
  25. * @var Grav
  26. */
  27. public $grav;
  28. /**
  29. * @var string
  30. */
  31. public $action;
  32. /**
  33. * @var array
  34. */
  35. public $post;
  36. /**
  37. * @var string
  38. */
  39. protected $redirect;
  40. /**
  41. * @var int
  42. */
  43. protected $redirectCode;
  44. /**
  45. * @var string
  46. */
  47. protected $prefix = 'task';
  48. /**
  49. * @var RememberMe\RememberMe
  50. * @deprecated 2.0 Use $grav['login']->rememberMe() instead
  51. */
  52. protected $rememberMe;
  53. /**
  54. * @var Login
  55. */
  56. protected $login;
  57. /**
  58. * @param Grav $grav
  59. * @param string $action
  60. * @param array $post
  61. */
  62. public function __construct(Grav $grav, $action, $post = null)
  63. {
  64. $this->grav = $grav;
  65. $this->action = $action;
  66. $this->login = $this->grav['login'];
  67. $this->post = $post ? $this->getPost($post) : [];
  68. $this->rememberMe();
  69. }
  70. /**
  71. * Performs an action.
  72. * @throws \RuntimeException
  73. */
  74. public function execute()
  75. {
  76. $messages = $this->grav['messages'];
  77. // Set redirect if available.
  78. if (isset($this->post['_redirect'])) {
  79. $redirect = $this->post['_redirect'];
  80. unset($this->post['_redirect']);
  81. }
  82. $success = false;
  83. $method = $this->prefix . ucfirst($this->action);
  84. if (!method_exists($this, $method)) {
  85. throw new \RuntimeException('Page Not Found', 404);
  86. }
  87. try {
  88. $success = call_user_func([$this, $method]);
  89. } catch (\RuntimeException $e) {
  90. $messages->add($e->getMessage(), 'error');
  91. $this->grav['log']->error('plugin.login: '. $e->getMessage());
  92. }
  93. if (!$this->redirect && isset($redirect)) {
  94. $this->setRedirect($redirect, 303);
  95. }
  96. return $success;
  97. }
  98. /**
  99. * Handle login.
  100. *
  101. * @return bool True if the action was performed.
  102. */
  103. public function taskLogin()
  104. {
  105. /** @var Language $t */
  106. $t = $this->grav['language'];
  107. /** @var Message $messages */
  108. $messages = $this->grav['messages'];
  109. $userKey = isset($this->post['username']) ? (string)$this->post['username'] : '';
  110. $ipKey = Uri::ip();
  111. $rateLimiter = $this->login->getRateLimiter('login_attempts');
  112. // Check if the current IP has been used in failed login attempts.
  113. $attempts = count($rateLimiter->getAttempts($ipKey, 'ip'));
  114. $rateLimiter->registerRateLimitedAction($ipKey, 'ip')->registerRateLimitedAction($userKey);
  115. // Check rate limit for both IP and user, but allow each IP a single try even if user is already rate limited.
  116. if ($rateLimiter->isRateLimited($ipKey, 'ip') || ($attempts && $rateLimiter->isRateLimited($userKey))) {
  117. $messages->add($t->translate(['PLUGIN_LOGIN.TOO_MANY_LOGIN_ATTEMPTS', $rateLimiter->getInterval()]), 'error');
  118. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  119. return true;
  120. }
  121. // Remove login nonce from the form.
  122. $form = array_diff_key($this->post, ['login-form-nonce' => true]);
  123. // Fire Login process.
  124. $event = $this->login->login($form, ['remember_me' => true], ['return_event' => true]);
  125. $user = $event->getUser();
  126. if ($user->authenticated) {
  127. $rateLimiter->resetRateLimit($ipKey, 'ip')->resetRateLimit($userKey);
  128. if ($user->authorized) {
  129. $event->defMessage('PLUGIN_LOGIN.LOGIN_SUCCESSFUL', 'info');
  130. $event->defRedirect(
  131. $this->grav['session']->redirect_after_login ?: $this->grav['uri']->referrer('/')
  132. );
  133. } else {
  134. $login_route = $this->grav['config']->get('plugins.login.route');
  135. if ($login_route) {
  136. $event->defRedirect($login_route);
  137. }
  138. }
  139. } else {
  140. if ($user->authorized) {
  141. $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error');
  142. $event->defRedirect($this->grav['config']->get('plugins.login.route_unauthorized', '/'));
  143. } else {
  144. $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error');
  145. }
  146. }
  147. $message = $event->getMessage();
  148. if ($message) {
  149. $messages->add($t->translate($message), $event->getMessageType());
  150. }
  151. $redirect = $event->getRedirect();
  152. if ($redirect) {
  153. $this->setRedirect($redirect, $event->getRedirectCode());
  154. }
  155. return true;
  156. }
  157. public function taskTwoFa()
  158. {
  159. /** @var Language $t */
  160. $t = $this->grav['language'];
  161. /** @var Message $messages */
  162. $messages = $this->grav['messages'];
  163. /** @var TwoFactorAuth $twoFa */
  164. $twoFa = $this->grav['login']->twoFactorAuth();
  165. $user = $this->grav['user'];
  166. $code = isset($this->post['2fa_code']) ? $this->post['2fa_code'] : null;
  167. $secret = isset($user->twofa_secret) ? $user->twofa_secret : null;
  168. if (!$code || !$secret || !$twoFa->verifyCode($secret, $code)) {
  169. $messages->add($t->translate('PLUGIN_LOGIN.2FA_FAILED'), 'error');
  170. $user->authenticated = false;
  171. $login_route = $this->grav['config']->get('plugins.login.route');
  172. if ($login_route) {
  173. $this->setRedirect($login_route, 303);
  174. }
  175. return true;
  176. }
  177. $messages->add($t->translate('PLUGIN_LOGIN.LOGIN_SUCCESSFUL'), 'info');
  178. $user->authorized = true;
  179. $this->setRedirect(
  180. $this->grav['session']->redirect_after_login
  181. ?: $this->grav['config']->get('plugins.login.redirect_after_login')
  182. ?: $this->grav['uri']->referrer('/')
  183. );
  184. return true;
  185. }
  186. /**
  187. * Handle logout.
  188. *
  189. * @return bool True if the action was performed.
  190. */
  191. public function taskLogout()
  192. {
  193. $event = $this->login->logout(['remember_me' => true], ['return_event' => true]);
  194. $message = $event->getMessage();
  195. if ($message) {
  196. /** @var Language $t */
  197. $t = $this->grav['language'];
  198. $messages = $this->grav['messages'];
  199. $messages->add($t->translate($message), $event->getMessageType());
  200. }
  201. $redirect = $event->getRedirect() ?: $this->grav['config']->get('plugins.login.redirect_after_logout');
  202. if ($redirect) {
  203. $this->setRedirect($redirect, $event->getRedirectCode());
  204. }
  205. $this->grav['session']->setFlashCookieObject(LoginPlugin::TMP_COOKIE_NAME, ['message' => $this->grav['language']->translate('PLUGIN_LOGIN.LOGGED_OUT'),
  206. 'status' => 'info']);
  207. return true;
  208. }
  209. /**
  210. * Handle the email password recovery procedure.
  211. *
  212. * @return bool True if the action was performed.
  213. */
  214. protected function taskForgot()
  215. {
  216. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  217. $data = $this->post;
  218. $email = isset($data['email']) ? $data['email'] : '';
  219. $user = !empty($email) ? User::find($email, ['email']) : null;
  220. /** @var Language $language */
  221. $language = $this->grav['language'];
  222. $messages = $this->grav['messages'];
  223. if (!isset($this->grav['Email'])) {
  224. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  225. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  226. return true;
  227. }
  228. if (!$user || !$user->exists()) {
  229. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), 'info');
  230. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  231. return true;
  232. }
  233. if (empty($user->email)) {
  234. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL', $email]),
  235. 'error');
  236. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  237. return true;
  238. }
  239. if (empty($user->password) && empty($user->hashed_password)) {
  240. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_EMAIL_NO_PASSWORD', $email]),
  241. 'error');
  242. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  243. return true;
  244. }
  245. $from = $this->grav['config']->get('plugins.email.from');
  246. if (empty($from)) {
  247. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  248. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  249. return true;
  250. }
  251. $userKey = $user->username;
  252. $rateLimiter = $this->login->getRateLimiter('pw_resets');
  253. $rateLimiter->registerRateLimitedAction($userKey);
  254. if ($rateLimiter->isRateLimited($userKey)) {
  255. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_IT_IS_BLOCKED', $email, $rateLimiter->getInterval()]), 'error');
  256. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  257. return true;
  258. }
  259. $token = md5(uniqid(mt_rand(), true));
  260. $expire = time() + 604800; // next week
  261. $user->reset = $token . '::' . $expire;
  262. $user->save();
  263. $author = $this->grav['config']->get('site.author.name', '');
  264. $fullname = $user->fullname ?: $user->username;
  265. $reset_link = $this->grav['base_url_absolute'] . $this->grav['config']->get('plugins.login.route_reset') . '/task:login.reset/token' . $param_sep . $token . '/user' . $param_sep . $user->username . '/nonce' . $param_sep . Utils::getNonce('reset-form');
  266. $sitename = $this->grav['config']->get('site.title', 'Website');
  267. $to = $user->email;
  268. $subject = $language->translate(['PLUGIN_LOGIN.FORGOT_EMAIL_SUBJECT', $sitename]);
  269. $content = $language->translate(['PLUGIN_LOGIN.FORGOT_EMAIL_BODY', $fullname, $reset_link, $author, $sitename]);
  270. $sent = EmailUtils::sendEmail($subject, $content, $to);
  271. if ($sent < 1) {
  272. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_FAILED_TO_EMAIL'), 'error');
  273. } else {
  274. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), 'info');
  275. }
  276. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  277. return true;
  278. }
  279. /**
  280. * Handle the reset password action.
  281. *
  282. * @return bool True if the action was performed.
  283. * @throws \Exception
  284. */
  285. public function taskReset()
  286. {
  287. $data = $this->post;
  288. $language = $this->grav['language'];
  289. $messages = $this->grav['messages'];
  290. if (isset($data['password'])) {
  291. $username = isset($data['username']) ? $data['username'] : null;
  292. $user = !empty($username) ? User::find($username) : null;
  293. $password = isset($data['password']) ? $data['password'] : null;
  294. $token = isset($data['token']) ? $data['token'] : null;
  295. if ($user && !empty($user->reset) && $user->exists()) {
  296. list($good_token, $expire) = explode('::', $user->reset);
  297. if ($good_token === $token) {
  298. if (time() > $expire) {
  299. $messages->add($language->translate('PLUGIN_LOGIN.RESET_LINK_EXPIRED'), 'error');
  300. $this->grav->redirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  301. return true;
  302. }
  303. unset($user->hashed_password, $user->reset);
  304. $user->password = $password;
  305. $user->validate();
  306. $user->filter();
  307. $user->save();
  308. $messages->add($language->translate('PLUGIN_LOGIN.RESET_PASSWORD_RESET'), 'info');
  309. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  310. return true;
  311. }
  312. }
  313. $messages->add($language->translate('PLUGIN_LOGIN.RESET_INVALID_LINK'), 'error');
  314. $this->grav->redirect($this->grav['config']->get('plugins.login.route_forgot'));
  315. return true;
  316. }
  317. $user = $this->grav['uri']->param('user');
  318. $token = $this->grav['uri']->param('token');
  319. if (!$user || !$token) {
  320. $messages->add($language->translate('PLUGIN_LOGIN.RESET_INVALID_LINK'), 'error');
  321. $this->grav->redirect($this->grav['config']->get('plugins.login.route_forgot'));
  322. return true;
  323. }
  324. return true;
  325. }
  326. /**
  327. * Redirects an action
  328. */
  329. public function redirect()
  330. {
  331. if ($this->redirect) {
  332. $this->grav->redirect($this->redirect, $this->redirectCode);
  333. }
  334. }
  335. /**
  336. * Set redirect.
  337. *
  338. * @param $path
  339. * @param int $code
  340. */
  341. public function setRedirect($path, $code = 303)
  342. {
  343. $this->redirect = $path;
  344. $this->redirectCode = $code;
  345. }
  346. /**
  347. * @return array Array containing [redirect, code].
  348. */
  349. public function getRedirect()
  350. {
  351. return [$this->redirect, $this->redirectCode];
  352. }
  353. /**
  354. * Prepare and return POST data.
  355. *
  356. * @param array $post
  357. *
  358. * @return array
  359. */
  360. protected function &getPost(array $post)
  361. {
  362. unset($post[$this->prefix]);
  363. // Decode JSON encoded fields and merge them to data.
  364. if (isset($post['_json'])) {
  365. $post = array_merge_recursive($post, $this->jsonDecode($post['_json']));
  366. unset($post['_json']);
  367. }
  368. return $post;
  369. }
  370. /**
  371. * Recursively JSON decode data.
  372. *
  373. * @param array $data
  374. *
  375. * @return array
  376. */
  377. protected function jsonDecode(array $data)
  378. {
  379. foreach ($data as &$value) {
  380. if (is_array($value)) {
  381. $value = $this->jsonDecode($value);
  382. } else {
  383. $value = json_decode($value, true);
  384. }
  385. }
  386. return $data;
  387. }
  388. /**
  389. * Gets and sets the RememberMe class
  390. *
  391. * @param mixed $var A rememberMe instance to set
  392. *
  393. * @return RememberMe\RememberMe Returns the current rememberMe instance
  394. * @deprecated 2.5.0 Use $grav['login']->rememberMe() instead
  395. */
  396. public function rememberMe($var = null)
  397. {
  398. $this->rememberMe = $this->login->rememberMe($var);
  399. return $this->rememberMe;
  400. }
  401. /**
  402. * Check if user may use password reset functionality.
  403. *
  404. * @param User $user
  405. * @param $field
  406. * @param $count
  407. * @param $interval
  408. * @return bool
  409. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  410. */
  411. protected function isUserRateLimited(User $user, $field, $count, $interval)
  412. {
  413. return $this->login->isUserRateLimited($user, $field, $count, $interval);
  414. }
  415. /**
  416. * Reset the rate limit counter
  417. *
  418. * @param User $user
  419. * @param $field
  420. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  421. */
  422. protected function resetRateLimit(User $user, $field)
  423. {
  424. $this->login->resetRateLimit($user, $field);
  425. }
  426. /**
  427. * Authenticate user.
  428. *
  429. * @param array $form Form fields.
  430. *
  431. * @return bool
  432. * @deprecated 2.6.2 Will be removed without replacement.
  433. */
  434. protected function authenticate($form)
  435. {
  436. // Remove login nonce.
  437. $form = array_diff_key($form, ['login-form-nonce' => true]);
  438. return $this->login->login($form, ['remember_me' => true])->authenticated;
  439. }
  440. }