Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Application_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
- const UNAUTHORIZED_ACCESS = 'UNAUTHORIZED_ACCESS';
- // at first i tried routeStartup by that will mean controller and actions will be unknown
- function preDispatch(Zend_Controller_Request_Abstract $req) {
- // get role from Zend_Auth, if not logged in, use 'guest'
- $auth = Zend_Auth::getInstance();
- if ($auth->hasIdentity()) {
- $role = $auth->getIdentity();
- } else {
- $role = 'guest';
- }
- // get ACL
- $acl = Zend_Registry::get('aclWrapper');
- // set resource & privilege based on controller & action
- $resource = $req->getControllerName();
- $privilege = $req->getActionName();
- // "plugin": modify resource if is isset
- $id = $req->getParam('id');
- if (!empty($id)) {
- $em = Zend_Registry::get('em');
- switch ($resource) {
- case 'posts':
- $post = $em->getRepository('Application\\Models\\Post')
- ->findOneById($id);
- if (!empty($post)) {
- $resource = $post;
- }
- break;
- case 'users':
- $user = $em->getRepository('Application\\Models\\User')
- ->findOneById($id);
- if (!empty($user)) {
- $resource = $user;
- }
- break;
- }
- }
- if (!$acl->isAllowed($role, $resource, $privilege)) {
- $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
- if (!$auth->hasIdentity()) {
- // login required
- $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
- $flashMessenger->addMessage('You need to login first');
- $redirector->gotoSimple('login', 'auth', 'default', array(
- 'returnUrl' => urlencode($req->getRequestUri())
- ));
- } else {
- // not enough privilege
- $error = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
- $error->type = self::UNAUTHORIZED_ACCESS;
- $error->request = clone $req;
- $error->exception = new Zend_Acl_Exception('Access Denied', 403);
- $req->setControllerName('error')
- ->setActionName('error')
- ->setParams(array(
- 'error_handler' => $error,
- 'returnUrl' => urlencode($req->getRequestUri())
- ))
- ->setDispatched(false);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment