Login.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 Birke\Rememberme\Cookie;
  10. use Grav\Common\Config\Config;
  11. use Grav\Common\Data\Data;
  12. use Grav\Common\Grav;
  13. use Grav\Common\File\CompiledYamlFile;
  14. use Grav\Common\Language\Language;
  15. use Grav\Common\Page\Page;
  16. use Grav\Common\Session;
  17. use Grav\Common\User\User;
  18. use Grav\Common\Uri;
  19. use Grav\Plugin\Email\Utils as EmailUtils;
  20. use Grav\Plugin\Login\Events\UserLoginEvent;
  21. use Grav\Plugin\Login\RememberMe\RememberMe;
  22. use Grav\Plugin\Login\RememberMe\TokenStorage;
  23. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  24. /**
  25. * Class Login
  26. * @package Grav\Plugin
  27. */
  28. class Login
  29. {
  30. /** @var Grav */
  31. protected $grav;
  32. /** @var Config */
  33. protected $config;
  34. /** @var Language $language */
  35. protected $language;
  36. /** @var Session */
  37. protected $session;
  38. /** @var Uri */
  39. protected $uri;
  40. /** @var RememberMe */
  41. protected $rememberMe;
  42. /** @var TwoFactorAuth */
  43. protected $twoFa;
  44. /** @var RateLimiter[] */
  45. protected $rateLimiters = [];
  46. /** @var array */
  47. protected $provider_login_templates = [];
  48. /**
  49. * Login constructor.
  50. *
  51. * @param Grav $grav
  52. */
  53. public function __construct(Grav $grav)
  54. {
  55. $this->grav = $grav;
  56. $this->config = $this->grav['config'];
  57. $this->language = $this->grav['language'];
  58. $this->session = $this->grav['session'];
  59. $this->uri = $this->grav['uri'];
  60. }
  61. /**
  62. * Login user.
  63. *
  64. * @param array $credentials Login credentials, eg: ['username' => '', 'password' => '']
  65. * @param array $options Login options, eg: ['remember_me' => true]
  66. * @param array $extra Example: ['authorize' => 'site.login', 'user' => null], undefined variables get set.
  67. * @return User|UserLoginEvent Returns event if $extra['return_event'] is true.
  68. */
  69. public function login(array $credentials, array $options = [], array $extra = [])
  70. {
  71. $grav = Grav::instance();
  72. $eventOptions = [
  73. 'credentials' => $credentials,
  74. 'options' => $options
  75. ] + $extra;
  76. // Attempt to authenticate the user.
  77. $event = new UserLoginEvent($eventOptions);
  78. $grav->fireEvent('onUserLoginAuthenticate', $event);
  79. if ($event->isSuccess()) {
  80. // Make sure that event didn't mess up with the user authorization.
  81. $user = $event->getUser();
  82. $user->authenticated = true;
  83. $user->authorized = false;
  84. // Allow plugins to prevent login after successful authentication.
  85. $event = new UserLoginEvent($event->toArray());
  86. $grav->fireEvent('onUserLoginAuthorize', $event);
  87. }
  88. if ($event->isSuccess()) {
  89. // User has been logged in, let plugins know.
  90. $event = new UserLoginEvent($event->toArray());
  91. $grav->fireEvent('onUserLogin', $event);
  92. // Make sure that event didn't mess up with the user authorization.
  93. $user = $event->getUser();
  94. $user->authenticated = true;
  95. $user->authorized = !$event->isDelayed();
  96. } else {
  97. // Allow plugins to log errors or do other tasks on failure.
  98. $event = new UserLoginEvent($event->toArray());
  99. $grav->fireEvent('onUserLoginFailure', $event);
  100. // Make sure that event didn't mess up with the user authorization.
  101. $user = $event->getUser();
  102. $user->authenticated = false;
  103. $user->authorized = false;
  104. }
  105. $user = $event->getUser();
  106. $user->def('language', 'en');
  107. return !empty($event['return_event']) ? $event : $user;
  108. }
  109. /**
  110. * Logout user.
  111. *
  112. * @param array $options
  113. * @param array|User $extra Array of: ['user' => $user, ...] or User object (deprecated).
  114. * @return User|UserLoginEvent Returns event if $extra['return_event'] is true.
  115. */
  116. public function logout(array $options = [], $extra = [])
  117. {
  118. $grav = Grav::instance();
  119. if ($extra instanceof User) {
  120. $extra = ['user' => $extra];
  121. } elseif (isset($extra['user'])) {
  122. $extra['user'] = $grav['user'];
  123. }
  124. $eventOptions = [
  125. 'options' => $options
  126. ] + $extra;
  127. $event = new UserLoginEvent($eventOptions);
  128. // Logout the user.
  129. $grav->fireEvent('onUserLogout', $event);
  130. $user = $event->getUser();
  131. $user->authenticated = false;
  132. $user->authorized = false;
  133. return !empty($event['return_event']) ? $event : $user;
  134. }
  135. /**
  136. * Authenticate user.
  137. *
  138. * @param array $credentials Form fields.
  139. * @param array $options
  140. *
  141. * @return bool
  142. */
  143. public function authenticate($credentials, $options = ['remember_me' => true])
  144. {
  145. $event = $this->login($credentials, $options, ['return_event' => true]);
  146. $user = $event['user'];
  147. $redirect = $event->getRedirect();
  148. $message = $event->getMessage();
  149. $messageType = $event->getMessageType();
  150. if ($user->authenticated && $user->authorized) {
  151. if (!$message) {
  152. $message = 'PLUGIN_LOGIN.LOGIN_SUCCESSFUL';
  153. $messageType = 'info';
  154. }
  155. if (!$redirect) {
  156. $redirect = $this->uri->route();
  157. }
  158. }
  159. if ($message) {
  160. $this->grav['messages']->add($this->language->translate($message, [$user->language]), $messageType);
  161. }
  162. if ($redirect) {
  163. $this->grav->redirect($redirect, $event->getRedirectCode());
  164. }
  165. return $user->authenticated && $user->authorized;
  166. }
  167. /**
  168. * Create a new user file
  169. *
  170. * @param array $data
  171. *
  172. * @return User
  173. */
  174. public function register($data)
  175. {
  176. if (!isset($data['groups'])) {
  177. //Add new user ACL settings
  178. $groups = (array) $this->config->get('plugins.login.user_registration.groups', []);
  179. if (count($groups) > 0) {
  180. $data['groups'] = $groups;
  181. }
  182. }
  183. if (!isset($data['access'])) {
  184. $access = (array) $this->config->get('plugins.login.user_registration.access.site', []);
  185. if (count($access) > 0) {
  186. $data['access']['site'] = $access;
  187. }
  188. }
  189. $username = $this->validateField('username', $data['username']);
  190. $file = CompiledYamlFile::instance($this->grav['locator']->findResource('account://' . $username . YAML_EXT,
  191. true, true));
  192. // Create user object and save it
  193. $user = new User($data);
  194. $user->file($file);
  195. $user->save();
  196. return $user;
  197. }
  198. /**
  199. * @param string $type
  200. * @param mixed $value
  201. * @param string $extra
  202. *
  203. * @return string
  204. */
  205. public function validateField($type, $value, $extra = '')
  206. {
  207. switch ($type) {
  208. case 'user':
  209. case 'username':
  210. /** @var Config $config */
  211. $config = Grav::instance()['config'];
  212. $username_regex = '/' . $config->get('system.username_regex') . '/';
  213. if (!is_string($value) || !preg_match($username_regex, $value)) {
  214. throw new \RuntimeException('Username should be between 3 and 16 characters, including lowercase letters, numbers, underscores, and hyphens. Uppercase letters, spaces, and special characters are not allowed');
  215. }
  216. break;
  217. case 'password1':
  218. /** @var Config $config */
  219. $config = Grav::instance()['config'];
  220. $pwd_regex = '/' . $config->get('system.pwd_regex') . '/';
  221. if (!is_string($value) || !preg_match($pwd_regex, $value)) {
  222. throw new \RuntimeException('Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters');
  223. }
  224. break;
  225. case 'password2':
  226. if (!is_string($value) || strcmp($value, $extra)) {
  227. throw new \RuntimeException('Passwords did not match.');
  228. }
  229. break;
  230. case 'email':
  231. if (!is_string($value) || !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  232. throw new \RuntimeException('Not a valid email address');
  233. }
  234. break;
  235. case 'permissions':
  236. if (!is_string($value) || !in_array($value, ['a', 's', 'b'])) {
  237. throw new \RuntimeException('Permissions ' . $value . ' are invalid.');
  238. }
  239. break;
  240. case 'fullname':
  241. if (!is_string($value) || trim($value) === '') {
  242. throw new \RuntimeException('Fullname cannot be empty');
  243. }
  244. break;
  245. case 'state':
  246. if ($value !== 'enabled' && $value !== 'disabled') {
  247. throw new \RuntimeException('State is not valid');
  248. }
  249. break;
  250. }
  251. return $value;
  252. }
  253. /**
  254. * Handle the email to notify the user account creation to the site admin.
  255. *
  256. * @param User $user
  257. *
  258. * @return bool True if the action was performed.
  259. * @throws \RuntimeException
  260. */
  261. public function sendNotificationEmail(User $user)
  262. {
  263. if (empty($user->email)) {
  264. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.USER_NEEDS_EMAIL_FIELD'));
  265. }
  266. $site_name = $this->config->get('site.title', 'Website');
  267. $subject = $this->language->translate(['PLUGIN_LOGIN.NOTIFICATION_EMAIL_SUBJECT', $site_name]);
  268. $content = $this->language->translate([
  269. 'PLUGIN_LOGIN.NOTIFICATION_EMAIL_BODY',
  270. $site_name,
  271. $user->username,
  272. $user->email,
  273. $this->grav['base_url_absolute'],
  274. ]);
  275. $to = $this->config->get('plugins.email.from');
  276. if (empty($to)) {
  277. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.EMAIL_NOT_CONFIGURED'));
  278. }
  279. $sent = EmailUtils::sendEmail($subject, $content, $to);
  280. if ($sent < 1) {
  281. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.EMAIL_SENDING_FAILURE'));
  282. }
  283. return true;
  284. }
  285. /**
  286. * Handle the email to welcome the new user
  287. *
  288. * @param User $user
  289. *
  290. * @return bool True if the action was performed.
  291. * @throws \RuntimeException
  292. */
  293. public function sendWelcomeEmail(User $user)
  294. {
  295. if (empty($user->email)) {
  296. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.USER_NEEDS_EMAIL_FIELD'));
  297. }
  298. $site_name = $this->config->get('site.title', 'Website');
  299. $author = $this->grav['config']->get('site.author.name', '');
  300. $fullname = $user->fullname ?: $user->username;
  301. $subject = $this->language->translate(['PLUGIN_LOGIN.WELCOME_EMAIL_SUBJECT', $site_name]);
  302. $content = $this->language->translate(['PLUGIN_LOGIN.WELCOME_EMAIL_BODY',
  303. $fullname,
  304. $this->grav['base_url_absolute'],
  305. $site_name,
  306. $author
  307. ]);
  308. $to = $user->email;
  309. $sent = EmailUtils::sendEmail($subject, $content, $to);
  310. if ($sent < 1) {
  311. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.EMAIL_SENDING_FAILURE'));
  312. }
  313. return true;
  314. }
  315. /**
  316. * Handle the email to activate the user account.
  317. *
  318. * @param User $user
  319. *
  320. * @return bool True if the action was performed.
  321. * @throws \RuntimeException
  322. */
  323. public function sendActivationEmail(User $user)
  324. {
  325. if (empty($user->email)) {
  326. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.USER_NEEDS_EMAIL_FIELD'));
  327. }
  328. $token = md5(uniqid(mt_rand(), true));
  329. $expire = time() + 604800; // next week
  330. $user->activation_token = $token . '::' . $expire;
  331. $user->save();
  332. $param_sep = $this->config->get('system.param_sep', ':');
  333. $activation_link = $this->grav['base_url_absolute'] . $this->config->get('plugins.login.route_activate') . '/token' . $param_sep . $token . '/username' . $param_sep . $user->username;
  334. $site_name = $this->config->get('site.title', 'Website');
  335. $author = $this->grav['config']->get('site.author.name', '');
  336. $fullname = $user->fullname ?: $user->username;
  337. $subject = $this->language->translate(['PLUGIN_LOGIN.ACTIVATION_EMAIL_SUBJECT', $site_name]);
  338. $content = $this->language->translate(['PLUGIN_LOGIN.ACTIVATION_EMAIL_BODY',
  339. $fullname,
  340. $activation_link,
  341. $site_name,
  342. $author
  343. ]);
  344. $to = $user->email;
  345. $sent = EmailUtils::sendEmail($subject, $content, $to);
  346. if ($sent < 1) {
  347. throw new \RuntimeException($this->language->translate('PLUGIN_LOGIN.EMAIL_SENDING_FAILURE'));
  348. }
  349. return true;
  350. }
  351. /**
  352. * Gets and sets the RememberMe class
  353. *
  354. * @param mixed $var A rememberMe instance to set
  355. *
  356. * @return RememberMe Returns the current rememberMe instance
  357. * @throws \InvalidArgumentException
  358. */
  359. public function rememberMe($var = null)
  360. {
  361. if ($var !== null) {
  362. $this->rememberMe = $var;
  363. }
  364. if (!$this->rememberMe) {
  365. /** @var Config $config */
  366. $config = $this->grav['config'];
  367. // Setup storage for RememberMe cookies
  368. $storage = new TokenStorage;
  369. $this->rememberMe = new RememberMe($storage);
  370. $this->rememberMe->setCookieName($config->get('plugins.login.rememberme.name'));
  371. $this->rememberMe->setExpireTime($config->get('plugins.login.rememberme.timeout'));
  372. // Hardening cookies with user-agent and random salt or
  373. // fallback to use system based cache key
  374. $server_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown';
  375. $data = $server_agent . $config->get('security.salt', $this->grav['cache']->getKey());
  376. $this->rememberMe->setSalt(hash('sha512', $data));
  377. // Set cookie with correct base path of Grav install
  378. $cookie = new Cookie;
  379. $cookie->setPath($this->grav['base_url_relative'] ?: '/');
  380. $this->rememberMe->setCookie($cookie);
  381. }
  382. return $this->rememberMe;
  383. }
  384. /**
  385. * Gets and sets the TwoFactorAuth object
  386. *
  387. * @param TwoFactorAuth $var
  388. * @return TwoFactorAuth
  389. * @throws \RobThree\Auth\TwoFactorAuthException
  390. */
  391. public function twoFactorAuth($var = null)
  392. {
  393. if ($var !== null) {
  394. $this->twoFa = $var;
  395. }
  396. if (!$this->twoFa) {
  397. $this->twoFa = new TwoFactorAuth;
  398. }
  399. return $this->twoFa;
  400. }
  401. /**
  402. * @param string $context
  403. * @param int $maxCount
  404. * @param int $interval
  405. * @return RateLimiter
  406. */
  407. public function getRateLimiter($context, $maxCount = null, $interval = null)
  408. {
  409. if (!isset($this->rateLimiters[$context])) {
  410. switch ($context) {
  411. case 'login_attempts':
  412. $maxCount = $this->grav['config']->get('plugins.login.max_login_count', 5);
  413. $interval = $this->grav['config']->get('plugins.login.max_login_interval', 10);
  414. break;
  415. case 'pw_resets':
  416. $maxCount = $this->grav['config']->get('plugins.login.max_pw_resets_count', 0);
  417. $interval = $this->grav['config']->get('plugins.login.max_pw_resets_interval', 2);
  418. break;
  419. }
  420. $this->rateLimiters[$context] = new RateLimiter($context, $maxCount, $interval);
  421. }
  422. return $this->rateLimiters[$context];
  423. }
  424. /**
  425. * @param User $user
  426. * @param Page $page
  427. * @param Data|null $config
  428. * @return bool
  429. */
  430. public function isUserAuthorizedForPage(User $user, Page $page, $config = null)
  431. {
  432. $header = $page->header();
  433. $rules = isset($header->access) ? (array)$header->access : [];
  434. if ($config !== null && $config->get('parent_acl')) {
  435. // If page has no ACL rules, use its parent's rules
  436. if (!$rules) {
  437. $parent = $page->parent();
  438. while (!$rules and $parent) {
  439. $header = $parent->header();
  440. $rules = isset($header->access) ? (array)$header->access : [];
  441. $parent = $parent->parent();
  442. }
  443. }
  444. }
  445. // Continue to the page if it has no ACL rules.
  446. if (!$rules) {
  447. return true;
  448. }
  449. if (!$user->authorized) {
  450. return false;
  451. }
  452. // Continue to the page if user is authorized to access the page.
  453. foreach ($rules as $rule => $value) {
  454. if (is_array($value)) {
  455. foreach ($value as $nested_rule => $nested_value) {
  456. if ($user->authorize($rule . '.' . $nested_rule) == $nested_value) {
  457. return true;
  458. }
  459. }
  460. } else {
  461. if ($user->authorize($rule) == $value) {
  462. return true;
  463. }
  464. }
  465. }
  466. return false;
  467. }
  468. /**
  469. * Check if user may use password reset functionality.
  470. *
  471. * @param User $user
  472. * @param string $field
  473. * @param int $count
  474. * @param int $interval
  475. * @return bool
  476. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  477. */
  478. public function isUserRateLimited(User $user, $field, $count, $interval)
  479. {
  480. if ($count > 0) {
  481. if (!isset($user->{$field})) {
  482. $user->{$field} = [];
  483. }
  484. //remove older than $interval x minute attempts
  485. $actual_resets = [];
  486. foreach ((array)$user->{$field} as $reset) {
  487. if ($reset > (time() - $interval * 60)) {
  488. $actual_resets[] = $reset;
  489. }
  490. }
  491. if (count($actual_resets) >= $count) {
  492. return true;
  493. }
  494. $actual_resets[] = time(); // current reset
  495. $user->{$field} = $actual_resets;
  496. }
  497. return false;
  498. }
  499. /**
  500. * Reset the rate limit counter.
  501. *
  502. * @param User $user
  503. * @param string $field
  504. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  505. */
  506. public function resetRateLimit(User $user, $field)
  507. {
  508. $user->{$field} = [];
  509. }
  510. /**
  511. * Get Current logged in user
  512. *
  513. * @return User
  514. * @deprecated 2.5.0 Use $grav['user'] instead.
  515. */
  516. public function getUser()
  517. {
  518. /** @var User $user */
  519. return $this->grav['user'];
  520. }
  521. public function addProviderLoginTemplate($template)
  522. {
  523. $this->provider_login_templates[] = $template;
  524. }
  525. public function getProviderLoginTemplates()
  526. {
  527. $templates = $this->provider_login_templates;
  528. return $templates;
  529. }
  530. }