BaseController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * @author Open Mind
  4. * @date 09/04/2018
  5. * @time 16:15
  6. */
  7. namespace OpenMind\Web;
  8. class BaseController
  9. {
  10. protected $dbHandle;
  11. protected $userId;
  12. private $sanitizedPostRequest;
  13. /**
  14. * @return mixed
  15. */
  16. public function getSanitizedPostRequest()
  17. {
  18. return $this->sanitizedPostRequest;
  19. }
  20. public function __construct($f3)
  21. {
  22. $this->sanitizedPostRequest = $f3->clean($f3->get('POST'));
  23. $this->dbHandle = $f3->get('DB');
  24. $this->userId = $this->checkLogin($f3->get('COOKIE.username'), $f3->get('COOKIE.password'));
  25. $f3->set('USERID', $this->userId);
  26. if (!is_null($this->userId))
  27. return;
  28. $f3->clear('COOKIE.username');
  29. $f3->clear('COOKIE.password');
  30. $f3->clear('COOKIE.id');
  31. if (!in_array($f3->get('PATTERN'), ['/login', '/']))
  32. $f3->reroute('/');
  33. return;
  34. }
  35. /**
  36. * Check if login is valid
  37. * @param $username
  38. * @param $password
  39. * @return int|null
  40. */
  41. private function checkLogin($username, $password): ?int
  42. {
  43. $accounts = \F3::get('users.PASSWORD');
  44. foreach($accounts as $index => $account) {
  45. $exist = password_verify("{$username}|{$password}", $account);
  46. if ($exist)
  47. return $index;
  48. }
  49. return null;
  50. }
  51. public function Login($f3)
  52. {
  53. $accountData = $this->getSanitizedPostRequest();
  54. $userId = $this->checkLogin($accountData['username'], $accountData['password']);
  55. if (is_null($userId)) {
  56. http_response_code(500);
  57. echo "Dati di accesso non corretti";
  58. return;
  59. }
  60. $f3->set('COOKIE.username', $accountData['username']);
  61. $f3->set('COOKIE.password', $accountData['password']);
  62. $f3->set('COOKIE.id', $userId);
  63. //http_response_code(200);
  64. $f3->reroute('/homemenu');
  65. }
  66. public function Logout($f3)
  67. {
  68. $f3->clear('COOKIE.username');
  69. $f3->clear('COOKIE.password');
  70. $f3->clear('COOKIE.id');
  71. $f3->reroute('/');
  72. }
  73. }