RoleSecurityHandler.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Sonata project.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Security\Handler;
  11. use Symfony\Component\Security\Core\SecurityContextInterface;
  12. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  13. use Sonata\AdminBundle\Admin\AdminInterface;
  14. class RoleSecurityHandler implements SecurityHandlerInterface
  15. {
  16. protected $securityContext;
  17. protected $superAdminRoles;
  18. /**
  19. * @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
  20. * @param array $superAdminRoles
  21. */
  22. public function __construct(SecurityContextInterface $securityContext, array $superAdminRoles)
  23. {
  24. $this->securityContext = $securityContext;
  25. $this->superAdminRoles = $superAdminRoles;
  26. }
  27. /**
  28. * {@inheritDoc}
  29. */
  30. public function isGranted(AdminInterface $admin, $attributes, $object = null)
  31. {
  32. if (!is_array($attributes)) {
  33. $attributes = array($attributes);
  34. }
  35. foreach ($attributes as $pos => $attribute) {
  36. $attributes[$pos] = sprintf($this->getBaseRole($admin), $attribute);
  37. }
  38. try {
  39. return $this->securityContext->isGranted($this->superAdminRoles) || $this->securityContext->isGranted($attributes);
  40. } catch (AuthenticationCredentialsNotFoundException $e) {
  41. return false;
  42. } catch (\Exception $e) {
  43. throw $e;
  44. }
  45. }
  46. /**
  47. * {@inheritDoc}
  48. */
  49. public function getBaseRole(AdminInterface $admin)
  50. {
  51. return 'ROLE_' . str_replace('.', '_', strtoupper($admin->getCode())) . '_%s';
  52. }
  53. /**
  54. * {@inheritDoc}
  55. */
  56. public function buildSecurityInformation(AdminInterface $admin)
  57. {
  58. return array();
  59. }
  60. /**
  61. * {@inheritDoc}
  62. */
  63. public function createObjectSecurity(AdminInterface $admin, $object)
  64. {
  65. }
  66. /**
  67. * {@inheritDoc}
  68. */
  69. public function deleteObjectSecurity(AdminInterface $admin, $object)
  70. {
  71. }
  72. }