我有一个User表,其中存储了userID,用户名和密码,还有一个包含用户角色的Role表。为了链接这两个表,我有一个表(user_role),其中包含userID和roleID。如何使用Zend Auth对用户进行身份验证并使用Zend Acl来控制用户访问。 This is the database design
答案 0 :(得分:0)
您可以创建一个适用于您的应用程序所具有的任何结构的Zend_Auth适配器。
以下是使用我的实体模型和映射器提供身份验证和用户数据进行身份验证的Auth适配器示例。
<?php
/**
* Description of Auth_Adapter
*
*/
class Auth_Adapter implements Zend_Auth_Adapter_Interface
{
/**
* The username
*
* @var string
*/
protected $identity = null;
/**
* The password
*
* @var string
*/
protected $credential = null;
/**
* Users database object
*
* @var Model_Mapper_Abstract
*/
protected $usersMapper = null;
/**
* @param string $username
* @param string $password
* @param Model_Mapper_Abstract $userMapper
*/
public function __construct($username, $password, Model_Mapper_Abstract $userMapper = null)
{
if (!is_null($userMapper)) {
$this->setMapper($userMapper);
} else {
$this->usersMapper = new Application_Model_Mapper_User();
}
$this->setIdentity($username);
$this->setCredential($password);
}
/**
* @return \Zend_Auth_Result
*/
public function authenticate()
{
// Fetch user information according to username
$user = $this->getUserObject();
if (is_null($user)) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
$this->getIdentity(),
array('Invalid username')
);
}
// check whether or not the hash matches using my own password class
$check = Password::comparePassword($this->getCredential(), $user->password);
if (!$check) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
$this->getIdentity(),
array('Incorrect password')
);
}
// Success!
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$this->getIdentity(),
array()
);
}
/**
* @param type $userName
* @return \Auth_Adapter
*/
public function setIdentity($userName)
{
$this->identity = $userName;
return $this;
}
/**
* @param type $password
* @return \Auth_Adapter
*/
public function setCredential($password)
{
$this->credential = $password;
return $this;
}
/**
* @param type $mapper
* @return \Auth_Adapter
*/
public function setMapper($mapper)
{
$this->usersMapper = $mapper;
return $this;
}
/**
* @return object
*/
private function getUserObject()
{
return $this->getMapper()->findOneByColumn('name', $this->getIdentity());
}
/**
* @return object
*/
public function getUser()
{
$object = $this->getUserObject();
$array = array(
'id' => $object->id,
'name' => $object->name,
'role' => $object->role
);
return (object) $array;
}
/**
* @return string
*/
public function getIdentity()
{
return $this->identity;
}
/**
* @return string
*/
public function getCredential()
{
return $this->credential;
}
/**
* @return object Model_Mapper_Abstract
*/
public function getMapper()
{
return $this->usersMapper;
}
}
您还可以扩展任何当前适配器以提供所需的功能。
祝你好运!