Question

I have a ZF2 with module ZfcUser setuped.

Registration and Login forms are working fine. I made a custom module to connect to Linkedin and get the info of a user, then register the user data in the Database.

The register part is done, but the issue I'm facing is that I need to login the user with Data from the Database (I have all the information about the user, so I know what user should be logged in), but I can not find a way to make ZfcUser login a specific user using PHP and not the login form.

I'm not good with the adapters and \Zend\Authentication. I would appreciate any help or directions.

I tried to look at the login procedure in the ZfcUser Controller, but it's confusing me more then helping me.

I also tried looking for the answer in google, but I found nothing on the topic.

If possible, I would like that "forced login procedure" to be outside of the ZfcUser module.

After a few hours of looking at the ZfcUser Controller I managed to build a method to do what i want

/**
* Change the currently logged user
* @param integer $user_id
*/
public function setLoggedUser($user_id) {
 $storage = new \Zend\Session\Container('Zend_Auth');
 $storage->storage = $user_id;
}
Was it helpful?

Solution

Setting the user id directly on your storage has some downsides. It (obviously) won't work if you use another storage engine. And events registered on ZFCUser's AuthService will not be executed.

I would solve this issue by using a custom authentication adapter. This Adapter can be called from a controller in the following way:

$this->zfcUserAuthentication()->getAuthService()->authenticate(new ForceLogin($user));

The implementation looks as follows:

class ForceLogin implements Zend\Authentication\Adapter\AdapterInterface
{
    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * @param $user
     */
    function __construct($user)
    {
        $this->user = $user;
    }

    public function authenticate()
    {
        return new Zend\Authentication\Result(
            Result::SUCCESS,
            $this->getUser()->getId()
        );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top