2014-09-30 61 views
-2

我想用用戶名或電子郵件地址登錄。我現在可以用用戶名登錄。我如何用ZF2做到這一點? (我用doctirine)ZF2 AuthenticationService

謝謝

$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); 
    } 
} 
+0

1.格式化問題更好2.提高投票率 – tasmaniski 2014-10-01 12:21:48

回答

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; 
    } 
0

如果你在你的module.config這個代碼,你可以修改identity_property and credential_property,用於登錄郵件/ nameUser/userName/etc ...

'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; 
        } 
       }, 
      ), 
     ), 
    ),