php - Symfony2 add role after registration to user account using event_subscriber and FOSUser bundle -
working on first large symfony2 project , i'm having little trouble grasping what's going on event listener/subscribers.
i want have event subscriber adds role (blog_user) fosuser entity after user registers account.
here's i've got far:
registration listener:
namespace myblog\sitebundle\eventlistener; use fos\userbundle\fosuserevents; use fos\userbundle\event\formevent; use symfony\component\eventdispatcher\eventsubscriberinterface; class registrationlistener implements eventsubscriberinterface { public static function getsubscribedevents() { return array( fosuserevents::registration_success => 'onregistrationsuccess', ); } public function onregistrationsuccess(formevent $event){ $rolesarr = array('role_user', 'blog_user'); $user = $event->getform()->getdata(); $user->setroles($rolesarr); } }
services.yml:
services: myblog_user.registration_listener: class: myblog\sitebundle\eventlistener\registrationlistener arguments: [] tags: - { name: kernel.event_subscriber }
security.yml:
access_control: - { path: ^/blog/, role: blog_user }
so far when register new user, can't access /blog route (which set of crud screens) - "access denied" message expected user without blog_user role.
edit:
my code appear add role user in database. in fos_user table under roles user has this:
a:1:{i:0;s:9:"blog_user";}
it seems access_control doesn't see however.
{% if is_granted('blog_user') %}
is_granted fails - can't see roles user has...
as explained in comments, problem in role name. roles must start role_
. solution set role hierarchy lite that
role_blog_user: role_user
quote documetation
all roles must begin role_ prefix managed symfony2. if define own roles dedicated role class (more advanced), don't use role_ prefix.
Comments
Post a Comment