RoleSecurityHandler.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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)
  40. || $this->securityContext->isGranted($attributes, $object);
  41. } catch (AuthenticationCredentialsNotFoundException $e) {
  42. return false;
  43. } catch (\Exception $e) {
  44. throw $e;
  45. }
  46. }
  47. /**
  48. * {@inheritDoc}
  49. */
  50. public function getBaseRole(AdminInterface $admin)
  51. {
  52. return 'ROLE_' . str_replace('.', '_', strtoupper($admin->getCode())) . '_%s';
  53. }
  54. /**
  55. * {@inheritDoc}
  56. */
  57. public function buildSecurityInformation(AdminInterface $admin)
  58. {
  59. return array();
  60. }
  61. /**
  62. * {@inheritDoc}
  63. */
  64. public function createObjectSecurity(AdminInterface $admin, $object)
  65. {
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. public function deleteObjectSecurity(AdminInterface $admin, $object)
  71. {
  72. }
  73. }