Using AuthComponent and ACL in CakePHP 1.2

19 07 2007

The uniqueness issues and also an issue with inheritence has been solved in changset 5588

Important Update (2007-07-24) : Brian brought to my attention a problem with multiple actions that have the same name. This problem is due to an incorrect Sql query in db_acl.php. I have filed Trac Ticket #2976 which includes a patch, unit test and test fixtures.

So I’ve shown you how to create a User Model that can be used for ACL, but what is next?

The AuthComponent allows you to both authenticate and authorize your users in a relatively simple manner – once you know how. This took me a lot of source code digging, mail list browsing and googling to find the way that “just works”.

Setting up Aco’s, Aro’s and Permissions

First of, we need to have some Aro’s and Aco’s. Aro’s are the User model from above and are simple enough – you can get away with scaffolding if you want.

Aco’s took me a little longer to figure out. There are going to be controller action pairs, naturally, but the catch was how to put these into the database. It turns out that you need to have Controllers at one level, with actions children of there respective controllers. This might seem obvious but I was trying to save the actions with an alias of “controller/action” when they should just be “action”.

Your tree of Aco aliases should look like the following:

ROOT
|-Controller1
  |-index
  |-action1
  |-action2
|-Controller2
  |-index
  |-action1

Pretty straight forward once you know how. This way the path can be followed down (or up actually) by the AclComponent. It also allows you to create wholesale permissions such as denying a whole controller by setting the permissions on the controller level.

Then all you need to do is grant Users access to actions. Because we are using User models the easist way is with a series of commands like:

$this->Acl->allow(array('model' => 'User', 'foreign_key' => $id), 'Controller1/action');

Using AuthComponent for Authentication

The AuthComponent is a really great tool and is very flexible. This post will only show one way to use it, but there are many other ways to put it to use.

First up, we will use AuthComponent for authentication. This part is pretty straight forward, but requires a little configuration. The best place to do this is in AppController::beforeFilter().

You need to include the AclComponent and the AuthComponent in AppController.

var $components = array('Acl', 'Auth');

It is very import that you include the AclComponent before the AuthComponent otherwise you will get this funky error message.

Fatal error: Call to a member function check() on a non-object in /var/www/geoff/cake/cake/libs/controller/components/acl.php on line 87

The reason for this is that Components are started in the order they appear in the $components list, and the AuthComponent does all its magic at startup, so when Auth tries to use Acl::check() there is no Acl.

For authentication we need to set the loginAction and loginRedirect properties.

function beforeFilter(){
  if (isset($this->Auth)) {
    $this->Auth->loginAction = '/users/login';
    $this->Auth->loginRedirect = '/users/account';
  }
}

You can also set the fields that are used for authentication if your user model does not use the default of ‘username’ and ‘password’.

$this->Auth->fields = array('username' => 'login_name', 'password' => 'p4sswrd');

It is worth noting that the AuthComponent will hash the password for security reasons. This is default behaviour and it can not be overriden. Where I got caught out (again) was that I had a before save on my user model that hashed the password in the same manner as AuthComponent. Do not hash your passwords at the model level if you have included the AuthComponet at the AppController level. The AuthComponent will hash it before it gets to your beforeSave and you will end up with double hashed passwords in the database and therefore unable to login.

Another good config option is the userScope property. It allows you to add other conditions to the authentication query, such as checking a disabled field.

 $this->Auth->userScope = array('User.disabled' => 0);

Using AuthComponent for Authorization

So that was how to set your authentication. Setting up AuthComponet for authorization against ACL is actually easier. One extra line of code.

$this->Auth->authorize = 'actions';

This will use the User Aro’s created above that corresponds to the User just authenticated, and test it against the current controller and action. Surprisingly easy. 🙂

Final Result

The final AppController should look like:

class AppController extends Controller {
  var $helpers = array('Html', 'Javascript', 'Form');
  var $components = array('Acl', 'Auth');
  var $publicControllers = array('pages');
	
  function beforeFilter(){
    if (isset($this->Auth)) {
      $this->Auth->userScope = array('User.disabled' => 0);
      $this->Auth->loginAction = '/users/login';
      $this->Auth->loginRedirect = '/users/account';
      $this->Auth->fields = array('username' => 'username', 'password' => 'passwrd');
      $this->Auth->authorize = 'actions';

      if (in_array(low($this->params['controller']), $this->publicControllers)) {	
	    $this->Auth->allow();	
      }
    }
  }
}

$this->publicControllers allows you to assign controllers which do not require authentication or authorization. I mainly use it to grant access to the pages contoller.





Cracked 100

17 07 2007

Thanks to all the readers yesterday who helped me pass 100 hits in a day – 135 to be exact. This may not impress some, but I think it is alright for a niche blog that has only been running for 40 days.

So cheers to you all. 🙂





Using AclBehavior in CakePHP 1.2

15 07 2007

CakePHP 1.2 has a new AclBehavior which makes using the inbuilt ACL easier. AclBehavior makes the association between your model and the Aro (or Aco) database entry automatic. It handles the insert, updates and deletes whenever you modify your model. All that is required to use the AclBehavior is a function called parentNode().

AclBehavior can be used for creating AROs or ACOs. Any model may be an Access Request Object, but typically it is either the User model or a Group model that authorization is done on. In either case it is the same for any model you choose. AclBehavior defaults to creating AROs which is what we want. As for ACOs, usually these are controllers and/or actions, which don’t lend themselves to the AclBehavior so well.

First step is to set up your database ACL tables with

cake acl initdb

Basics

You need to include the behaviour and create a function called parentNode. This is the minimum required to use AclBehavior.

<?php
class User extends AppModel {
  var $name = 'User';
  var $actsAs = array('Acl');

  function parentNode(){
  }
}?>

What is the parentNode() function for?

It is used when you have cascading, or inherited permissions, for example a Group model. The parentNode() function must return the id of the parent Model (not the id of the parent Aro). Typically this will be the parent_id of your Model, if you are using the standard convention for trees in Cake.

<?php
class Group extends AppModel {
  var $name = 'Group';
  var $actsAs = array('Acl');

  function parentNode(){
    if (!$this->id) {
      return null;
    }
		
    $data = $this->read();
		
    if (!$data['Group']['parent_id']){
      return null;
    } else {
      return $data['Group']['parent_id'];
    }
  }

}
?>

That’s it. Your model is now associated with an Aro entry in the aro table in your database.

Further Reading

Keep an eye out for my upcoming article on the Auth Component. See my post Using AuthComponent and ACL in CakePHP 1.2
Also see Groups with ACL for using groups and users together
In the meantime I highly recommend the article Access Control for all (Part 1) by AD7six





All About Validation in CakePHP 1.2 – Part 2

6 07 2007

In my previous article I discussed the new constructs for Model::validate. This article follows on from this and is a run down of the new validation methods and rules available.

First up there are a couple of regular expressions defined, which are the same from CakePHP 1.1 and are pretty self explanatory. These are VALID_NOT_EMPTY, VALID_NUMBER, VALID_EMAIL, and VALID_YEAR (between 1000-2999).

The general format of the following validation methods is

var $validate = array('field' => array('rule' => 'ruleName'));

Where parameters are required, such as between and cc, the format is

var $validate = array('field' => 
        array('rule' => array('ruleName', 'param1', 'param2'));

alphaNumeric
Allows only digits and a-z or A-Z.

between
Checks that a strings length is between a min and max value.

blank
Checks if a field is empty and treats whitespace characters as empty.

cc
Credit Card Number validation, includes luhn check and Card Type to number format. Takes one parameter which can be one of :-

  • fast – skips Card Type to number format check
  • all – checks the number against all card types until it finds a match
  • array of card types – like all but limited to a subset of cards.

e.g.

var $validate = array('field' => 
        array('rule' => array('cc', array('Visa')));

compare
Allows you to compare two numeric values. Takes two parameters:-

  • Operator – one of <, >, <=, >=, == or !=
  • Comparison value to compare against

custom
Allows you to use custom regular expressions. Takes the custom regex as the only parameter.

date
Validates a string as a date. Can take one parameter;

  • Format – default is ‘ymd’. other options are:
    • dmy
    • mdy
    • ymd
    • dMy – short or long month names
    • Mdy
    • My
    • my

decimal
Checks that a number has a decimal point or is scientific notation. Takes the number of decimal places required after the point as the only parameter. If places is null it will check for scientific notation.

email
Checks for a valid email address. If a parameter of true is passed it will also attempt to verify the host. If the parameter passed is false, or none is passed it behaves the same as VALID_EMAIL.

ip
Checks for IPv4 dot notation. e.g. 192.168.0.1

minLength
Checks a string for a minimum length. Length is passed as the only parameter.

maxLength
Checks a string for a maximum length. Length is passed as the only parameter.

money
Checks that a string is numbers, optionally grouped into blocks of 3 separated by a space, comma or period, with an optional block of 2 at the end. Can take a parameter of ‘right’ if you expect the currency symbol at the end, the default is at the start.

numeric
Simply calls is_numeric()

phone
Checks for a valid phone format. Takes regex and country as parameters. Currently only supports ‘us’ country option.

postal
Checks for a valid post code format. Takes regex and country as parameters. Currently only supports ‘us’, ‘uk’ and ‘ca’ country options.

ssn
Checks for a valid social security number format. Takes regex and country as parameters. Currently only supports ‘us’, ‘dk’ and ‘nl’ country options.

url
Checks for valid URL format. Supports http(s), ftp(s), file, news and gopher protocols

userDefined
Calls a userdefined method of the current model passing along any parameters. , the first of which is the method to call. Personally I think this is redundant as you can simply replace userDefined with your method name and it works the same.

There are also some incomplete methods listed below that will be coming soon.

number – checks that a number is within a given range
multiple – will be used for selects and multiple selects
equalTo – direct comparison to another value
file – checks for a file.





All About Validation in CakePHP 1.2

3 07 2007

Validation in v1.1 of CakePHP was quite simple, and many found it lacking in features and flexibility. This is evidenced by the number of alternatives that people have written such as Daniel Hofstetter, Evan Sagge and Adeel Khan‘s ruby-esque approach.

However in CakePHP 1.2 there has been a major rework of the Validation class‘s inner workings, and the way Model::invalidFields() works.

The New $validate

The new $validate can take a number of different constructs now. There are 3 ways to define your validation rules and you can mix and match as needed.

Construct 1: CakePHP 1.1 way
The old CakePHP 1.1 $validate construct will still work

var $validate = array('fieldName' => 'ruleName')

Construct 2: Single Rule per field
You can now define more complex rules using the following construct. (Parameters explained later)

var $validate = array(
  'fieldName' => array(
    'rule' => 'ruleName' // or 'rule' => array('ruleName',  'param1', 'param2' ...)
    'required' => true,'allowEmpty' => false,
    'on' => 'create', // or update
    'message' => 'Your Error Message'
    )
  );

Constrct 3: Multiple Rules per field
Similar to Construct 2, however you can define multiple validation rules for a single field.

var $validate = array(
  'fieldName' => array(
    'rule_index' => array(
      'rule' => 'ruleName' // or 'rule' => array('ruleName',  'param1', 'param2' ...)
      'required' => true,'allowEmpty' => false,
      'on' => 'create', // or update
      'message' => 'Your Error Message'
      )
    )
  );

The new Parameters

The new $validate supports a number of parameters. The only required parameter is ‘rule’.

rule – mixed:
The Rule parameter defines the validation method and takes either a single value or an array. Rule may be (in order of preference) a method of your model, a method of the Validation class or a Regular Expression. If Rule is an array and ‘ruleName’ is a method, all other members of the array will be passed to the method. eg.

var $validate = array('username' => array('rule' => array('between', 6, 20)));

allowEmpty – bool:
This defines the behaviour when an empty value for the field is found. ‘allowEmpty’ => false will cause the validation to fail when the field data is empty. N.B: This rule is only enforced when there is an actual fieldName index in the data array.

Default is false.

required – bool:
‘required’ => true means that an index with fieldName must exist in the data array, i.e. validation will fail if isset($data[‘ModelName’][‘fieldName’]) fails. N.B Required does not care if the value is empty – see allowEmpty above.

Default is false.

on – string (‘create’ or ‘update’):
If on is defined , the validation rule will only be applied on model ‘create’ or ‘update’. If not defined it is applied everytime. This may be useful for situations such as created_by is required on record creation, but on update it must not be defined.

Default is null, i.e. apply rule everytime.

message – string:
Message is the error message that will be stored in validationErrors. If message is not define, it will attempt to use rule_index (in Construct 3) if it is a string, otherwise it will default to ‘This field cannot be left blank’.

There is also another parameter ‘last’ defined in the code but it is not used as yet. Not sure what it’s use will be either.

A Full Example

This is the actual validate variable from my User model. It contains a mixture of the above constructs and techniques.

var $validate = array(
  'username'   => array(
    VALID_NOT_EMPTY,
    'alphanumeric' => array(
      'rule' => 'alphanumeric',
      'message' => 'Username may only consist of letter and numbers'), 
    'length' => array(
      'rule' => array('between', 6, 20),
      'message' => 'Username must be between 6 and 20 characters in length')
  ),
  'name'     => VALID_NOT_EMPTY,
  'email'   => array(
    'Invalid email format' => VALID_EMAIL, 
    VALID_NOT_EMPTY
  ),
  'passwrd'   => array(
    VALID_NOT_EMPTY,
    'length' => array(
      'rule' => array('minLength', 6),
      'message' => 'Password must be at least 6 characters in length'),
    'strong' => array(
      'rule' => 'isStrong', 
      'message' => 'Your password is not strong enough')
  )
);

Disclaimer: My knowledge of the new validation was gained from the Bakery Article Multiple Rules of Validation, CakeBaker’s article Validation with CakePHP 1.2 and mostly from looking at the source code. If I have interpreted something incorrectly, please let me know.





Validation Gotcha in CakePHP 1.2

26 06 2007

While trying to write a simple login function for a user model today I came across a small gotcha that it is not apparent at first.

In CakePHP 1.1 if you want to manually validate a model you would write:

if ($this->Model->validates($this->data)){
    //success
}

However in CakePHP 1.2 this throws a nice deprecated warning:

Warning (512): (Model::validates) Parameter usage is deprecated, set the $data property instead [CORE/cake/libs/model/model.php, line 1660]

I first tried just an empty validates() expecting it to use Controller::data, however this was appearing to pass validation. Not good when the entire form was empty with VALID_NOT_EMPTY’s on every field. A quick look-see in the source of model.php reveals that Model::invalidFields() expects Model::data to be populated.

As pointed out by nate in the comments my original solution is not recommended.

The updated solution is to use:

$this->Model->set($this->data);
if ($this->Model->validates()){
    // success
}




CakePHP Test Suite Shell

24 06 2007

In addition to my changes to the core Test Suite to add support for plugins, I have now created a console shell to run test suites via the command line.

To use the Test Suite Shell simply place testsuite.php in /vendors/shells.

Usage:
cake testsuite help
this message
cake testsuite run section test_type [case_type] test
– section – app, core or plugin_name
– test_type – case, group or all
– case_type – only with case, one of behaviors, components, controllers, helpers or models
– test – file without (test|group).php

Examples:
cake testsuite run core all – will run all core tests
cake testsuite run app group models – will exexute /app/tests/groups/models.group.php
cake testsuite run contents case model content – will execute /app/plugins/contents/tests/cases/models/content.test.php