0

I am trying to work my path through the source of DoctrineModule for Zend2, since comprehensive documentation for beginners is virtually non-existent.

In there, I found a custom authentication adapter, ObjectRepository. This class takes an object of DoctrineModule\Options\Authentication. All I need to set the credentialCallable value to a custom, BCrypt-based function.

I wrote a class for my controllers to wrap the adapter:

namespace User\Controller\Plugin;

class UserAuthentication extends AbstractPlugin {
    protected $_authAdapter = null;
    protected $_authService = null;

    public function __construct($authAdapter) {
        $this->setAuthAdapter($authAdapter);
    }
    // More setters/getters
}

Now I need to configure the module in a way that this call here will give me a valid instance.

$uAuth = $this->getServiceLocator()->get('User\Controller\Plugin\UserAuthentication');

So naturally, I will have to work with the module condifguration. But here I am completely and entirely stuck, as I could not find any hint on how to create the instances of the classes properly. This is what I came up with so far:

return array(
    'di' => array(
        'instance' => array(
            'User\Event\Authentication' => array(
                'parameters' => array(
                    'userAuthenticationPlugin' => 'User\Controller\Plugin\UserAuthentication',
                ),
            ),
            'User\Controller\Plugin\UserAuthentication' => array(
                'parameters' => array(
                    'authAdapter' => 'DoctrineModule\Authentication\Adapter\ObjectRepository'
                ),
            ),
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'DoctrineModule\Authentication\Adapter\ObjectRepository' => function ($sm) {
                /// ????
            },
            'DoctrineModule\Options\Authentication' => function($sm) {                
                /// ????
            },
        ),
    ),
);

So I have no idea what to fill in there, or if this is even the correct way to go. Perhaps I go the wrong path entirely, since when executing this, I get:

An abstract factory could not create an instance of usercontrollerpluginuserauthentication(alias: User\Controller\Plugin\UserAuthentication).

I appreciate any ideas and hints. And please don't direct me to ZfcUser or similar, I want/need to implement this myself.

Lanbo
  • 15,118
  • 16
  • 70
  • 147

1 Answers1

2

I have not worked with Di in ZF2, yet. But here is how I use the DoctrineModule ObjectRepository in ZF2.

In my Module.php I have a factory for the AuthenticationService, just like you have an AuthenticationService. In the Factory I create a new ObjectRepository with all values it requires.

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'AuthService' => function($services) {
                $entityManager = $services->get('doctrine.entitymanager.orm_default');
                $doctrineAuthAdapter = new ObjectRepository(array(
                    'objectManager' => $entityManager,
                    'identityClass' => 'Auth\Entity\User',
                    'identityProperty' => 'username',
                    'credentialProperty' => 'password',
                    'credentialCallable' => function($identity, $credential) {
                        return md5($identity->salt . $credential);
                    }, // this function makes the password hash salted
                       // you could also just use return md5($credential);
                ));

                // my AuthenticationService uses the entity manager
                // and the ObjectRepository
                $authService = new AuthenticationService();
                $authService->setEntityManager($entityManager);
                $authService->setAdapter($doctrineAuthAdapter);

                return $authService;
            },
        ),
    );
}

The AuthenticationService is basically an extension of Zend's AuthenticationService with some additional methods, I found useful (and Zfc uses, because I peeked from there). For brevitiy’s sake, I removed the implementations, but left the declarations to allow you to see what I thought could be useful in the service.

<?php

namespace Auth\Service;

use Application\EntityManagerAwareInterface;
use Zend\Authentication\AuthenticationService as ZendAuthenticationService;

use Auth\Entity\User;

class AuthenticationService extends ZendAuthenticationService implements EntityManagerAwareInterface
{
    /**
     * This method makes sure that we always get a User-object
     * we can call methods on. In case of a non-authorized user
     * we will receive a dummy object without storage or with
     * session storage. So data might be lost!
     */
    public function getIdentity()
    {
        $storage = $this->getStorage();

        if ($storage->isEmpty()) {
            return new \Auth\Entity\User\Dummy();
        }

        $userid = $storage->read();

        $user = $this->getEntityManager()->find('Auth\Entity\User', $userid);

        if ($user == null) {
            return new \Auth\Entity\User\Dummy();
        } else {
            return $user;
        }
    }

    /**
     * Register a new user to the system. The user password will by hashed before
     * it will be saved to the database.
     */
    public function register(User $user)
    {

    }

    /**
     * Reset the users password to a random value and send an e-mail to the
     * user containing the new password.
     */
    public function resetPassword(User $user)
    {

    }

    /**
     * Delete a users account from the database. This does not really delete the
     * user, as there are too many connections to all other tables, but rather
     * deletes all personal information from the user records.
     */
    public function delete(User $user)
    {

    }

    public function setEntityManager(\Doctrine\ORM\EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function getEntityManager()
    {
        return $this->entityManager;
    }
}

Then in the Controller I can use the following piece of code to login a user:

// getAuthService() just calls $this->getServiceLocator()->get('AuthService')

$this->getAuthService()->getAdapter()
     ->setIdentityValue($username)
     ->setCredentialValue($password);

$result = $this->getAuthService()->authenticate();

foreach($result->getMessages() as $message) {
    $this->flashmessenger()->addMessage($message);
}

if ($result->isValid()) {
     $this->getAuthService()->getStorage()->write($result->getIdentity()->getId());
     return true;
 } else {
     return false;
 }
aufziehvogel
  • 7,167
  • 5
  • 34
  • 56
  • This helps a lot, thanks. I'll try it soon. I also saw that my plugin is actually an AuthService an I should use is as such. – Lanbo Feb 24 '13 at 11:54
  • 1
    This answer works, but it's a bit clumsy. Take a look at http://stackoverflow.com/questions/12092091/zend-2-doctrine-2-auth-adapter/12101461#12101461 for a simpler approach. – superdweebie Feb 25 '13 at 11:47