DarkAuth - another way...

3 : 5 Steps to Setup (well, maybe 6)

By Chris Walker (theChrisWalker)
I wrote this initially for Cake 1.1 - basing it on ideas from "obAuth" by Steve Oliveira, but upgraded it to 1.2 rather than using the built in Auth component, mostly because this works how I want it to and, once setup, is really easy to use.

Main Features:

- Per action / per controller / inline access control
- Optional Group support for HABTM and User BelongsTo Group associations
- A "super-user" functionality allowing one group automatic access granted
- Optional tamper-proof Cookie support
- Custom password hashing to suit your Model
The follow steps should guide you through the setup process and the files you need to alter.

Of course, you will need to have the models for your User table (and groups if applicable).

I would often use the following with a $hasAndBelongsToMany association (I pretty much always use the first 4 fields of the users and groups tables with cake):

CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`created` datetime default NULL,
`modified` datetime default NULL,
`live` tinyint(1) NOT NULL default 0,
`username` varchar(16) NOT NULL default '',
`password` varchar(32) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `groups` (
`id` int(11) NOT NULL auto_increment,
`created` datetime default NULL,
`modified` datetime default NULL,
`live` tinyint(1) NOT NULL default 0,
`name` varchar(32) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `groups_users` (
`group_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
KEY `group_id` (`group_id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Look at the Cake Manual for how to setup the Models for these tables.

If you don't use the HABTM association, then remember to set var HABTM = false; later. This will then assume that the user $belongsTo a group (and therefore you'd need a "group_id" field in your "users" table).

Now we have 5 (or 6) steps to a working, powerful authentication system!

Step 1: Modify AppController



I decided this was the easiest way as then your whole site knows about the Authentication, however I can see how it might put unnecessary load on in some situations.

This allows all controllers/views access to the auth component/data. In app_controller.php:

Controller Class:

<?php 
class AppController extends Controller {
    var 
$uses = array ('YOUR_MODEL_FOR_USERS');
    var 
$components = array('DarkAuth');
  }
?>


Where YOUR_MODEL_FOR_USERS is the name of your user model.

NB Remember if you want to use controllers with no models you will now need to use var $uses = array(); rather than var $uses = null; or you'll get errors!

Step 2: Add Default Methods



Now add the inversal login/logout methods to your app_controller.php and auto-include the "Session" helper (or is that included by default anyway now...):

Controller Class:

<?php 
  
var $helpers = array('Session');

  function 
_login(){
    if(
$this->data['DarkAuth']){
      unset(
$this->data['from_session']);
      
$this->DarkAuth->authenticate_from_post($this->data['DarkAuth']);
      exit();
    }
  }
  
  function 
logout(){
    
$this->DarkAuth->logout();
    
// By this stage we should have redirected and exited already, but just in case we'll pass them back to home...
    
$this->redirect($this->referer()); //thanks to everyone who spotted this.
  
}
?>


NB the logout method is called "logout" meaning you can call it from any controller at "/:controller/logout" but "_login()" won't be available, meaning you can create your own login page in a controller/page.

Step 3: Add the Views



Now we need to add the views for this component. They should be in the root of you views folder as we will need to call them from arbitrary controllers.

The 2 files are totally up to you except that the login page must pass the following data in the form:

[DarkAuth][username],
[DarkAuth][password]

and optionally if you have set the "$allow_cookie" variable:

[DarkAuth][remember_me],
[DarkAuth][cookie_expires],

Here are the templates I use:

View Template:

      
<?php /* View for login.ctp */ ?>
  
<h2>Login</h2>
  <div id='loginbox'>
      <?php 
    
echo $form->create('DarkAuth',array('url'=>substr($this->here,strlen($this->base))));
        echo 
"\n<div class='input required'>";
    echo 
$form->input('username', array('div'=>false));
    echo 
"</div>";
    echo 
"\n<div class='input required'>";
    echo 
$form->label('password');
        echo 
$form->password('DarkAuth/password');
    echo 
"</div>\n";
        
/* if you want to use cookies uncomment this. */
/*
      echo "<div class='input required'>";
      echo $form->checkbox('DarkAuth/remember_me');
      echo $form->label('Remember Me? (uses cookies)');
      echo "</div>\n";
      echo "<div class='input required'>";
      echo $form->label('If so, for how long?');
      echo $form->select('DarkAuth/cookie_expiry',array(
                                                        '+1 week'=>'in a week',
                                                        '+1 Months'=>'in a month',
                                                        '+6 Months'=>'in 6 months',
                                                        ));
      echo "</div>\n";
      
/* end of cookie bits */
        
     
echo $form->end('Login');
  
?>
  </div>
  
<?php /* View for deny.ctp */ ?>
  
<h2>Access Denied</h2>
<p>Sorry you don't have sufficient permission to access this page!</p>


Step 4: Edit the Component Setup Variables



Edit the class variables in this file to match your model structure.
these are in the top of the class definition on the previous page.

Step 5: Customise the password hasher



Change the "hasher()" function to match the way you store passwords in your model.
By default the hasher simply md5 hashes the input. you may wish to add salt, or encrypt in a different way.

Step 6 (optional): Create a Logout Route



Set up a route in you routes.php to allow you to logout in a nice way. Otherwise, you need to call "/controller/logout". I personally usually use my "Users" controller for this.

  Router::connect('/logout', array('controller' => 'ANY_CONTROLLER', 'action' => 'logout'));


And that's all



It sounds like a lot when I write it down, but actually it's not hard and the effect is great and easy to use. I haven't looked at Cake's own to know whether this is better / worse , simpler / more complex but it works for me and perhap you need something exactly like this!

Comments 617

CakePHP Team Comments Author Comments
 

Comment

1 Thanks for a great article

A very thorough and helpful article. Good job in creating it in a way to suit the most amount of people.

However the one thing that will probably keep me from using it, is that my tastes are a bit opposite to yours. I prefer to define access names and check for those. I have predefined what access the groups have and check if a user has access through it's group.

I dont know if that is clear, but in your example, I would define that the SecretsController requires "Secret level access" and either the (or one of the) group that logged in user belongs to has access to it or not.

The gain from doing it this way is that I don't have to edit my secrets controller when adding,removing or editing groups . This I feel is more inline with the cake behavior of controllers.

Anyways, just wanted to offer my 2 cents and thank you for your contribution.
Posted Feb 19, 2008 by Alexander
 

Comment

2 Thanks

Thanks for the article - haven't digested it all yet, but like you the first thing I do is user auth in my apps. I'll give this a look
Posted Feb 19, 2008 by Brit Gardner
 

Question

3 it doesnt work

Hi,

I'm newbie in cakePHP and I think this article is written in very bad way. Why you didn't create COMPLETE GUIDE ? You wrote sentenses like: "Look at the Cake Manual for how to setup the Models for these tables.", "var $uses = array ('YOUR_MODEL_FOR_USERS'); ", and so on.

I'm newbie and I don't know what you mean. I looked at manual but it still doesn't work !!!

I have errors like : "SQL Error: 1054: Unknown column 'User.email' in 'where clause'", when I go to "cake_1.2beta/users/_login" it has error "Error: UsersController::_login() cannot be accessed directly.", and so on ...

I know that I mistakely did something, BUT YOU CAN WRITE ARTICLES MORE UNDERSTAND ...

What do you recommend me ?

thx
Posted Feb 29, 2008 by greppi
 

Comment

4 RE it doesnt work

I don't think its really necessary to tell the author his article isn't written well when the problem is obviously your lack of understanding CakePHP, as you admitted. If you are unfamiliar with the framework then a good place to start would be the docs. Either http://tempdocs.cakephp.org/ for the BETA or http://manual.cakephp.org/ for the stable release.

We are all newbies once and I know exactly how you feel, when I first started I was completely lost (coming from an ASP.NET background to PHP), but it is through the docs and articles like these that I have quickly picked it up.

As far as the problems you have, the SQL error means you have not created the correct columns in your table.

"Look at the Cake Manual for how to setup the Models for these tables." - Means just that - go check out the documentation and samples that are available and you will quickly see how to implement the models for your application.

Anyways, I for one would like to say thank you to the author, I am in the middle of implementing this in my current project and it's looking promising. Great job
Posted Mar 2, 2008 by Wayne
 

Comment

5 RE RE it doesnt work

That's true, but ... Anyway, I'll study more, ...
Posted Mar 4, 2008 by greppi
 

Question

6 Redirect after login form broken

I am trying to get DarkAuth to work with Cake 1.2.0.6311. It is looking promising... but right now I am stuck.

I followed all your steps and am using your login and deny pages. DarkAuth is protecting a test controller, but after completing the login form I am not getting the page of the controller action. All I get is the Debug info, which is shown at the bottom of the page with the CakePHP default views. After reloading or loading another action manually, I get the correct behavior.

As I have by now started with freshly baked controllers/views a couple of times I begin to wonder whether this is an Apache or DarkAuth problem.

Any ideas?

Thanks for the nice component!
Posted Mar 10, 2008 by Stephan
 

Question

7 RE Redirect after login form broken

I followed all your steps and am using your login and deny pages. DarkAuth is protecting a test controller, but after completing the login form I am not getting the page of the controller action.

I had the same problem, I found a workaround by removing the line
exit();
from the _login() function in app_controller.php and sobstituting it with:
$this->redirect('./');

Hope that works
Posted Mar 15, 2008 by Stefano Pallicca
 

Question

8 DarkAuth for home.ctp

I'm trying to implement this auth system in one of my projects. Now I have a question: I'm trying to add authentication to my home page (that is home.ctp). Now, this page has no controller, so how can darkauth e aware of it?

I'll try to describe my problem more in depth: I've successfully applied darkauth to a User model, so if I try to access /cake/users I get my login screen, and everything works fine.
Now, if I want to go back to my site homepage, located in /cake, I get an error:

Undefined property: PagesController::$User [APP/controllers/components/dark_auth.php, line 248]

Line 248 says:

$check = $this->controller->{$this->user_model_name}->find($conditions);

And I can understand the error, since home.ctp has no controller associated.
home.ctp shows correctly if I logout from darkauth...
What if I'd like to show a different content on the home page for logged/unlogged users? Is it possibile?
Thanks in advance and sorry for the long post.
Posted Mar 15, 2008 by Stefano Pallicca
 

Comment

9 RE RE Redirect after login form broken

I followed all your steps and am using your login and deny pages. DarkAuth is protecting a test controller, but after completing the login form I am not getting the page of the controller action.

I had the same problem, I found a workaround by removing the line
exit();
from the _login() function in app_controller.php and sobstituting it with:
$this->redirect('./');

Hope that works



First, I would like to thank Chris Walker or this wonderful component. It is simple, straightforward and fully working.

My approach to the problem above is to include this line:

$this->redirect($this->referer());

just before the exit();

This way, the user is redirected to the url he wants to.
Posted Mar 17, 2008 by mike stivaktakis
 

Comment

10 Re DarkAuth for home.ctp

Firstly, thanks to you all for your comments, suggestions and encouragement. Particularly the first comment by Alexander: "Good job in creating it in a way to suit the most amount of people." This is exactly what I wanted to do but you can never tell!

In response to Stefano Pallicca:
I'm trying to implement this auth system in one of my projects. Now I have a question: I'm trying to add authentication to my home page (that is home.ctp). Now, this page has no controller, so how can darkauth e aware of it?

I'll try to describe my problem more in depth: I've successfully applied darkauth to a User model, so if I try to access /cake/users I get my login screen, and everything works fine.
Now, if I want to go back to my site homepage, located in /cake, I get an error:

Undefined property: PagesController::$User [APP/controllers/components/dark_auth.php, line 248]

Line 248 says:

$check = $this->controller->{$this->user_model_name}->find($conditions);

And I can understand the error, since home.ctp has no controller associated.
home.ctp shows correctly if I logout from darkauth...
What if I'd like to show a different content on the home page for logged/unlogged users? Is it possibile?
Thanks in advance and sorry for the long post.


It looks like you haven't added the

$uses = array('User');

line to your AppController, that's what I would check first.
The controller your home.ctp view uses is the PagesController, which doesn't appear to have access to your User model. In an update I will get DarkAuth to load it automagically if needed, but for now you must add it to your AppController class.

Posted Apr 4, 2008 by Chris Walker
 

Comment

11 Re DarkAuth for home.ctp

It looks like you haven't added the
$uses = array('User');


That was the point: I added 'user' (lowercase), that's why it didn't work! Thanks for the tip and keep improving darkauth!
Posted Apr 5, 2008 by Stefano Pallicca
 

Comment

12 destroyDate() destroys all session data.

When the function destroyData() is called, it destroys all session data, while it should only delete the session data set by DarkAuth.

To fix this, replace:
$this->Session->destroy($this->secure_key());
by
$this->Session->delete($this->secure_key());
Posted Apr 26, 2008 by Tijmen
 

Comment

13 RE destroyData()

When the function destroyData() is called, it destroys all session data, while it should only delete the session data set by DarkAuth.

To fix this, replace:
$this->Session->destroy($this->secure_key());
by
$this->Session->delete($this->secure_key());


Thanks, I've updated this in the article. Also I have updated the code in a much bigger way, adding some new features and improving efficiency, and have posted a new article with it - which hasn't been moderated yet. Sometime soon it should be available at: http://bakery.cakephp.org/articles/view/darkauth-v1-3-an-auth-component
Posted Apr 26, 2008 by Chris Walker
 

Question

14 New Code


Thanks, I've updated this in the article. Also I have updated the code in a much bigger way, adding some new features and improving efficiency, and have posted a new article with it - which hasn't been moderated yet. Sometime soon it should be available at: http://bakery.cakephp.org/articles/view/darkauth-v1-3-an-auth-component


Hi Chris, any ideas when the article might be moderated? I am quite interested in the updated code for my new project :)
Posted May 2, 2008 by Wayne
 

Comment

15 RE New Code


Hi Chris, any ideas when the article might be moderated? I am quite interested in the updated code for my new project :)


I have no idea, so I put a copy of the article on my own website... http://thechriswalker.net/darkauth-1. Enjoy.
Posted May 2, 2008 by Chris Walker
 

Comment

16 I got this works

Chris May be this could help someone :

STEP [ 1 ]
Create 3 tables, if you have users table just add this fields (live, username, password)

CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`created` datetime default NULL,
`modified` datetime default NULL,
`live` tinyint(1) NOT NULL default 0,
`username` varchar(16) NOT NULL default '',
`passwd` varchar(32) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `groups` (
`id` int(11) NOT NULL auto_increment,
`created` datetime default NULL,
`modified` datetime default NULL,
`live` tinyint(1) NOT NULL default 0,
`name` varchar(32) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `groups_users` (
`group_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
KEY `group_id` (`group_id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


STEP [ 2 ]
Create Group Model (/app/models/group.php)

Model Class:

<?php 

class Group extends AppModel {

    var 
$name 'Group';

    var 
$useTable 'groups';

}

?>


STEP [ 3 ]
Add HABTM to your user's model (/app/models/user.php)

var $hasAndBelongsToMany = array('Group' => array('className'    => 'Group',
        'joinTable'    => 'groups_users',
        'foreignKey'   => 'user_id',
        'associationForeignKey'=> 'group_id',
        'unique'       => true
        )
    );


STEP [ 4 ]
Modify your appcontroller like mine (/app/app_controller.php)

Controller Class:

<?php 
class AppController extends Controller {
    var 
$helpers = array('Form''Html''Javascript''Session');
    var 
$uses = array('User''Group');
    var 
$components = array('DarkAuth');
    
    function 
_login(){
        if(
is_array($this->data) && array_key_exists('DarkAuth',$this->data) ){
            
$this->DarkAuth->authenticate_from_post($this->data['DarkAuth']);
            
$this->data['DarkAuth']['password'] = '';
        }
    }

    function 
logout(){
        
$this->DarkAuth->logout();
    }
}
?>


STEP [ 5 ]
Put DarkAuth Component as (/app/controllers/components/dark_auth.php)
You can get the code from author site http://thechriswalker.net/darkauth-2

Component Class:

<?php 
class DarkAuthComponent extends Object {
    ....
}
?>


STEP [ 6 ]
Add some view (/app/views/login.ctp)

View Template:


<?
   $this
->pageTitle 'Access Restricted';
   echo 
$form->create('DarkAuth',array('url'=>substr($this->here,strlen($this->base))));
   echo 
$form->input('DarkAuth.username');
   echo 
$form->password('DarkAuth.password');
                
   echo 
$form->end('login');
?>

and (/app/views/deny.ctp)

View Template:


<?php
    $this
->pageTitle 'Access Denied!';
?>
<p>I'm sorry, but you don't have sufficient permission to access this page!</p>


and then modify (/app/controllers/components/dark_auth.php) to match your password encryption type.
find "function hasher".

  function hasher($plain_text){
    $hashed = md5('dark'.$plain_text.'cake');
    return $hashed;
  }

in this default hasher your password should be
UPDATE users SET password = MD5('dark....cake') WHERE id = ....

find "$user_name_field" and set variable as your table's field

var $user_name_field = 'email';
var $user_pass_field = 'pswd';

because we use 'username' and 'password' from CREATE TABLE above, so we have to set like this :

var $user_name_field = 'username';
var $user_pass_field = 'passwd';


STEP [ 7 ]
Add new records to your table

INSERT INTO `groups` (`created`, `modified`, `live`, `name`) VALUES
(NOW(), NOW(), 1, 'Admin'),
(NOW(), NOW(), 1, 'Root');

INSERT INTO `groups_users` (`group_id`, `user_id`) VALUES
(1, 1);

INSERT INTO `users` (`live`, `username`, `passwd`) VALUES 
('1', 'YOURNAME', MD5('darkMYPASSWORDcake')); 


STEP [ 8 ]
Put any rules in your controller

var $_DarkAuth = array('required'=>array('Admin','Member'));


eg : in my User controller

Controller Class:

<?php 

class UsersController extends AppController {

    var 
$name 'Users';

    var 
$helpers = array('Html''Form');
    var 
$_DarkAuth = array('required'=>array('Admin','Member'));
    
    ...
    ...
}
?>


STEP [ 9 ]
Testing go to http://yourapps/users/login, type YOURNAME as username
and MYPASSWORD as password.

Happy coding...thanks to Chris
Posted May 29, 2008 by Agus Sudarmanto