开发者

Authorization in Zend FW

I want to make authorization in my ZF-based application. In Kohana I could make something like

public $auth;
public $user;
public fun开发者_开发技巧ction before()
{
    parent::before();

    $this->auth = Auth::instance();
    $this->user = $this->auth->get_user();
    // $this->user is object if user was logged in or FALSE if not
}

in my abstract controller.

How to make the same in Zend? I've read about plugins and think it's what I need but didnt found any information where to save plugin-classes files and where should I enable them?


You can also do something similar in ZF to what you did in Kohana. I personally have never used Kohana, but I thing that ZF's version of your example would be similar to that:

// assuming IndexController
class IndexController extends Zend_Controller_Action {

    protected $_auth;
    protected $_user;

    // you could also use init() here.
    public function preDispatch() {
        $this->_auth = Zend_Auth::getInstance();
        $this->_user = $this->_auth->getIdentity(); 
    }
}

If you would like to have it in an abstract controller, then you could just create one (e.g. My_Controller_Action) that extends Zend_Controller_Action. Having this, IndexController would just extend your abstract controller rather than Zend_Controller_Action.


Hey! It's really simple, too. But if you want to get the authorization or process a new one? What ever, here comes both ones. First processing the authorization with credentials in a database table:

$db   = $this->getInvokeArg('bootstrap')->db;
$auth = Zend_Auth::getInstance();

$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('authLogin')
    ->setIdentityColumn('username')
    ->setCredentialColumn('password')
    ->setIdentity($username)
    ->setCredential($password);

$result = $auth->authenticate($authAdapter);

if ($result->isValid()) {
    // Yeah, logged in. Do some stuff here...
}

And here comes the check, if the user is currently logged in:

$auth = Zend_Auth::getInstance();

if ($auth->hasIdentity()) {
    // User is logged in. Retrieve its identity
    $username = $auth->getIdentity();
}

Hope this helps...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜