tags:

views:

34

answers:

3

I want to be able to show or hide certain elements in a view based on ACL. For instance, if a user is looking at my Users/index view, I don't want to show a 'Delete User' element if he doesn't have permission to delete users. If he does have permission to edit users, I do want to show a 'Edit User' link.

I can hack this together, but being very new to Cake I'm hoping that there is an elegant solution. The best I've done involves keeping logic in two places, so it's hell to maintain.

Thanks!

+1  A: 

There is no generic "elegant solution" :) I've always wanted to make such thing as well. Anyway how you could do it:

Overwrite the Html Helper in your app directory - make a copy from /cake/libs/views/helpers/html.php to /app/views/helpers/html.php and made some changes in the Html::link function.

For example you can check if the url contain action edit or delete.

The other part is to pass the proper parameters from the controller. In AppController::beforeFilter you can read the rights of the user (it's better to be cached) and to pass it in a special Auth variable to the View.

So when you have the rights in your View it's easy to modify the link. :)

As I said I haven't did it in real example, but this is the way I would do it.

There is 1 bad point in that - if the original Html helper is changed, your one will remain the same. But I believe that Html helper is mature enough so for me is not a big issue.

Nik
A: 

I do it like this in app_controller.php, although you could just as well do it in specific controllers. The view variables $usersIndexAllowed and $configureAllowed are then used in conditional statements in the view.

function beforeRender()
{
    if($this->layout=='admin')
    {
        $usersIndexAllowed = $this->Acl->check($user,"users/index");
        $configureAllowed = $this->Acl->check($user,"siteAdmins/configure");
    }
    $this->set(compact('usersIndexAllowed','configureAllowed'));
}
Leo
A: 

In case you don't want to mess around with overriding core helpers and you want a more automatic way of checking (without hard-coding user group names and users or setting separate link-specific variables) here's my suggestion:

Store all user permissions as session vars when the user logs in (clear on logout) and create a permissions helper to check if logged on user has permissions for a specific action.

code and example here

hope that helps

Thanos