User.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: giancarlo
  5. * Date: 28/06/2018
  6. * Time: 20:01
  7. */
  8. namespace OpenMind\System;
  9. use DB\SQL\Mapper;
  10. /**
  11. * Class User
  12. *
  13. * @property int $id
  14. * @property string $username
  15. * @property string $saltedpassword
  16. * @property string $roles
  17. * @package OpenMind\System
  18. */
  19. class User extends Mapper
  20. {
  21. private $userRoles;
  22. /**
  23. * User constructor.
  24. * @param string/array $where
  25. */
  26. public function __construct($where)
  27. {
  28. global $f3;
  29. $this->onload(function ($obj) {
  30. $obj->userRoles = unserialize($obj->roles);
  31. });
  32. parent::__construct($f3->get('DB'), 'users', NULL, 3600);
  33. if ($where !== NULL) {
  34. $this->load($where);
  35. } else
  36. $this->userRoles = [];
  37. }
  38. public function generatePassword(string $clearPassword)
  39. {
  40. return password_hash($this->username . "|$clearPassword", PASSWORD_BCRYPT);
  41. }
  42. /**
  43. * Reload user from $_SESSION
  44. */
  45. public static function Restore()
  46. {
  47. global $f3;
  48. $userId = $f3->get('SESSION.user');
  49. return new User(['id=?', $userId]);
  50. }
  51. /**
  52. * Save user in $_SESSION
  53. */
  54. public function Store()
  55. {
  56. global $f3;
  57. $f3->set('SESSION.user', $this->id);
  58. }
  59. /**
  60. * Check if user can do <$permissionName>
  61. *
  62. * @param string $permissionName
  63. * @return bool
  64. */
  65. public function hasPermission(string $permissionName): bool
  66. {
  67. if ($this->userRoles)
  68. return in_array($permissionName, $this->userRoles);
  69. else
  70. return false;
  71. }
  72. public function grantPermission(string $permissionName)
  73. {
  74. if (!in_array($permissionName, $this->userRoles))
  75. array_push($this->userRoles, $permissionName);
  76. }
  77. public function removePermission(string $permissionName)
  78. {
  79. $i = array_search($permissionName, $this->userRoles);
  80. if ($i !== false)
  81. unset($this->userRoles[$i]);
  82. }
  83. public function save()
  84. {
  85. $this->roles = serialize($this->userRoles);
  86. return parent::save(); // TODO: Change the autogenerated stub
  87. }
  88. /**
  89. * @return array
  90. */
  91. public function getRoles(): array
  92. {
  93. return $this->userRoles;
  94. }
  95. }