src/Security/Voter/UserVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. class UserVoter extends Voter
  8. {
  9. const DOCTOR_MANAGE = 'DOCTOR_MANAGE';
  10. const STUDENT_MANAGE = 'STUDENT_MANAGE';
  11. /**
  12. * @var Security
  13. */
  14. private $security;
  15. /**
  16. * UserVoter constructor.
  17. * @param Security $security
  18. */
  19. public function __construct(Security $security)
  20. {
  21. $this->security = $security;
  22. }
  23. protected function supports($attribute, $subject)
  24. {
  25. return in_array($attribute, [self::DOCTOR_MANAGE, self::STUDENT_MANAGE])
  26. && $subject instanceof User;
  27. }
  28. protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
  29. {
  30. /** @var User $user */
  31. $user = $token->getUser();
  32. // if the user is anonymous, do not grant access
  33. if (!$user instanceof User) {
  34. return false;
  35. }
  36. // if the user is anonymous, do not grant access
  37. if (!in_array('ROLE_ADMIN', $user->getRoles()) || !in_array('ROLE_ECITY', $user->getRoles())) {
  38. return false;
  39. }
  40. // get user permissions
  41. $permissions = $user->getPermissions();
  42. if( !is_array($permissions) ) {
  43. return false;
  44. }
  45. switch ($attribute) {
  46. case self::DOCTOR_MANAGE:
  47. if (in_array('DOCTOR_MANAGE', $permissions)) {
  48. return true;
  49. }
  50. break;
  51. case self::STUDENT_MANAGE:
  52. if (in_array('STUDENT_MANAGE', $permissions)) {
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. }