src/Security/Voter/FileVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\CompanyDemand;
  4. use App\Entity\DemandFile;
  5. use App\Entity\File;
  6. use App\Entity\User;
  7. use LogicException;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. class FileVoter extends Voter
  11. {
  12. protected function supports(string $attribute, $subject): bool
  13. {
  14. // replace with your own logic
  15. // https://symfony.com/doc/current/security/voters.html
  16. return in_array($attribute, ['FILE_DOWNLOAD', 'FILE_REMOVE'], true)
  17. && $subject instanceof File;
  18. }
  19. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  20. {
  21. $user = $token->getUser();
  22. // if the user is anonymous, do not grant access
  23. if (!$user instanceof User) {
  24. return false;
  25. }
  26. /** @var File $file */
  27. $file = $subject;
  28. switch ($attribute) {
  29. case 'FILE_REMOVE':
  30. return $file->getUser() === $user;
  31. case 'FILE_DOWNLOAD':
  32. if ($file->getUser() === $user) {
  33. return true;
  34. }
  35. if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
  36. return true;
  37. }
  38. // at this stage, we already know that the current user is a company who is trying to download a demand file
  39. if ($file->getDemandFile()) {
  40. $demand = $file->getDemandFile()->getDemand();
  41. if ($file->getDemandFile()->getType() === DemandFile::USER_PROOF_TYPE) {
  42. return false;
  43. }
  44. return $demand->getCompanyDemands()->exists(function (int $key, CompanyDemand $companyDemand) use ($user): bool {
  45. return $companyDemand->getCompany() === $user->getCompanies()->first();
  46. });
  47. }
  48. if ($file->getDemandTree()) {
  49. $demand = $file->getDemandTree()->getDemand();
  50. return $demand->getCompanyDemands()->exists(function (int $key, CompanyDemand $companyDemand) use ($user): bool {
  51. return $companyDemand->getCompany() === $user->getCompanies()->first();
  52. });
  53. }
  54. throw new LogicException('Unexpected case.');
  55. }
  56. return false;
  57. }
  58. }