1
votes

I am using the Auth component and ACL to give permission to roles and redirect them to /login if they don't have the proper rights.

That works fine for all existing controller/action. But when ever I enter a none existing controller action http://www.mypage.de/fake/bla I get a notFoundExeption.

My issue with that is, that the user sees my admin layout, because the 404 is rendered within the admin layout template.

Is there a way to say that admin (or any prefix) is always restricted and users that are not logged in get redirected to the login page?

What I came up with is this, but I don't like it, because I would have to do the same for all other prefixes.

/**
 * AppController::afterFilter()
 *
 * @return void
 */
function afterFilter() {
    if ($this->response->statusCode() === 404 && !empty($this->request->params['admin'])) {
        $url = Router::url(
            array(
                'admin' => false,
                'plugin' => false,
                'controller' => 'users',
                'action' => 'login'
            )
        );
        $this->Common->flashMessage(__('You are not authorized to access that location.'), 'error');
        return $this->redirect($url);
    }
}
1

1 Answers

1
votes

Your code actually does the trick pretty well, but there is no way to automatically do this for every prefix, except maybe doing it in a foreach loop:

function afterFilter() {
    if($this->response->statusCode() === 404) {
        foreach(array('admin', 'otherprefix') as $prefix) {
            if(!empty($this->request->params[$prefix])) {
                [...]
            }
        }
    }
}

If you want to treat all 404 errors the same – regardless of the possible prefixes – you could just change the layout for your 404 error:

function afterFilter() {
    if($this->response->statusCode() === 404) {
        $this->layout = 'default';
    }
}

This way, no one would see the admin layout on any 404 page.