Erkana: CodeIgniter Authorization Library

First of all, let me be blunt about this: this is my authorization library. Of course, I will be taking user suggestions and bug fixes into account but ultimately, if it doesn’t fit within the scope of my needs, it won’t make it into the library.

User Authentication is something that many CodeIgniter developers face every single day - there are tons of libraries out there to help in doing this as well. In my opinion though, most of them are to bloated for my use.

My goal with this library was to create a small set of methods and helpers that would prove useful for a variety of user authentication while not hijacking the framework and forcing you to adopt the practices that library dictates.

What I came up with is Erkana Auth - a library of 3 methods and a helper with 2 functions. Erkana Auth supports user login (maintaining this login via a Session), logout, and a basic role system. The role system is merely the definition of roles, the actual implementation of roles is still left up to you - the developer.

To use the library, after installation, include the following in your controller methods (or in the constructor). The helper will be loaded automatically:

$this->load->library('Erkanaauth');

The library only has one requirement - you have a table (users) with an id field. If you would like to use the role system, you’ll need a table (roles) with 2 fields (id and name). So, here’s a quick rundown of the library and it’s helper functions:

try_login($condition = array())
This method attempts to log the user in, using an array of conditions. Upon success it will store the user’s ID in a session variable.

I have found, a great way to use this method is within the callback of a login form. Here’s an example of that right here:

function login() {
  $this->load->library('validation');
  // Validation Rules and Fields
  if ($this->validation->run()) {
    redirect('admin/index');
  } else {
    $this->load->view('admin/login');
  }
}
 
function _check_login($username) {
  $this->load->helper('security');
  $password = dohash($this->input->post('password'));
  if ($this->erkanaauth->try_login('username'=>$username, 'password'=>$password)) {
    return TRUE;
  } else {
    $this->validation->set_message('_check_login', 'Incorrect login info.');
    return FALSE;
  }
}

The reason I opted for try_login to accept an array condition is that not everyone verifies their login’s by username/password. Who am I to tell you that you must accept a username and a password? What if you merely want to accept a password, or maybe email and password? It’s all possible with the try_login() method.

try_session_login()
This method will attempt to see if the user is currently logged in by checking if there is a session variable named user_id. If so, it will check to verify that is a valid user ID, and will return TRUE if both cases are met satisfactorily (otherwise, it will return FALSE).

This function is great for the pages within your admin area that are protected:

function index() {
  if (!$this->erkanaauth->try_session_login()) {
    redirect('admin/login');
  }
}

logout()
The simplest of all the methods - it merely logs the user out be setting their user ID session variable to FALSE. This method does not return anything (as the chance for failure is virtually impossible).

function logout() {
  $this->erkanaauth->logout();
  redirect('admin/login');
}

getField($field = ”)
This method is also a helper (therefore it can be used in either the controller or the view). It simply returns a field from the users table and is great for returning a username, date created, whether the user is active, etc. The example below is from a view file:

Welcome, <?= getField('username'); ?>!

getRole()
This method is also a helper (therefore it can be used in either the controller or the view). It returns the user’s role. A user’s role is defined as an integer within the role_id field of the users table, and corresponds to a name field (VARCHAR) within the roles table. The example below comes from a view:

<ul id="nav">
  <li><?= anchor('admin/pages', 'Pages'); ?></li>
  <? if (getRole() == 'admin') { ?>
    <li><?= anchor('admin/users', 'Users'); ?></li>
  <? } ?>
</ul>

More Info

This library has only been tested in PHP5, although I tried to make it backwards compatible. There may some instances where I messed up and I am more than welcome to accept corrections to make this library PHP4 compatible.

This library was tested on the SVN version of CodeIgniter but should work fine with the current release. You may also use any session library you please, although I only tested it with the session library that comes in the SVN (once again, the release version should work fine).

Also, this library was only tested on MySQL. For the most part it uses the Active Record class, but there is one query (it’s in the try_session_login() method) that uses a manually written query.

I am more than open to suggestions and if I feel they fit the scope of this library, I’d be more than happy to add that functionality. Right now, I fully intend to add in some password reminders and email activation.

Once again, this library requires a table named users with an ID field - any other information is yours to define (may I recommend a username, email, password, and created_on field)? If you would like to use the getRole() method/helper, you will need a table named roles with id and name fields (you can use the following SQL query):

CREATE TABLE `roles` (
  `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(10) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `name` (`name`)
);

Download

The library can be downloaded here and should be extracted into your \system\ directory within CodeIgniter. This archive contains the following:

\application\
  \libraries\
    Erkaanaauth.php
  \helpers\
    Erkanaauth_helper.php

Download Erkana Auth Library


Creative Commons License


ErkanaAuth is licensed under a
Creative Commons Attribution-Share Alike 3.0 United States License.

Comments

  1. Henrik says at 2007-10-25 02:10:

    Just something to point out: remember that MySQL usually does not care about case. So if you have a table like this:

    id, username, userpass

    and the following values

    1, henrik,secretpassword

    then loggin in with either ‘henrik’,'Henrik’ or ‘HeNRik’ as username and ’secretpassword’ as userpass will return a row, and let you in.

    So make sure to double-check your values, or create a users-table where MySQL searches are case-sensitive.

    Otherwise: great library mr Wales!

  2. Michael says at 2007-11-01 12:11:

    I love this library! It’s easy to use and has most of the functions I need. Just the email activation and password reset functions are missing. Hope they come soon…

  3. Steve Finkelstein says at 2007-11-11 12:11:

    Hi Michael,

    This is stevefink from the CodeIgniter forums. I just want to say looks like you did wonderful work with this authentication library. I’m excited to give it a try for my next CI project.

    Cheers!

    - sf

  4. Pavel A. Brilow says at 2007-11-12 12:11:

    Hello. Very nice library. I’m trying to use it in my project, and rewriting it not to use CI DB classes, and use PDO.

    In try_session_login method, you’ll better use “select count(id)…” nor “select count(*)”. It will work more faster, because it is not necessary to count all the fields. Details you can find in mysql and php manuals.

    Wish it will help you to improve your library.

  5. catcatcat says at 2007-11-20 14:11:

    hello, i’m currently trying it out, and I firstly thank you.
    A trivial problem, but, you can correct your example, about the try_login() function, the parameter is an array, so it’s better be:

    try_login(array('username'=>$username, 'password'=>$password))

    Cheers

  6. Lars S. Linnet says at 2007-11-22 01:11:

    Hey, Pavel A. Brilow, that really depends on which type of database you use, if you choose the default MyISAM, the count(*) is just as fast as count(id) because the way MySQL indexes the MyISAM database type. But on the other hand if you use the InnoDB using count(id) on an indexed where clause is the faster way.

  7. CodeIgniter PHP Authorization Libraries | David Bisset: Web Designer, Coder, Wordpress Guru says at 2007-11-25 00:11:

    […] using a year-old solution, but interested in other authorization libraries for CodeIgniter. Michael Wales seems to have created one, so bookmarking for future reference. Tags: CodeIgniter, […]

  8. Spaceout says at 2007-11-27 00:11:

    What is the advantage of using this over the excellent FreakAuth Light library for CI?

    I’ve been using FAL in many of my apps, and it works just fine.

    Not only that, it provides email verification, options for password reminders, etc.

    Just tweak a few views and its integrated into any CI app. I just integrated it yesterday on a new CI app I’m developing. It took all of 15 minutes to have it up and running. It provides a nice admin panel as well.

    I’m not discouraging your effort, but just curious to see why I would want to use this over something that seems to be proven and extremely feature rich.

  9. Michael Wales says at 2007-11-27 17:11:

    FAL is nice - but it’s not what I would call unobtrusive. FAL basically jumps in there, takes over, and does it what it wants - you must conform to FAL.

    ErkanaAuth, is a mindset, not really a library. There have already been numerous adaptations of ErkanaAuth posted for the public to use.

    ErkanaAuth’s primary feature: it’s lack of features. ErkanaAuth doesn’t force you to use username/password (hell, you could use an ID number to login if you wanted). It doesn’t force you to do anything really. It just helps you along the way - leading you in the right direction to achieving an authentication system.

  10. Dsyfa says at 2007-11-29 00:11:

    Hi,

    A small demo application covering at least login and logout would be helpful.

    Thanks

  11. Chris Newton says at 2007-12-19 21:12:

    Nice library. I’d love to see a lot more basic things like this for use in Codeigniter than full scale applications.

    Over the years I’ve cobbled together countless programs like Joomla, OSCommerce, Vbulletin, etc and I’ve found over and over again that what my clients want is only parts of those applications, they want everything integrated, and whatever is impossible to customize is exactly what their business requires me to customize.

    This is nice because it doesn’t require me to use any specific method for login, authorization, ACL, password storage, etc.

    Within a few hours I’ve already managed to build a better, more flexible, and straitforward login & registration system than I would have if I was using a bunch of the previously mentioned applications. In short, thanks!

  12. Alex Biddle says at 2007-12-22 13:12:

    Thanks for the code, using it in a project at the moment. One question, why Erkana?

  13. Michael Wales says at 2007-12-25 02:12:

    Erkana is a word I originally believed I had made up - I liked the sound of it, easy to say, and just has a nice ring to it. Personally, it makes me thing of peace, serenity, calm and soothing, etc. I’ve had this word, erkana in my head for about 2 years now.

    When thinking of a name for this library I decided to do some googling around for the term - just to make sure I wasn’t associating this library with something I’d rather not be associated with. I quickly learned that erkana is a Turkmen word meaning: free, unrestricted, easy.

    I can’t think of a better way to describe this library. :)

  14. Indranil says at 2007-12-27 04:12:

    Thanks very much for the code.
    Am using it in building my portfolio’s admin page, so that I don’t have to ftp changes everytime something gets updated. :P Great work. Made my work tons easier!

  15. PPiirto says at 2008-01-02 15:01:

    Thanks for the library! I’m using it in my current project.

    There’s minor problem with unix/linux systems: the helper file should be named erkanaauth_helper.php not Erkanaauth_helper.php. It can’t find the file.

  16. Fusspawn says at 2008-01-20 12:01:

    Nice Lib :D Using it in a project i am working on now,
    Thanks for your help

  17. Heuristic Blog » Blog Archive » Code Igniter Authentication with Erkana Auth says at 2008-02-01 13:02:

    […] are many Code Igniter authentication libraries, Michael Wales’s Erkana Auth differentiates itself by aiming to be a “small set of methods and helpers that would prove […]

  18. sigmaCMS: A Codeigniter based Content Management System — tomybeat.com says at 2008-03-01 20:03:

    […] management stuff. I’ve built the account registration from scratch. The cool thing about Erkana is it’s so light and flexible, I’m still left with a lot of freedom to implement the […]

  19. dimitrios mistriotis says at 2008-03-11 09:03:

    I was wondering for how long a user stays logged in. I programmed an application for testing some students where they should stay without doing anything for half an hour or so. So how can I keep them logged in?
    Thank you and great piece of code with smart ideas.

  20. Michael Wales says at 2008-03-11 22:03:

    @dimitrios
    The time a user is logged in is based off of the following setting within config.php:
    $config['sess_expiration'] = 0;

    0, in this case, means they will stay logged in until the browser window is closed.

  21. dimitrios mistriotis says at 2008-03-18 03:03:

    Yes and it is not Erkana-specific. I found it later on, thnak you for the response.

  22. louis w says at 2008-03-23 19:03:

    Hi, I am reviewing your project. It looks very cool.

    Wondering a couple things. Why not set the table name and id column name either in an external config or even as a variable name at the top of the class. That way its easier for devs to make it work with existing app.

    Also in looking at the try_session_login method, I am wondering if authenticating against a userid (simple integer) stored in the session is enough? Seems like this would be easy to forge.

  23. Jonathon Hill says at 2008-03-24 07:03:

    Hey Michael,

    I love the simplicity of this library! Just wanted to give you a heads-up on a small error in Erkanaauth.php in the getRole() method:


    Line 105:

    $this->CI->db->JOIN('roles', 'users.role_id = roles.id');

    Should read:

    $this->CI->db->JOIN('roles', 'users.role_id = roles.name');

    Thanks so much for sharing your work and for being open-minded about other’s needs.

  24. jurigjarian says at 2008-03-26 21:03:

    Is it possible to use in commercial product ?, sorry I’m not really understand about CC license.
    thanks

  25. sigmaCMS: A Codeigniter based CMS — tomybeat says at 2008-04-01 04:04:

    […] management stuff. I’ve built the account registration from scratch. The cool thing about Erkana is it’s so light and flexible, I’m still left with a lot of freedom to implement the […]

  26. Mark says at 2008-04-04 13:04:

    Hey, man, thanks for the great library!
    You should state in your explanation a couple of sample validation rights, cause i’m kind of a noob in CI and it took me a while to figure it out (a week to be more presice) :))))

    $rules['username'] = "required|callback_check_login";
    $rules['password'] = "required";

    Thanks again!

  27. Sam says at 2008-04-05 09:04:

    if i use the erkana auth lib then will the rest of my script depending on it have to be licensed under Creative Commons Attribution-Share Alike 3.0 United States License or can it be different

  28. Michael Wales says at 2008-04-05 14:04:

    @Sam
    No, you may license your script however you like - you just need to place a credit within the documentation, on the website, within the code, etc. that you are using the Erkana Authorization Library, which is licensed under the CC Attribution-Share Alike 3.0 with a link to this post.

    Thanks for your interest in the library.

  29. Petter Andersen says at 2008-04-11 10:04:

    Thanks for this nice library, I want to use it in my next project!

  30. Kuba Mlacki says at 2008-05-07 02:05:

    Very nice, very helpful. Thanks for that librabry. I used it once for my project and will use it in the next one for sure.

  31. HSDell says at 2008-05-09 18:05:

    Hi!

    Looks great and I’m trying to implement, but getting the following error in the Erkanaauth class try_login call:

    Fatal error: Call to undefined method CI_DB_mysql_driver::select()

    I’m running PHP 5.2.5 and CI 1.5.4

    Thanks in advance for any help.

  32. HSDell says at 2008-05-09 18:05:

    …nevermind, I fixed it.

    Needed to set config parm in database.php:
    $db['default']['active_r'] = TRUE;

    Even though I was using active record class successfully without it in other models.

    Thanks!

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>