Zend 2 Authentication : Manage 2 Identities
我正在使用zend 2身份验证。现在,存在一种情况,用户可以使用用户名和密码或电子邮件和密码登录。是否可以在zend 2中同时提供用户名和电子邮件作为身份。否则,我该如何处理这种情况?
这是我当前的工作代码。这里使用电子邮件作为身份,使用密码作为凭据。
在Module.php
中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; }, ) ); } |
和控制器中的
1 2 3 4 5 6 7 8 9 10 11 | $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 } |
有什么想法吗?谢谢。
如果您使用的是Zend \\\\\\\\ Authentication \\\\\\\\ Adapter \\\\\\\\ DbTable适配器,也许您可??以尝试这样的操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $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(); |
另一种方法是创建两个身份验证服务,一个用于电子邮件,另一个用于用户名。
当用户提交登录名时,请检查其是否为有效电子邮件。在这种情况下,请使用电子邮件身份验证服务。否则,请选择用户名身份验证服务。
您可以使用Zend电子邮件验证程序从Zend网站
中检查其是否为有效电子邮件
1 2 3 4 5 6 7 8 | $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 } |