Reputation: 36273
What is the best practice for user website/REST authentication in ZV MVC? How and where to put the code in the ZF framework? Can you provide me a code example?
I have a website and a REST server written in Zend Framework but no user session jet implemented.
THX!
Upvotes: 4
Views: 1928
Reputation: 70466
Authentication is setup in the _initAutoload
of the bootstrap file, e.g. like this:
if(Zend_Auth::getInstance()->hasIdentity()) {
Zend_Registry::set('role', Zend_Auth::getInstance()
->getStorage()->read()->role);
}else{
Zend_Registry::set('role', 'guests');
}
In case of a REST authentication you might need to authenticate by just passing the login parameters instead of logging in through a form.
So it might look like this in your AuthenticationController
:
private function getAuthAdapter() {
$authAdapter = new Zend_Auth_Adapter_DbTable(
Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users') // the db table where users are stored
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment('SHA1(CONCAT(?,salt))');
return $authAdapter;
}
public function logoutAction() {
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('index/index');
}
public function loginAction(){
if (Zend_Auth::getInstance()->hasIdentity()){
$this->_redirect('index/index');
}
if ($request->isPost()){
$username = $request->getPost('username');
$password = $request->getPost('password');
if ($username != "" && $password != "") {
$authAdapter = $this->getAuthAdapter ();
$authAdapter->setIdentity($username)
->setCredential($password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if($result->isValid()){
$identity = $authAdapter->getResultRowObject();
$authStorage = $auth->getStorage();
$authStorage->write($identity);
$this->_redirect ( 'index/index' );
}
}
}
}
If you need more help on zend_auth
and zend_acl
you might have a look at this how to.
Upvotes: 1