Zend framework - tutorial: authorization
I would like to facilitate this first stage for those who are still only at the beginning of the journey.
For authorization, we will of course need a ready-made user table - at least two fields, userName and passwordMD5.
passwordMD5 - it’s immediately clear that it stores the password implicitly so that someone would not steal it at one time.
1. Make the login form.
class Form_Login extends Zend_Form
{
public function init()
{
// метод пост
$this->setMethod('post');
$this->addElement('text', 'userName', array(
'label' => 'Имя Пользователя:',
'filters' => array('StringTrim')
));
$el = $this->getElement('userName');
$el->setRequired(true)
->addValidators(array(
array('NotEmpty', true, array('messages' => array(
'isEmpty' => 'имя пользователя обязательный пункт!',
)))));
$this->addElement('password', 'password', array(
'label' => 'Пароль:'
));
$el = $this->getElement('password');
$el->setRequired(true)->addValidators(array(
array('NotEmpty', true, array('messages' => array(
'isEmpty' => 'пароль не может быть пустым!',
)))));
$this->addElement('submit', 'login', array(
'label' => 'логин'
));
}
}
* This source code was highlighted with Source Code Highlighter.We put this class in / application / forms (or whatever you like)
2. The controller for the login.
class LoginController extends Zend_Controller_Action
{
public function preDispatch()
{
if (Zend_Auth::getInstance()->hasIdentity()) {
return $this->_redirect('/');//вдруг уже залогинен, перенаправляем на главную
}
}
public function indexAction()
{
$form = $this->_getLoginForm();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
$auth = Zend_Auth::getInstance();
$authAdapter = $this->_getAuthAdapter($formData['userName'],$formData['password']);
$result = $auth->authenticate($authAdapter);
if (!$result->isValid()) {
// все неправильно
$form->setDescription('Неправильные имя или пароль');
$form->populate($formData);
$this->view->form = $form;
return $this->render('index'); // перерисуем форму
}else{
$currentUser = $authAdapter->getResultRowObject();
Zend_Auth::getInstance()->getStorage()->write( $currentUser);//записали юзера в auth, теперь он везде доступен - только для чтения
return $this->_redirect('/');//залогинился,редирект на главную
}
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
}
protected function _getLoginForm()
{
require_once APPLICATION_PATH . '/forms/Login.php';
return new Form_Login();
}
protected function _getAuthAdapter($userName, $userPassword)
{
$authAdapter = new Zend_Auth_Adapter_DbTable(
$registry->dbAdapter,
'user',
'username',
'passwordMD5',
'MD5(?) AND status = "OK"'
);
$authAdapter->setIdentity($userName)->setCredential($userPassword);
return $authAdapter;
}
}
?>
* This source code was highlighted with Source Code Highlighter.Registry :: getInstance () -> session - create a session in bootstrap.php and gently pop it into our registry object.
$configuration = new Zend_Config(require APPLICATION_PATH . '/config/config.php');
$dbAdapter = Zend_Db::factory($configuration->database);
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
$registry = Zend_Registry::getInstance();
$registry->configuration = $configuration;
$registry->dbAdapter = $dbAdapter;
$registry->session = new Zend_Session_Namespace();
* This source code was highlighted with Source Code Highlighter.I think there is nothing to chew here, everything is clear. I think there are other ways of authorization, but this one suits me completely.
Remember me?
In order for your user to remember the system, you just need to add an element on the form (you know which one) and if our user logs in to call this code:
Zend_Session::rememberMe(1209600);// here everyone decides for himself how much is needed After the login, the user object can be accessed anywhere code this way:
$auth = Zend_Auth::getInstance()->getIdentity();But here it is - when you try to change some property of this object and save it immediately get such an error -
Cannot save a Row unless it is connected
It turns out we recorded the object in the session, and after that it's just an object and a connection with the base he has lost.
For this, I made a very simple solution.
Create a plugin class:
class CheckLoginPlugin extends Zend_Controller_Plugin_Abstract
{
protected $_userModel;
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request){
$auth = Zend_Auth::getInstance();
$user = $auth->getIdentity();
$model = $this->_getUserModel();
$auth->getStorage()->write($model->getUserById($user->id));
}
public function _getUserModel(){
if (null === $this->_userModel) {
require_once APPLICATION_PATH . '/models/User.php';
$this->_userModel = new Model_User();
}
return $this->_userModel;
}
}
?>
* This source code was highlighted with Source Code Highlighter.We connect the plugin in bootstrap.php
require_once 'My/Plugin/CheckLoginPlugin.php';
$frontController->registerPlugin(new CheckLoginPlugin());
* This source code was highlighted with Source Code Highlighter.This plugin simply updates the object from the database every time the page is called. Of course, you can do this only if necessary, as someone saves, I have enough matches :)
PS - the example, of course, may contain some errors (logics), take it as a pseudo-code, but with minimal knowledge in the PCP I think it will be easy to fix.
You can also make authorization for zend programs using OpenID