Question

I'm using bjyauthorize and I works great for existing users. I now are in need to add users dynamically.

I can set the connection between User and Role manually in the table UserRoleLinker but how do I it the way it is meant to be for new users? Maybe I missed something trivial?

Thanks!

Was it helpful?

Solution

The ZfcUser User service triggers a register.post event after the user is inserted in the db, so you just need to listen to that event. You can do that by attaching a listener to the shared events manager in your module bootstrap.

The event instance received by your listener contains the user service itself, plus the user data, and the form that was used during registration, which should be enough to make the link

public function onBootstrap(MvcEvent $e)
{
    $app = $e->getApplication();
    $events = $app->getEventManager();
    $shared = $events->getSharedManager();
    $sm = $app->getServiceManager();

    $shared->attach('ZfcUser\Service\User', 'register.post', function ($e) use ($sm) {
         $userService = $e->getTarget();
         $newUser = $e->getParam('user');
         $registrationForm = $e->getParam('form');
         // do something with the new user info, eg, assign new user role...
    });
}

OTHER TIPS

Here's the full solution:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    //You need a copy of the service manager and it has to be set as a member for the lambda function to call it
    $this->sm = $e->getApplication()->getServiceManager();

    $zfcServiceEvents = $e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager();

    $zfcServiceEvents->attach('register.post', function($e) {

        /** @var \User\Entity\UserPdo $user */
        $user = $e->getParam('user');

        //This is the adapter that both bjyAuthorize and zfcuser use
        $adapter     = $this->sm->get('zfcuser_zend_db_adapter');

        //Build the insert statement
        $sql = new \Zend\Db\Sql\Sql($adapter);

        //bjyAuthorize uses a magic constant for the table name
        $insert = new \Zend\Db\Sql\Insert('user_role_linker');
        $insert->columns(array('user_id', 'role_id'));
        $insert->values(array('user_id' => $user->getId(), 'role_id' => 'user'), $insert::VALUES_MERGE);

        //Execute the insert statement
        $adapter->query($sql->getSqlStringForSqlObject($insert), $adapter::QUERY_MODE_EXECUTE);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top