Login.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: giancarlo
  5. * Date: 28/06/2018
  6. * Time: 16:52
  7. */
  8. namespace OpenMind\Web;
  9. use OpenMind\System\User;
  10. class Login extends Controller
  11. {
  12. public function Login($f3)
  13. {
  14. if ($f3->exists('SESSION.user_id')) {
  15. $f3->reroute('/homemenu');
  16. return;
  17. }
  18. $f3->clear('SESSION');
  19. $f3->clear('COOKIE.username');
  20. $f3->set('CONTENT', 'login.tpl');
  21. echo \Template::instance()->render('masterpage.tpl');
  22. }
  23. /**
  24. * Check if login is valid
  25. *
  26. * @param string $username
  27. * @param string $password
  28. * @return int|null
  29. */
  30. private function checkLogin(string $username, string $password): ?int
  31. {
  32. $accounts = \F3::get('users.PASSWORD');
  33. foreach ($accounts as $index => $account) {
  34. $exist = password_verify("{$username}|{$password}", $account);
  35. if ($exist)
  36. return $index;
  37. }
  38. return null;
  39. }
  40. /**
  41. * Check if username and password are correct
  42. *
  43. * @param $f3
  44. */
  45. public function LoginForm($f3)
  46. {
  47. $accountData = $this->getSanitizedPostRequest();
  48. $userId = $this->checkLogin($accountData['username'], $accountData['password']);
  49. if (is_null($userId)) {
  50. http_response_code(500);
  51. echo "Dati di accesso non corretti";
  52. return;
  53. }
  54. $f3->set('SESSION.user_id', $userId);
  55. $user = new User($userId, $accountData['username']);
  56. $user->Save();
  57. $f3->set('USERID', $userId);
  58. $f3->set('COOKIE.username', $accountData['username']);
  59. $f3->reroute('/homemenu');
  60. }
  61. public function Logout($f3)
  62. {
  63. $f3->clear('SESSION');
  64. $f3->clear('COOKIE.username');
  65. $f3->reroute('/');
  66. }
  67. }