ZF2 AuthenticationService

时间:2014-09-30 15:22:37

标签: authentication doctrine-orm zend-framework2

我想使用用户名或电子邮件地址登录。我现在只能使用用户名登录。我怎么能用ZF2做到这一点? (我用doctirine)

谢谢

$authService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
// Do the same you did for the ordinar Zend AuthService
$adapter = $authService->getAdapter();
$adapter->setIdentityValue($post['username']); //$data['usr_name']
$adapter->setCredentialValue($post['password']); // $data['usr_password']
$authResult = $authService->authenticate();

if ($authResult->isValid()) {
    $identity = $authResult->getIdentity();

    $authService->getStorage()->write($identity);
    $time = 1209600; // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days

    if ($post['rememberme']) {
        $sessionManager = new \Zend\Session\SessionManager();
        $sessionManager->rememberMe($time);
    }
}

2 个答案:

答案 0 :(得分:0)

这是在zfcUser模块中实现的方式:

    $userObject = null;

    // Cycle through the configured identity sources and test each
    $fields = $this->getOptions()->getAuthIdentityFields();
    while (!is_object($userObject) && count($fields) > 0) {
        $mode = array_shift($fields);
        switch ($mode) {
            case 'username':
                $userObject = $this->getMapper()->findByUsername($identity);
                break;
            case 'email':
                $userObject = $this->getMapper()->findByEmail($identity);
                break;
        }
    }

    if (!$userObject) {
        $e->setCode(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND)
          ->setMessages(array('A record with the supplied identity could not be found.'));
        $this->setSatisfied(false);
        return false;
    }

答案 1 :(得分:0)

如果您的 module.config 中包含此代码,则可以修改 identity_property credential_property ,以使用mail / nameUser / userName进行登录/等...

'doctrine' => array(
        // 1) for Aithentication
        'authentication' => array( // this part is for the Auth adapter from DoctrineModule/Authentication
            'orm_default' => array(
                'object_manager' => 'Doctrine\ORM\EntityManager',
                // object_repository can be used instead of the object_manager key
                'identity_class' => 'Application\Entity\Users', //'Application\Entity\User',
                'identity_property' => 'usrName', // 'username', // 'email',
                'credential_property' => 'usrPassword', // 'password',
                'credential_callable' => function($user, $passwordGiven) { // not only User
                    if ($user->getUsrPassword() == md5('aFGQ475SDsdfsaf2342' . $passwordGiven . $user->getUsrPasswordSalt()) &&
                        $user->getUsrActive() == 1) {
                        return true;
                    }
                    else {
                        return false;
                    }
                },
            ),
        ),
    ),