Joel Vardy

Permission Based Authentication Library

Posted: 27 September 2013

I can't count the number of authentication libraries I have written since I started building websites, often I would simply iterate on the previous library each time I wrote one.

Last year, while I was working on several CodeIgniter projects I wrote (and released) an authentication library. This served it's purpose however it did not have any permissions, and of course, was limited to being used within CodeIgniter projects. I needed an authentication library in a current project, so decided to write a new authentication library which I've released as a Composer package. In this post I'm going to explain how the permission control works.

Previously

Most of my previous authentication libraries had rudimentary access controls, for example:

if ($user->is_admin() || $user->is_mod() || $user->is_super_admin()) {
    // This user can moderate comments
}

if ($user_level == 1 || $user_level == 2 || $user_level == 0) {
    // This user can moderate comments
}

Both of these examples will soon result in code which is hard to maintain. It is also easy to accidentally grant permission to the wrong type of user.

Much Better

Before I started writing the library I wrote the code below:

if ($auth->permission('moderate-comments')) {
    // This user can moderate comments
}

As you can see this code is quiet succinct, the rule doesn't need changing if a new type of user is added, and it is self-descriptive.

The Tables

Like most developers, as soon as I had written the three lines above, I was already thinking about the database schema. There are three tables, which are described below:

Database Connection

I have wanted to write a Composer authentication package ever since I saw the light (realised how amazing Composer was) - the problem, not everyone connects to their database in the same way. I thought long and hard about how to accommodate everyone.

In the end I decided to just make it work for me, and get a version out there, because I can always refactor the library so it uses the Doctrine DBAL at a later point.

You can view the authentication library Packagist.org.

In case you are interested here is a link to the CodeIgniter authentication library I wrote.