Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
class Model_User extends Skaya_Model_Abstract implements Zend_Auth_Adapter_Interface {
const USER_STATE_ACTIVE = 'active';
const USER_STATE_DEACTIVE = 'deactive';
const USER_ROLE_GUEST = 'guest';
const USER_ROLE_USER = 'user';
const USER_ROLE_ADMIN = 'admin';
public function getRole() {
if (empty($this->_data['role'])) {
$this->_data['role'] = self::USER_ROLE_GUEST;
}
return $this->_data['role'];
}
public function authenticate() {
/**
* @var Model_User $user
*/
$user = $this->getMapper()->getUserByEmail($this->email);
if (is_array($user) &&
!empty($user) &&
!empty($this->email) && $user['email'] == $this->email &&
$user['password'] == md5($this->password) &&
$user['status'] == self::USER_STATE_ACTIVE
) {
if (empty($user['role'])) {
$user['role'] = self::USER_ROLE_USER;
}
$this->populate($user);
unset($this->password);
$result = new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this);
}
else {
$code = Zend_Auth_Result::FAILURE;
if (!is_array($user) ||
empty($user) ||
$user['username'] != $this->email
) {
$code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
}
elseif ($user['password'] != $this->password) {
$code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
}
$result = new Zend_Auth_Result($code, null, array('loginFailed' => 'Incorrect Email & Password'));
}
return $result;
}
}
class Admin_UsersController extends Zend_Controller_Action {
/**
* @var Model_User
*/
protected $_user;
public function loginAction() {
$request = $this->getRequest();
$loginForm = new Admin_Form_Login(array(
'name' => 'loginForm',
'action' => $this->_helper->url('login')
));
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
$user = Service_User::create(array(
'email' => $loginForm->email->getValue(),
'password' => $loginForm->password->getValue()
));
$auth = Zend_Auth::getInstance();
$authResult = $auth->authenticate($user);
if ($authResult->isValid()) {
$user->lastLoginDate = time();
$user->save();
}
}
}
$this->view->loginForm = $loginForm->prepareDecorators();
}
public function logoutAction() {
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('/admin');
}
}
$auth->getIdentity(), там есть дополнительноя проверка на пустоту хранилища, не нужно самому вызывать hasIdentity(). Имхо, плохой тон работать напрямую с хранилищем Zend_Auth и хранить там что-то помимо ID, максимум — модель типа User иначе потом сам замахаешься выбгербать оттуда кучу данных непонятной структуры.$this->getRequest()->getParams(), перед этим проверив какого типа запрос: $this->getRequest()->isPost(), тогда мы можем определить открыта страница GETом или пришла форма POSTом. public function getRequest()
{
return $this->_request;
}
Практикум Zend Framework. Часть первая: Аутентификация и Acl