Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying view based on ACL in CakePHP

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!

like image 373
Jay Avatar asked Jul 19 '10 02:07

Jay


2 Answers

I know this is an old question now but for anyone looking for a way like I was...

In AppController::beforeFilter you can assign the ACL component to a view variable and then use it in your view:

$this->set('user', $this->Auth->user());    
$this->set('acl', $this->Acl);

And then in you view just juse it like thie:

if($acl->check(array('User' => $user), 'controllers/groupd/admin_delete')) {

This is't necessarily the most correct way to do it but it does work nicely

like image 55
Andy Hobbs Avatar answered Oct 10 '22 15:10

Andy Hobbs


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.

like image 43
Nik Chankov Avatar answered Oct 10 '22 13:10

Nik Chankov