7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. PHP

How to Use CakePHP's Access Control Lists

Scroll to top
Read Time: 17 mins

If you're building a CMS, you'll probably need different user roles—superusers, admins, users—with different permission levels. Too complicated to code? Enter CakePHP's ACL (Access Control Lists). With the right setup, you'll be checking user permissions with just one line.

Introduction: What Are Access Control Lists?

The ACL lets you create a hierarchy of users with their respective roles. Here's a quick example.

  • Super Users
    • User #1
  • Admins
    • User #2
    • User #3
  • Users
    • User #4
    • User #5
    • User #6
    • ....

In this tutorial, we will be setting up an ACL for a simple blog. If you haven't yet checked out Getting Started With CakePHP (and Part 2) here on Nettuts+, please do so and then return, as we will be taking for granted the framework basics.

With this hierarchy, we can assign several permissions for each role:

  • The Super Users can create, read, update and delete Posts and Users.
  • The Admins can create, read, update and delete Posts.
  • The Users can create and read Posts.
  • Everyone else can just read Posts.

Each permission will be given to the group, not to the user; so if user #6 is promoted to Admin, he will be checked against the group permission --not his. These roles and child nodes (users) are called Access Requests Objects, or AROs.

Now, on the other side, we have the Access Control Objects, or ACOs. These are the objects to be controlled. Above I mentioned Posts and Users. Normally, these objects are directly linked with the models, so if we have a Post model, we will need an ACO for this model.

Each ACO has four basic permissions: create, read, update and delete. You can remember them with the keyword CRUD. There's a fifth permission, the asterisk, that is a shortcut for full access.

We will be using just two ACOs for this tutorial: Post and User, but you can create as many as you need.

The ACL Tables

Let's proceed to create the database tables. You can find this code in db_acl.sql inside your app's config/sql directory.

We can begin now creating ARO and ACO nodes, but hey, we don't have users! We'll have to create a basic authentication system.

Step 1: A Basic Authentication System

As this tutorial is intended for CakePHP developers with a basic to moderate knowledge of the framework, I will be supplying the code and a brief explanation. However, the authentication system is not the goal of this tutorial.

The MySQL table:

The User model (models/user.php)

The Users controller (controllers/users_controller.php)

Since we have new elements, let's review them. First, we are setting a $components variable. This variable includes all the components in the array. We will be needing the Auth component, which is a core component, as are HTML and Form helpers, but since it isn't included by default by Cake, we will have to include it manually.

The Auth component handles some basic authentication mechanics: it helps us to login a user and it handles an authenticated user's session for us, as well as handling the log out and basic authorization for guests. Also, it hashes the password automatically. I'll be explaining how to call each function in the following paragraphs.

Next, we are creating a function called beforeFilter. This is a callback function and it lets us set some actions before all the controller logic is processed. The Auth component requires us to specify a model to be used, in this case the User. Then, by default, it will deny all the access to users not logged in. We'll have to overwrite this behaviour with allow() which requires one parameter. That parameter can be an asterisk, specifying that all methods inside said controller can be accessed by unauthenticated users. Or, it can be passed an array with the functions that can be accessed by unauthenticated users. In this case, since we have just three functions, the following lines are the same thing.

For the login() function, the Auth component will handle all the login mechanics for us. We will just have to supply the function with an array with two keys: the username and the password. These keys can be changed, but by default, both username and password fields will be matched against the database and will return true if the user has been authenticated.

Finally, the controller's login function will try to match a username/password combination against the database.

Please note that this code is very basic. You'll need to validate the username characters, if the username exists, the minimum length for the password, and so on.

The Register view (views/users/register.ctp)

The Login view (views/users/login.ctp)

Open /users/register in your web browser and register a new account. I suggest admin as username and 123 as password and if your session expires just go to /users/login and enter the correct username/password combination you just created.

Step 2: Denying Access To Unauthenticated Users

We're not even working with ACL, but we already can deny posting, editing and deleting posts. Open your Posts controller and add the Auth component.

Now go to /posts in your web browser. If you're logged in, you should see the posts, but if you're not, you will be redirected to /users/login. By simply including the Auth component, all the actions are by default, denied for guests. We need to deny three actions for unauthorized users: create, edit and delete. In other terms, we'll have to allow index and view.

Go to edit or create a post; if you're not logged in, you should be redirected to /users/login. Everything seems to be working quite good, but what about the views? The edit and delete links are being shown to everybody. We should make a conditional.

But before going into that, let's see how Auth's user() function works. Copy and paste these lines into the index function.

Open your /posts in your browser and, if logged in, the pr() will throw something like this.

The user() function returns an array just as a model would do. If we had more than three fields (password is not included), they will be shown in the array. If you're not logged in, the array will be empty, so you can know a user is logged in if Auth's user() array is not empty.

Now, Auth is a component, meant to be used in a controller. We need to know from a view if a user is logged in, preferably via a helper. How can we use a component inside a helper? CakePHP is so awesome and flexible that it is possible.

Save this snippet in views/helpers as access.php. Now let's see the code, line by line. First, we are setting up a $helpers var. Helpers can include other helpers, just like $components can. The Session component is required for the Auth component, but we have no access to this component inside a helper. Fortunately we have a Session helper, that will help us.

Next, we create a function and use App::import which will let us import an element that normally we wouldn't have access to. The next line creates the Auth component in a $auth variable, and now a little dirty hack; since the Auth component reads the session to know if we are logged or not, it requires the Session component, but as we are importing it from a place it shouldn't belong to, we'll have to give it a new Session object. Finally, we are using user() and setting it to $user and returning true if the variable is not empty, otherwise false.

Let's get back to the posts controller and proceed to add the helper.

The access helper is now accessible from the view. Open index.ctp in views/posts and replace this line.

With this one.

Go back to your web browser, reload the index page and if you're logged in, you'll see the edit and delete links for each post. Otherwise, you'll see nothing.

While this would be enough if you have an app with one or two users, it is not enough if you have registrations open.

Step 3: Installing ACL

Open the Users controller and add the ACL component.

Next, let's create a function to install the ACOs and AROs nodes.

By importing the ACL component, we can access the ACOs and AROs model. We begin by creating an ARO, which is the requester for the objects; in other words, who will be accessing the objects. That would be the user (hence the User string in model). We are creating different roles; Super, Admin, User and Suspended.

Next, we do the same with ACOs, since we just have two objects to manage (Posts and Users), we'll create two, one for each.

Now, a quick note. The array that we are saving for both ACOs and AROs have four fields: the model name, foreign key (which is useful if you want to give access to one ARO, like a post he created), parent id (which will be used later and is the basic parent-child nodes relationship; we will be creating users below these roles), and the alias (which is a quick form to find the objects).

Finally, we are using ACL's allow() function. The first parameter is the ACO alias; second, the ARO alias, and third, the permissions given to said ARO. A Superuser has full access to the Post and User models, an Admin has full access to the Post model, and a User can just create posts.

At the function's beginning, I declared a conditional to check if the Admin role exists in ACOs. You don't want to install the same thing more than once, do you? It would mess up the database quite badly.

Open /users/install in your web browser, and, since we don't have a view, CakePHP will throw an error, but just check the MySQL dump. All the relationships have been successfully created, it's time to work with the child nodes.

Setting users to roles

Let's clean the users table. Open phpMyAdmin, select your database, the users table and click empty. We'll get back to the register() function on the Users Controller. Just below this line:

Paste this code:

In the first line we create a new ARO object. Then we'll get the parent node in which the user will be created. If there's a record in the database, we'll set it to the User ARO, else, the first user should be the Super.

Then we'll save a new ARO; the model is the one we are working currently on, User, the foreign_key is the last record's id we just created. The parent_id is the node we began with; we'll just pass it the id and finally the alias. It is a good idea to call it Model_name, then a separator ::, and then the identifier. It will be much easier to find it.

Now we're done. Create four users: superuser, adminuser, normaluser and suspendeduser. I suggest the same username and password for testing purposes. Don't forget that, until this point, only the superuser has a role of Super; all the remaining will be Users!

Step 4: Reading Permissions

Because ACL is a component, it is accessible only within the controller. Later, it will be also in the view; but first things first. Include the ACL component in the Posts controller, as we did in the Users controller. Now you can begin checking permissions. Let's go to the edit function and do a quick test. In the first line of said method, add this.

ACL's check() function needs three parameters: the ARO, the ACO and the action. Go and edit a post, and, if you're not logged in as the super user, the script will die. Go to /users/login and access as the Super user and go back to editing. You should be able to edit the post. Check below the MySQL dump to see the magic. Four database queries: that sure isn't scalable.

We have two issues. First, two lines for the permissions check. Second, the ACLs aren't being cached. And don't forget all the logged users can see the edit link, even if just the Super user can use it.

Let's create a new component. Let's call it Access.

Save it in controllers/components as access.php. The class's $user var will be initiated as the component is loaded, and startup() is a callback function, so it's now set in the class. Now let's create our check() function.

Our check() method will need just two parameters: the ACO and the action (which is optional). The ARO will be the current user for each session. The action parameter will default to *, which is full access for the ARO. The function begins by checking if the $this->user is not empty (which really tells us if a user is logged in) and then we go to ACL. We have already covered this.

We can now include the Access component in our Posts controller and check the permissions with just one line.

The same result is achieved with less code, but the error message is ugly. You'd better replace the die() with the CakePHP error handler:

Permissions in views

This might be ugly, but it works. We'll have to create a helper that loads a component with a custom method for use in the helper.

Add this function in the Access component (controllers/components/access.php).

Now,let's rewrite the access helper (views/helpers/access.php).

The beforeRender() method is a callback, similar to the component's startup(). We are loading two components and since these will be used in most functions, it's a good idea to start all at once, than to manually start them each time the method is called.

Now on your index.ctp view in views/posts you can replace this line.

With this one.

Just don't forget to check permissions, both in the views and the controllers!

User data

You can access the user data for a logged user with the user() method in the Auth component. Then you can access the array and get the info you want. But there must be a better way. Let's add the following function in the Access component.

This is quite useful when you need to save a Post with a user_id relationship.

And in the view, we can do something similar with the helper.

In your template file you can do something like below to greet a user by his username.

Step 5: Modifying Permissions

Let's say we need to switch roles for the user #4: he needs to be a Super User. So, User's id is 4 and Aro's id is 1.

Now we need to find the User's Aro in order to modify its parent Aro.

Finally, if the $aro_user variable is not empty, let's update the Aro.parent_id field.

Please note that you have to validate both the user's id and the new aro's id. If one of these do not exist, it will create a mess in your ACL tables.

Step 6: Optimization

Although the component we just created are both simple and useful, the database is queried with each and every check. It is not ready for production yet. First, the database should be queried as little as possible. To optimize this, we should take advantage of CakePHP's Cache.

Using Cache will reduce the load quite a bit, but if we have ten posts showing up in the index, and, for each one, we are checking if the user has update permissions for the Post Aco, the framework will be reading and parsing a file to return the same result...ten times for each page load.

That's the second point: a variable inside the class and some conditionals will make the work lighter, so that a repeated request will be checking against Cache just once.

Both these changes are reflected in access_cache.php, inside the controllers/components directory. So make sure you download the source!


Access Control Lists are a basic features that most apps need. CakePHP has a nice implementation, but lacks in both good documentation and examples. I hope that, with this tutorial, these two issues will now be covered. Thanks for reading!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.