Search code examples
phpaclbefore-filter

cancel request in beforefilter() in PHP


I'm using CakePHP , CAS for Authentication and ACL for Authorization. If the user donot have permission to view the page, i need to flash a message stating Not permitted OR redirect to another page.

Ex: If the user is viewing /users/view/1 .Now the user requests /users/delete/1. The user donot have permission to delete. So I want to display a flash message on the page he requested from (/users/view/1).

In my app_controller, i have the following function:

function beforeFilter() {
  $this->__initPhpCas();
  if (isset($_SESSION['loggedIn'])){
    if(!$this->Acl->check(.....){
        //User do not have permission to view the page.
        // Need to cancel this request and flash a message 
   }
  }

Any suggestions are appreciated

Final answer is

function beforeFilter() {
      $this->__initPhpCas();
      if (isset($_SESSION['loggedIn'])){
        if(!$this->Acl->check(.....){
            //User do not have permission to view the page.
            // Need to cancel this request and flash a message 
            $this->Session->setFlash(__('You are not authorized to view this page.', true));
        $this->redirect($_SERVER['HTTP_REFERER']);
       }
      }

Solution

  • to redirect use $this->redirect(); and add a message by using $this->Session->setFlash();. I have included links to show you.

    EDIT:

    I would recommend setting the flash message then doing the redirect. Then on the redirected page, display the flash message with $session->flash();.

    EDIT2:

    Since you are not wanting to do a redirect you will need to do something like this.

    function view() {
        if($this->Acl->check(.....){
            //display the page and continue with the view action
        }
        else {
            $this->Session->setFlash("You do not have access to use this feature");
        }
    }
    

    EDIT 3:

    Try this. Take a look at the last post in the link.

    Edit 4: Try using deny()

    Edit 5:

    If I understand you correctly you want to use beforeFilter to check if they have access and if not then don't continue running the actions. CakePHP doesn't really allow this but a work around is.

    function beforeFilter() {
        if($this->Acl->check(.....){
            //display the page and continue with the view action
        }
        else {
            $this->Session->setFlash("You do not have access to use this feature");
            $this->params['action'] = "failedCheck";
        }
    }
    
    function failedCheck() {
        //blah blah blah
    }