AclSecurityHandler.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 AclSecurityHandler 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. if ($object instanceof AdminInterface) {
  36. foreach ($attributes as $pos => $attribute) {
  37. $attributes[$pos] = sprintf('ROLE_%s_%s',
  38. str_replace('.', '_', strtoupper($admin->getCode())),
  39. $attribute
  40. );
  41. }
  42. }
  43. $attributes = array_merge($attributes, $this->superAdminRoles);
  44. try {
  45. return $this->securityContext->isGranted($attributes, $object);
  46. } catch (AuthenticationCredentialsNotFoundException $e) {
  47. return false;
  48. } catch (\Exception $e) {
  49. throw $e;
  50. }
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. public function buildSecurityInformation(AdminInterface $admin)
  56. {
  57. $baseRole = 'ROLE_'.str_replace('.', '_', strtoupper($admin->getCode())).'_%s';
  58. $results = array();
  59. foreach ($admin->getSecurityInformation() as $name => $permissions) {
  60. $results[sprintf($baseRole, $name)] = $permissions;
  61. }
  62. return $results;
  63. }
  64. }