Setting up and using the Auth module in Kohana 3.1

The documentation about the Auth module in Kohana 3.1 is severely lacking, and the module has changed sufficiently that existing tutorials and documentations are no longer relevant.

So below is a quick tutorial on how to setup and use the module:

1) Enable the modules

If not done already, enable the needed modules in bootstrap.php. In particular, auth, database and ORM need to be enabled:

<?php
Kohana::modules(array(
    'auth'       => MODPATH.'auth',       // Basic authentication
    // 'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database'   => MODPATH.'database',   // Database access
    // 'image'      => MODPATH.'image',      // Image manipulation
    'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
    ));
?>

2) Setup the database

– Copy the configuration file from modules/database/config/database.php to application/config/database.php
– Open it and set username, password, etc.
– Create the database schema using the SQL file in modules/orm/auth-schema-mysql.sql

You should now have a working database with all the required tables.

3) Setup the Auth module

– Copy the Auth config file from modules\auth\config\auth.php to your config folder in application/config.
– Open this file and change the driver to “ORM” and set a hash key. It can be any random value such as those generated by WordPress.
– Your file should then look like this:

<?php defined('SYSPATH') or die('No direct access allowed.');

return array(

    'driver'       => 'ORM',
    'hash_method'  => 'sha256',
    'hash_key'     => "4b 8?((~FKnpD))>8kb!B |#-uXIO24G3rc:&MG+FR{x;r#Uq4k{Ef@F4E9^-qS!",
    'lifetime'     => 1209600,
    'session_key'  => 'auth_user',

    // Username/password combinations for the Auth File driver
    'users' => array(
        // 'admin' => 'b3154acf3a344170077d11bdb5fff31532f679a1919e716a02',
    ),

);

In order for the Auth module to work, you must also set the cookie salt variable. So add this at the end of your bootstrap.php file:

Cookie::$salt = 'somerandomstring';

4) How to register a user

Once the database and Auth are setup, it is relatively easy to add a user to the database, although there are some pitfalls (see comments below). Here is the minimum code required to add a user:

<?php
$client = ORM::factory('user');
$client->email = "my@email.com";

/* Note that the username cannot contain
   certain characters such as"." or "@".
   If it does "$client->save()" is going
   to crash, and the error message is not
   helpful */
$client->username = "laurent";

/* Auth is going to automatically hash
   the password when saving the user,
   so don't do it manually */
$client->password = "mypa55word";

$client->save();
?>

After saving the user, assign a role to him (see this post comments).

5) Example login

Once this is all done, login a user is straightforwards:

<?php
$r = Auth::instance()->login("laurent", "mypa55word");
?>

You can also check if a user is currently logged in and, if so, retrieve it from the database:

<?php
$loggedIn = Auth::instance()->logged_in();
if ($loggedIn) {
    $user = Auth::instance()->get_user();
} else {
    echo "User is not logged in";
}
?>

For more information, have a look at the Auth Module API documentation.

Tags: , , , ,

7 Responses to “Setting up and using the Auth module in Kohana 3.1”

  1. Bernardo Says:

    I spent many hours trying to make the system login KO3.1 work until you get into your post.
    I tried to access it before the google search for it seems that was outside of HR.

    Wonderful contribution.

  2. MBa Says:

    Thanks a lot.

  3. niski Says:

    And what about assigning roles to user?

    In http://kohanaframework.org/3.1/guide/api/Auth_ORM#_login it looks like the user needs to be put into roles_users with id of login role…

    Without that set I wasn’t able to log in. I’ve inserted the row manually in database, is there any solution using kohana objects?

  4. Laurent Says:

    Unfortunately, I don’t know as I ended up developing my own Auth class. Kohana Auth’s module does too many magic things behind the scene and it’s difficult to guess how they expect us to work with it. It also unnecessarily force us to follow certain conventions (like the names of roles, the fact that a user cannot login with his email, it has to be his username, etc.). All this should be customizable, like in the Zend Framework, to be really useful.

    It took me a day to understand the module and work around its limitations and just a an hour or so to develop mine. It’s not as complete but it does the job and at least I know how it works.

  5. niski Says:

    Oh, good to know…

    BTW, that’s the code which needs to be put just after first
    $client->save();

    $role = ORM::factory(‘role’,’1′);
    $client->add(‘roles’,$role);
    $client->save();

  6. Laurent Says:

    Thanks Niski, I mentioned it in the post.

  7. Eduardo Says:

    Just a note that costed me some time to find.
    It’s necessary to create a model to the user, when creating it it’s necessary to extend Model_Auth_User. I was extending ORM and it broke when I was saving the role.
    Hope it helps somebody =D

Copyright © Pogopixels Ltd, 2008-2018