2015-01-02 72 views
0

我正在使用zend 2身份驗證。現在有一種情況,用戶可以用用戶名和密碼或電子郵件和密碼登錄。是否有可能在zend 2中同時提供用戶名和電子郵件身份。否則,我該如何管理這種情況?Zend 2身份驗證:管理2身份

這是我目前的工作代碼。這裏使用電子郵件作爲身份和密碼作爲憑證。

在Module.php

public function getServiceConfig() 
{ 
    return array(
     'factories' => array(

      'AuthService' => function($sm) { 
       $dbTableAuthAdapter  = new DbTableAuthAdapter(
        $sm->get('Zend\Db\Adapter\Adapter'), 
        'users', 
        'email', 
        'password' 
       ); 
       $authService   = new AuthenticationService(); 
       $authService->setAdapter($dbTableAuthAdapter); 
       return $authService; 
      }, 

     ) 
    ); 
} 

和控制器,

$this->getAuthService()->getAdapter()->setIdentity($oRequest->getPost('username'))->setCredential(md5($oRequest->getPost('password'))); 
      $select  = $this->getAuthService()->getAdapter()->getDbSelect(); 
      $select->where('is_active = 1'); 

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

      // Authentication ends here 

      if ($oResult->isValid()) { 
     // code after authentication 
    } 

任何想法?謝謝。

+0

這肯定會需要一個自定義的認證適配器類,可能延長'的Zend \認證\適配器\ DBTABLE \ AbstractAdapter'。您可以修改「標識列」爲有效列名稱的數組,並在'authenticateCreateSelect'中構建選擇查詢時使用這些列名。 – AlexP

回答

1

如果你使用Zend \認證\適配器\ DBTABLE適配器,或許你可以嘗試這樣的事:

 $this->getAuthService()->getAdapter() 
      ->setIdentity($oRequest->getPost('username')) 
      ->setCredential(md5($oRequest->getPost('password'))); 
     $select = $this->getAuthService()->getAdapter()->getDbSelect(); 
     $select->where('is_active = 1'); 

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

     if (!$oResult->isValid()) { //authentication by username failed, try with email 
      $this->getAuthService()->getAdapter()->setIdentityColumn('email') 
       ->setIdentity($oRequest->getPost('email')) 
       ->setCredential(md5($oRequest->getPost('password'))); 

      $oResult = $this->getAuthService()->authenticate(); 
     } 
     return $oResult->isValid(); 
+0

其實我已經這樣做了。但以同樣的方式。無論如何感謝您的代碼 – Science

0

另一種方法可能是創建2的認證服務,一個用於電子郵件和另一個用戶名。

當用戶提交登錄檢查是否有效的電子郵件。在這種情況下,請使用電子郵件驗證服務。否則,請選擇用戶名認證服務。

您可以檢查其是否與Zend電子郵件驗證有效的電子郵件從Zend website

$validator = new Zend\Validator\EmailAddress(); 
if ($validator->isValid($login)) { 
    // email appears to be valid 
    // Use email authentication service 
} else { 
    // email is invalid; It may be the username. 
    // use username authentication service 
}