security.rst 25 KB

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