CakePHP Auth Component - Users, Groups & Permissions - Part II

Published: on 2/6/08 | Comments (0)

In my first article in this series, I outlined a flexible and powerfull way of implementing a complete User Authentication and Authorization system, which:

In this article I am going to expand on the system and show how you can use the code to get a basic but flexible Admin menu with minimum effort.

Listing all controllers within your application

Those of you paying close attention may have noticed the line:

    var $admin = array(); 

line in app/app_controller.php, along with the following beforeRender function:

    function beforeRender(){
        //If we have an authorised user logged in then set up the admin element
        if($this->Auth->user()){
            $controllerList = Configure::listObjects('controller');
            foreach($controllerList as $controllerItem){
                if($controllerItem <> 'App'){
                    if($this->__permitted($controllerItem,'index')){
                        $this->admin[] = $controllerItem;
                    }
                }
            }
        }
        $this->set('admin',$this->admin);
    }

Basically, if an Authenticated user is logged in to the system, then this function sends over an array of controllers to which the current user has permission to access the index action.

Now combine this with the following element: app/views/elements/admin.ctp

<?php
if(!count($admin)==0){
    echo '<h2>Site Management<h2>';
    echo '<ul>';
    foreach($admin as $link){
        if($link <> 'Pages'){
            echo '<li>'.$html->link($link,'/'.$link).'</li>';
        }
    }
    echo '<li>'.$html->link('Log Out',array('controller'=>'users','action'=>'logout')).'</li>';
    echo '</ul>';
}
?>

Add the line:

<?php echo $this->element('admin');?>

Into your site's layout file and you have an instant Admin menu linking to the index action of every controller that the user has access to.

That's it for this time, in the next article in this series, I will show you how to use the system to create a funky looking admin toolbar, so make sure you subscribe to the site's feed.

Till next time, Happy Baking.

This post is now closed to new comments