security.rst 27 KB

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