security.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. Security
  2. ========
  3. Users management
  4. ----------------
  5. By default, the SonataAdminBundle does not come with any user management,
  6. however it is most likely the application requires such feature. The Sonata
  7. Project includes a ``SonataUserBundle`` which integrates the ``FOSUserBundle``.
  8. The ``FOSUserBundle`` adds support for a database-backed user system in Symfony2.
  9. It provides a flexible framework for user management that aims to handle common
  10. tasks such as user login, registration and password retrieval.
  11. The ``SonataUserBundle`` is just a thin wrapper to include the ``FOSUserBundle``
  12. into the ``AdminBundle``. The ``SonataUserBundle`` includes :
  13. * A default login area
  14. * A default ``user_block`` template which is used to display the current user
  15. and the logout link
  16. * 2 Admin classes : User and Group
  17. * A default class for User and Group.
  18. There is a little magic in the ``SonataAdminBundle`` : if the bundle detects the
  19. ``SonataUserBundle`` class, then the default ``user_block`` template will be
  20. changed to use the one provided by the ``SonataUserBundle``.
  21. The install process is available on the dedicated `SonataUserBundle's
  22. documentation area
  23. <http://sonata-project.org/bundles/user/master/doc/reference/installation.html>`_
  24. Security handlers
  25. -----------------
  26. The security part is managed by a ``SecurityHandler``, the bundle comes with 3
  27. handlers
  28. - ``sonata.admin.security.handler.role`` : ROLES to handle permissions
  29. - ``sonata.admin.security.handler.acl`` : ACL and ROLES to handle permissions
  30. - ``sonata.admin.security.handler.noop`` : always returns true, can be used
  31. with the Symfony2 firewall
  32. The default value is ``sonata.admin.security.handler.noop``, if you want to
  33. change the default value you can set the ``security_handler`` to
  34. ``sonata.admin.security.handler.acl`` or ``sonata.admin.security.handler.role``.
  35. To quickly secure an admin the role security can be used. It allows to specify
  36. the actions a user can with the admin. The ACL security system is more advanced
  37. and allows to secure the objects. For people using the previous ACL
  38. implementation, you can switch the security_handler to the role security handler.
  39. Configuration
  40. ~~~~~~~~~~~~~
  41. Only the security handler is required to determine which type of security to use.
  42. The other parameters are set as default, change them if needed.
  43. Using roles:
  44. .. code-block:: yaml
  45. sonata_admin:
  46. security:
  47. handler: sonata.admin.security.handler.role
  48. Using ACL:
  49. .. code-block:: yaml
  50. # app/config/config.yml
  51. sonata_admin:
  52. security:
  53. handler: sonata.admin.security.handler.acl
  54. # acl security information
  55. information:
  56. GUEST: [VIEW, LIST]
  57. STAFF: [EDIT, LIST, CREATE]
  58. EDITOR: [OPERATOR, EXPORT]
  59. ADMIN: [MASTER]
  60. # permissions not related to an object instance and also to be available when objects do not exist
  61. # the DELETE admin permission means the user is allowed to batch delete objects
  62. admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
  63. # permission related to the objects
  64. object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]
  65. Later, we will explain how to set up ACL with the
  66. ``FriendsOfSymfony/UserBundle``.
  67. Role handler
  68. -----------------
  69. The ``sonata.admin.security.handler.role`` allows you to operate finely on the actions that can be done (den peding on the entity class), without requiring to set up ACL.
  70. Configuration
  71. ~~~~~~~~~~~~~
  72. First, activate the role security handler as described above.
  73. Each time an user tries to do an action in the admin, Sonata checks if he is either a super admin (``ROLE_SUPER_ADMIN``) **or** has the permission.
  74. The permissions are:
  75. * LIST: view the list of objects
  76. * VIEW: view the detail of one object
  77. * CREATE
  78. * EDIT
  79. * DELETE
  80. * EXPORT (for the native Sonata export links)
  81. Each permission is relative to an admin: if you try to get a list in FooAdmin (declared as ``sonata.admin.demo.foo``
  82. service), Sonata will check if the user has the ``ROLE_SONATA_ADMIN_DEMO_FOO_EDIT`` role.
  83. So our ``security.yml`` file may look to something like this:
  84. .. code-block:: yaml
  85. security:
  86. ...
  87. role_hierarchy:
  88. # for convenience, I decided to gather Sonata roles here
  89. ROLE_SONATA_FOO_READER:
  90. - ROLE_SONATA_ADMIN_DEMO_FOO_LIST
  91. - ROLE_SONATA_ADMIN_DEMO_FOO_VIEW
  92. ROLE_SONATA_FOO_EDITOR:
  93. - ROLE_SONATA_ADMIN_DEMO_FOO_CREATE
  94. - ROLE_SONATA_ADMIN_DEMO_FOO_EDIT
  95. ROLE_SONATA_FOO_ADMIN:
  96. - ROLE_SONATA_ADMIN_DEMO_FOO_DELETE
  97. - ROLE_SONATA_ADMIN_DEMO_FOO_EXPORT
  98. # those are the roles I will use (less verbose)
  99. ROLE_STAFF: [ROLE_USER, ROLE_SONATA_FOO_READER]
  100. ROLE_ADMIN: [ROLE_STAFF, ROLE_SONATA_FOO_EDITOR, ROLE_SONATA_FOO_ADMIN]
  101. ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  102. # set access_strategy to unanimous, else you may have unexpected behaviors
  103. access_decision_manager:
  104. strategy: unanimous
  105. Note that we also set ``access_strategy`` to unanimous.
  106. It means that if one voter (for example Sonata) refuses access, access will be denied.
  107. For more information on this subject, please see `here
  108. <http://symfony.com/doc/2.2/cookbook/security/voters.html#changing-the-access-decision-strategy>`_
  109. Usage
  110. ~~~~~
  111. You can now test if an user is authorized from an Admin class:
  112. .. code-block:: php
  113. if ($this->isGranted('LIST')) {
  114. ...
  115. }
  116. From a controller extending ``Sonata\AdminBundle\Controller\CRUDController``:
  117. .. code-block:: php
  118. if ($this->admin->isGranted('LIST')) {
  119. ...
  120. }
  121. Or from a Twig template:
  122. .. code-block:: jinja
  123. {% if is_granted('VIEW') %}
  124. <p>Hello there!</p>
  125. {% endif %}
  126. Note that you don't have to re-specify the prefix.
  127. Sonata check those permissions for the action it handles internally. Of course you will have to recheck them in your own code.
  128. Yon can also create your own permissions, for example ``EMAIL`` (which will turn into role ``ROLE_SONATA_ADMIN_DEMO_FOO_EMAIL``).
  129. Going further
  130. ~~~~~~~~~~~~~
  131. Because Sonata role handler supplements Symfony2 security, but does not override it, you are free to do more advanced operations.
  132. For example, you can create your `own voter
  133. <http://symfony.com/doc/2.2/cookbook/security/voters.html>`_
  134. Customizing the handler behavior
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. If you want to change the handler behavior (for example, to pass the current object to voters), extend
  137. ``Sonata\AdminBundle\Security\Handler\RoleSecurityHandler``, and override the ``isGranted`` method.
  138. Then declare your handler as a service:
  139. .. code-block:: xml
  140. <parameters>
  141. <parameter key="acme.demo.security.handler.role.class" >Acme\DemoBundle\Security\Handler\RoleSecurityHandler</parameter>
  142. </parameters>
  143. <services>
  144. <service id="acme.demo.security.handler.role" class="%acme.demo.security.handler.role.class%" public="false">
  145. <argument type="service" id="security.context" on-invalid="null" />
  146. <argument type="collection">
  147. <argument>ROLE_SUPER_ADMIN</argument>
  148. </argument>
  149. </service>
  150. ...
  151. And specify it as Sonata security handler on your configuration (``config.yml``):
  152. .. code-block: yaml
  153. sonata_admin:
  154. security:
  155. handler: acme.demo.security.handler.role
  156. ACL and FriendsOfSymfony/UserBundle
  157. -----------------------------------
  158. If you want an easy way to handle users, please use :
  159. - https://github.com/FriendsOfSymfony/FOSUserBundle : handle users and groups
  160. stored in RDMS or MongoDB
  161. - https://github.com/sonata-project/SonataUserBundle : integrates the
  162. ``FriendsOfSymfony/UserBundle`` with the ``AdminBundle``
  163. The security integration is a work in progress and has some known issues :
  164. - ACL permissions are immutables
  165. - A listener must be implemented that creates the object Access Control List
  166. with the required rules if objects are created outside the Admin
  167. Configuration
  168. ~~~~~~~~~~~~~
  169. Before you can use ``FriendsOfSymfony/FOSUserBundle`` you need to set it up as
  170. described in the documentation of the bundle. In step 4 you need to create a
  171. User class (in a custom UserBundle). Do it as follows:
  172. .. code-block:: php
  173. <?php
  174. namespace Acme\UserBundle\Entity;
  175. use Sonata\UserBundle\Entity\BaseUser as BaseUser;
  176. use Doctrine\ORM\Mapping as ORM;
  177. /**
  178. * @ORM\Entity
  179. * @ORM\Table(name="fos_user")
  180. \*/
  181. class User extends BaseUser
  182. {
  183. /**
  184. * @ORM\Id
  185. * @ORM\Column(type="integer")
  186. * @ORM\GeneratedValue(strategy="AUTO")
  187. \*/
  188. protected $id;
  189. public function __construct()
  190. {
  191. parent::__construct();
  192. // your own logic
  193. }
  194. }
  195. In your ``app/config/config.yml`` you then need to put the following:
  196. .. code-block:: yaml
  197. fos_user:
  198. db_driver: orm
  199. firewall_name: main
  200. user_class: Acme\UserBundle\Entity\User
  201. The following configuration for the SonataUserBundle defines:
  202. - the ``FriendsOfSymfony/FOSUserBundle`` as a security provider
  203. - the login form for authentication
  204. - the access control : resources with related required roles, the important
  205. part is the admin configuration
  206. - the ``acl`` option to enable the ACL.
  207. - the ``AdminPermissionMap`` defines the permissions of the Admin class
  208. .. code-block:: yaml
  209. # app/config/security.yml
  210. parameters:
  211. # ... other parameters
  212. security.acl.permission.map.class: Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap
  213. # optionally use a custom MaskBuilder
  214. #sonata.admin.security.mask.builder.class: Sonata\AdminBundle\Security\Acl\Permission\MaskBuilder
  215. In ``app/config/security.yml``:
  216. .. code-block:: yaml
  217. security:
  218. providers:
  219. fos_userbundle:
  220. id: fos_user.user_manager
  221. firewalls:
  222. main:
  223. pattern: .*
  224. form-login:
  225. provider: fos_userbundle
  226. login_path: /login
  227. use_forward: false
  228. check_path: /login_check
  229. failure_path: null
  230. logout: true
  231. anonymous: true
  232. access_control:
  233. # The WDT has to be allowed to anonymous users to avoid requiring the login with the AJAX request
  234. - { path: ^/wdt/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  235. - { path: ^/profiler/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  236. # AsseticBundle paths used when using the controller for assets
  237. - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  238. - { path: ^/css/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  239. # URL of FOSUserBundle which need to be available to anonymous users
  240. - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  241. - { path: ^/login_check$, role: IS_AUTHENTICATED_ANONYMOUSLY } # for the case of a failed login
  242. - { path: ^/user/new$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  243. - { path: ^/user/check-confirmation-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  244. - { path: ^/user/confirm/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  245. - { path: ^/user/confirmed$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  246. - { path: ^/user/request-reset-password$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  247. - { path: ^/user/send-resetting-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  248. - { path: ^/user/check-resetting-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  249. - { path: ^/user/reset-password/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  250. # Secured part of the site
  251. # This config requires being logged for the whole site and having the admin role for the admin part.
  252. # Change these rules to adapt them to your needs
  253. - { path: ^/admin/, role: ROLE_ADMIN }
  254. - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
  255. role_hierarchy:
  256. ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
  257. ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  258. acl:
  259. connection: default
  260. - Install the ACL tables ``php app/console init:acl``
  261. - Create a new root user :
  262. .. code-block:: sh
  263. # php app/console fos:user:create --super-admin
  264. Please choose a username:root
  265. Please choose an email:root@domain.com
  266. Please choose a password:root
  267. Created user root
  268. If you have Admin classes, you can install or update the related CRUD ACL rules :
  269. .. code-block:: sh
  270. # php app/console sonata:admin:setup-acl
  271. Starting ACL AdminBundle configuration
  272. > install ACL for sonata.media.admin.media
  273. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_GUEST, permissions: ["VIEW","LIST"]
  274. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_STAFF, permissions: ["EDIT","LIST","CREATE"]
  275. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_EDITOR, permissions: ["OPERATOR","EXPORT"]
  276. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_ADMIN, permissions: ["MASTER"]
  277. ... skipped ...
  278. If you already have objects, you can generate the object ACL rules for each
  279. object of an admin:
  280. .. code-block:: sh
  281. $ php app/console sonata:admin:generate-object-acl
  282. Optionally, you can specify an object owner, and step through each admin. See
  283. the help of the command for more information.
  284. If you try to access to the admin class you should see the login form, just
  285. log in with the ``root`` user.
  286. An Admin is displayed in the dashboard (and menu) when the user has the role
  287. ``LIST``. To change this override the ``showIn`` method in the Admin class.
  288. Roles and Access control lists
  289. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  290. A user can have several roles when working with an application. Each Admin class
  291. has several roles, and each role specifies the permissions of the user for the
  292. ``Admin`` class. Or more specifically, what the user can do with the domain object(s)
  293. the ``Admin`` class is created for.
  294. By default each ``Admin`` class contains the following roles, override the
  295. property ``$securityInformation`` to change this:
  296. - ``ROLE_SONATA_..._GUEST`` : a guest that is allowed to view an object and a
  297. list of objects;
  298. - ``ROLE_SONATA_..._STAFF`` : probably the biggest part of the users, a staff
  299. user has the same permissions as guests and is additionally allowed to
  300. ``EDIT`` and ``CREATE`` new objects;
  301. - ``ROLE_SONATA_..._EDITOR`` : an editor is granted all access and, compared to
  302. the staff users, is allowed to ``DELETE``;
  303. - ``ROLE_SONATA_..._ADMIN`` : an administrative user is granted all access and
  304. on top of that, the user is allowed to grant other users access.
  305. Owner:
  306. - when an object is created, the currently logged in user is set as owner for
  307. that object and is granted all access for that object;
  308. - this means the user owning the object is always allowed to ``DELETE`` the
  309. object, even when it only has the staff role.
  310. Vocabulary used for Access Control Lists:
  311. - **Role :** a user role;
  312. - **ACL :** a list of access rules, the Admin uses 2 types:
  313. - **Admin ACL :** created from the Security information of the Admin class
  314. for each admin and shares the Access Control Entries that specify what
  315. the user can do (permissions) with the admin
  316. - **Object ACL :** also created from the security information of the ``Admin``
  317. class however created for each object, it uses 2 scopes:
  318. - **Class-Scope :** the class scope contains the rules that are valid
  319. for all object of a certain class;
  320. - **Object-Scope :** specifies the owner;
  321. - **Sid :** Security identity, an ACL role for the Class-Scope ACL and the
  322. user for the Object-Scope ACL;
  323. - **Oid :** Object identity, identifies the ACL, for the admin ACL this is
  324. the admin code, for the object ACL this is the object id;
  325. - **ACE :** a role (or sid) and its permissions;
  326. - **Permission :** this tells what the user is allowed to do with the Object
  327. identity;
  328. - **Bitmask :** a permission can have several bitmasks, each bitmask
  329. represents a permission. When permission ``VIEW`` is requested and it
  330. contains the ``VIEW`` and ``EDIT`` bitmask and the user only has the
  331. ``EDIT`` permission, then the permission ``VIEW`` is granted.
  332. - **PermissionMap :** configures the bitmasks for each permission, to change
  333. the default mapping create a voter for the domain class of the Admin.
  334. There can be many voters that may have different permission maps. However,
  335. prevent that multiple voters vote on the same class with overlapping bitmasks.
  336. See the cookbook article "Advanced ACL concepts" for the meaning of the different
  337. permissions:
  338. http://symfony.com/doc/current/cookbook/security/acl_advanced.html#pre-authorization-decisions.
  339. How is access granted?
  340. ~~~~~~~~~~~~~~~~~~~~~~
  341. In the application the security context is asked if access is granted for a role
  342. or a permission (``admin.isGranted``):
  343. - **Token :** a token identifies a user between requests;
  344. - **Voter :** sort of judge that returns if access is granted of denied, if the
  345. voter should not vote for a case, it returns abstrain;
  346. - **AccessDecisionManager :** decides if access is granted or denied according
  347. a specific strategy. It grants access if at least one (affirmative strategy),
  348. all (unanimous strategy) or more then half (consensus strategy) of the
  349. counted votes granted access;
  350. - **RoleVoter :** votes for all attributes stating with ``ROLE_`` and grants
  351. access if the user has this role;
  352. - **RoleHierarchieVoter :** when the role ``ROLE_SONATA_ADMIN`` is voted for,
  353. it also votes "granted" if the user has the role ``ROLE_SUPER_ADMIN``;
  354. - **AclVoter :** grants access for the permissions of the ``Admin`` class if
  355. the user has the permission, the user has a permission that is included in
  356. the bitmasks of the permission requested to vote for or the user owns the
  357. object.
  358. Create a custom voter or a custom permission map
  359. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  360. In some occasions you need to create a custom voter or a custom permission map
  361. because for example you want to restrict access using extra rules:
  362. - create a custom voter class that extends the ``AclVoter``
  363. .. code-block:: php
  364. <?php
  365. namespace Acme\DemoBundle\Security\Authorization\Voter;
  366. use FOS\UserBundle\Model\UserInterface;
  367. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  368. use Symfony\Component\Security\Acl\Voter\AclVoter;
  369. class UserAclVoter extends AclVoter
  370. {
  371. /**
  372. * {@InheritDoc}
  373. */
  374. public function supportsClass($class)
  375. {
  376. // support the Class-Scope ACL for votes with the custom permission map
  377. // return $class === 'Sonata\UserBundle\Admin\Entity\UserAdmin' || $is_subclass_of($class, 'FOS\UserBundle\Model\UserInterface');
  378. // if you use php >=5.3.7 you can check the inheritance with is_a($class, 'Sonata\UserBundle\Admin\Entity\UserAdmin');
  379. // support the Object-Scope ACL
  380. return is_subclass_of($class, 'FOS\UserBundle\Model\UserInterface');
  381. }
  382. public function supportsAttribute($attribute)
  383. {
  384. return $attribute === 'EDIT' || $attribute === 'DELETE';
  385. }
  386. public function vote(TokenInterface $token, $object, array $attributes)
  387. {
  388. if (!$this->supportsClass(get_class($object))) {
  389. return self::ACCESS_ABSTAIN;
  390. }
  391. foreach ($attributes as $attribute) {
  392. if ($this->supportsAttribute($attribute) && $object instanceof UserInterface) {
  393. if ($object->isSuperAdmin() && !$token->getUser()->isSuperAdmin()) {
  394. // deny a non super admin user to edit a super admin user
  395. return self::ACCESS_DENIED;
  396. }
  397. }
  398. }
  399. // use the parent vote with the custom permission map:
  400. // return parent::vote($token, $object, $attributes);
  401. // otherwise leave the permission voting to the AclVoter that is using the default permission map
  402. return self::ACCESS_ABSTAIN;
  403. }
  404. }
  405. - optionally create a custom permission map, copy to start the
  406. ``Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap.php`` to
  407. your bundle
  408. - declare the voter and permission map as a service
  409. .. code-block:: xml
  410. <!-- src/Acme/DemoBundle/Resources/config/services.xml -->
  411. <parameters>
  412. <parameter key="security.acl.user_voter.class">Acme\DemoBundle\Security\Authorization\Voter\UserAclVoter</parameter>
  413. <!-- <parameter key="security.acl.user_permission.map.class">Acme\DemoBundle\Security\Acl\Permission\UserAdminPermissionMap</parameter> -->
  414. </parameters>
  415. <services>
  416. <!-- <service id="security.acl.user_permission.map" class="%security.acl.permission.map.class%" public="false"></service> -->
  417. <service id="security.acl.voter.user_permissions" class="%security.acl.user_voter.class%" public="false">
  418. <tag name="monolog.logger" channel="security" />
  419. <argument type="service" id="security.acl.provider" />
  420. <argument type="service" id="security.acl.object_identity_retrieval_strategy" />
  421. <argument type="service" id="security.acl.security_identity_retrieval_strategy" />
  422. <argument type="service" id="security.acl.permission.map" />
  423. <argument type="service" id="logger" on-invalid="null" />
  424. <tag name="security.voter" priority="255" />
  425. </service>
  426. </services>
  427. - change the access decision strategy to ``unanimous``
  428. .. code-block:: yaml
  429. # app/config/security.yml
  430. security:
  431. access_decision_manager:
  432. # Strategy can be: affirmative, unanimous or consensus
  433. strategy: unanimous
  434. - to make this work the permission needs to be checked using the Object ACL
  435. - modify the template (or code) where applicable:
  436. .. code-block:: html+jinja
  437. {% if admin.isGranted('EDIT', user_object) %} {# ... #} {% endif %}
  438. - because the object ACL permission is checked, the ACL for the object must
  439. have been created, otherwise the ``AclVoter`` will deny ``EDIT`` access
  440. for a non super admin user trying to edit another non super admin user.
  441. This is automatically done when the object is created using the Admin.
  442. If objects are also created outside the Admin, have a look at the
  443. ``createSecurityObject`` method in the ``AclSecurityHandler``.
  444. Usage
  445. ~~~~~
  446. Every time you create a new ``Admin`` class, you should start with the command
  447. ``php app/console sonata:admin:setup-acl`` so the ACL database will be updated
  448. with the latest roles and permissions.
  449. In the templates, or in your code, you can use the Admin method ``isGranted()`` :
  450. - check for an admin that the user is allowed to ``EDIT`` :
  451. .. code-block:: html+jinja
  452. {# use the admin security method #}
  453. {% if admin.isGranted('EDIT') %} {# ... #} {% endif %}
  454. {# or use the default is_granted symfony helper, the following will give the same result #}
  455. {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('EDIT', admin) %} {# ... #} {% endif %}
  456. - check for an admin that the user is allowed to ``DELETE``, the object is added
  457. to also check if the object owner is allowed to ``DELETE`` :
  458. .. code-block:: html+jinja
  459. {# use the admin security method #}
  460. {% if admin.isGranted('DELETE', object) %} {# ... #} {% endif %}
  461. {# or use the default is_granted symfony helper, the following will give the same result #}
  462. {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('DELETE', object) %} {# ... #} {% endif %}
  463. ACL editor
  464. ----------
  465. SonataAdminBundle provides a user-friendly ACL editor
  466. interface.
  467. It will be automatically available if the ``sonata.admin.security.handler.acl``
  468. security handler is used and properly configured.
  469. The ACL editor is only available for users with `OWNER` or `MASTER` permissions
  470. on the object instance.
  471. The `OWNER` and `MASTER` permissions can only be edited by an user with the
  472. `OWNER` permission on the object instance.
  473. .. figure:: ../images/acl_editor.png
  474. :align: center
  475. :alt: The ACL editor
  476. :width: 700px
  477. User list customization
  478. ~~~~~~~~~~~~~~~~~~~~~~~
  479. By default, the ACL editor allows to set permissions for all users managed by
  480. ``FOSUserBundle``.
  481. To cutomize displayed user override
  482. `Sonata\AdminBundle\Controller\CRUDController::getAclUsers()`. This method must
  483. return an iterable collection of users.
  484. .. code-block:: php
  485. /**
  486. * {@InheritDoc}
  487. */
  488. protected function getAclUsers()
  489. {
  490. $userManager = $container->get('fos_user.user_manager');
  491. // Display only kevin and anne
  492. $kevin = $userManager->findUserByUsername('kevin');
  493. $anne = $userManager->findUserByUsername('anne');
  494. return array($kevin, $anne);
  495. }
  496. Custom user manager
  497. ~~~~~~~~~~~~~~~~~~~
  498. If your project does not use `FOSUserBundle`, you can globally configure another
  499. service to use when retrieving your users.
  500. - Create a service with a method called `findUsers()` returning an iterable
  501. collection of users
  502. - Update your admin configuration to reference your service name
  503. .. code-block:: yaml
  504. sonata_admin:
  505. security:
  506. acl_user_manager: my_user_manager # The name of your service