All posts tagged "CakePHP"

I found 4 posts tagged CakePHP

MVC framwork - from scratch!

So, I started a new job. And the first thing I get to work with is a large PHP application for managing Wireless Hotspots. The application presents a portal page to people trying to connect and handles payment and creation of the Radius info to allow them to use the service. The PHP element is mainly a large and complicated database frontend, with a few special functions to interface with some other systems. Anyway, the thing was originally written about 5 years ago in PHP 4.2.2 and the code makes me shudder.

So, I gave some thought to how I would do it if I was writing the same thing from scratch. I immediately thought "Cake" but then realised that for a commecial application I would want to fully understand all the under-the-hood business and as good as CakePHP is, I don't have that full understanding. So instead I thought about writing a framework from scratch - albeit based on many CakePHP principles.

Requirements

The first thing to think about is what you want the framework to achieve on it's own before we start to think about building the app on top of it. This project has some features which must be available in the framework.

  • Multiple points of entry:

    The application is accessed from 3 different places, and they will share much code.

    • The user interface is what a person trying to connect to the wireless network would see.
    • The customer interface is a Customer self-care portal for a hotspot provider to manage their hotspots.
    • The admin interface allows management of the entire system and reporting.
  • Multiple Databases: specifically, their are 2 databases in use, the "main" one and the Radius AAA database.

  • Authentication and Accesss control: for the 2 restricted interfaces, this should be ingrained into the framework at a low level, but extendible to accept different authentication mechanisms.

  • Licensing: this product may be sold under license so the ability to restrict capabilities is required.

Design

The next think to think about is how the framework will be put together. I leaned heavily on the cake approach in designing the basic structure of the framework. I tried to imagine the flow of a request and what I would need to build to make it work. So I got the following:

  1. Index.php: accepts the request set's some paths, loads a common "boot.php" file.
  2. Boot.php: loads the generic functions (including a "Loader" class for autoloading other classes), loads some config options from "ini" files, creates a Dispatcher instance and starts the ball rolling.
  3. Configure.php: handles the config options loaded, a "Globals" replacement.
  4. Dispatcher.php: co-ordinates the request. Processes POST data, gets info from Router class, and instantiates our Controller, and creates and renders the View.
  5. Router.php: Router class does forwards and reverse routing, extension parsing and parameter handling.
  6. Controller.php: has methods to set options for the view.
  7. View.php: takes the request options, controller settings and renders the appropriate template / layout.

Then there's all the other useful side classes Session, Cookie, HTML, Money and I haven't even got onto to Models yet.

Next time

I might have made a diagram to explain how this works, or myabe will be ranting about the Model parts, and multiple database access. To be honest to point of this article was not so much about the actual code, but more the structure and how if you break it down, a framework with much of the principles of Cake can be put together relatively easily. Of course I am only half way through, but progress has been quick.

In conclusion, I found it extremely interesting to see how the varous part of a framework work together and it is very satisfying to see it all fall into place. I now have the basis of a web-application framework that I understand inside out because I wrote every line of code. That is the benefit. When I use this now I will be supremely confident that I understand every nuance and feature.

Comments:

Sorry, comments are closed.

DarkAuth update, and test app.

I found another small glitch in DarkAuth, which stemmed from the major bug after CakePHP 1.2 RC1 was released.

The Controller::render() method has changed, which was integral to DarkAuth's functionality. The change stopped anything from being displayed if Auth was not present or sufficient. To fix it I had to force an exit() into the code.

This exit() then meant that the Component was not setting the $_DarkAuth variable at all, if the "login" or "deny" view where being displayed.

The updated code fixes this, and has been updated on the DarkAuth page.

In addition I introduced a nice utility method, DarkAuthComponent::getUserId() which simply the returns the id of the currently auth'd user. Something I needed often.

Also I decided it would be good to have a "test application", a simple setup of a working DarkAuth + Cake combo. So I have built one, and you can use it to see how DarkAuth works, and to play around with it to your hearts content!

There's 2 versions: one is just the app/ folder, and the other contains the full CakePHP1.2 RC1 code as well:

I put some useful code in there to help create the database config file and set up the required tables, so just extract and play!

Comments (14):

  1. Bill said at 00:28, 7th July 2008:

    Hi Chris, the link DarkAuth.test.inc.cake.zip is off. Great component, thanks
  2. theChrisWalker said at 17:36, 7th July 2008:

    You're right, I mean to update it to the RC2 code anyway... I'll remove for now.
  3. Theo said at 21:30, 9th July 2008:

    Hi, is it not possible for you to add functions to save logins (user/groups) back to the HABTM ? for example a submitted form of username/password and checkboxes for groups? or is there just a easy way to do it in cakephp? thanks
  4. Theo said at 21:44, 9th July 2008:

    sorry i meant 'save logins (user/roles)' not 'save logins (user/groups)' and 'checkboxes for roles' not 'checkboxes for groups'
  5. theChrisWalker said at 09:17, 10th July 2008:

    "or is there just a easy way to do it in cakephp?" Bingo.
  6. itsnotvalid said at 13:02, 11th July 2008:

    Glad that the comment system is up now. I just leave a message here to hope to see a SVN/git repository or a single dark_auth.php download, instead of just hoping through the archive or copying from the website(where sensible person wouldn't do anyway). And this component is a great one and really save me a lot of time. Thank you!!
  7. Theo said at 12:59, 12th July 2008:

    had the wrong case on my models names in my form :/ thats why it wasnt working for me thanks anyways
  8. blablacio said at 15:15, 15th July 2008:

    Hello Chris, I'm developing an application which apparently needs user authentication and I chose your component to help out with this. Everything runs just fine now, but I was wondering if there is a way to do this: <?php class UsersController extends AppController { var $name = 'Users'; var $scaffold; var $_DarkAuth = array('required'=>'Administrators'); function register(){ } function add(){ } } ?> I want to let only users of the group Administrators to do anything within the UsersController, but let regular guests access the register() function only. Any ideas? Thank you for your time and exceptional component!
  9. itsnotvalid said at 12:08, 20th July 2008:

    Also I discovered a bug that, when you are having a login form for a action that also reads from $this->data, e.g. scaffold views (e.g. add), you would also submit empty dataset to those actions. In scaffold add, for example, you would create an empty record. How to fix this?
  10. theChrisWalker said at 20:48, 20th July 2008:

    @ blablacio: I emailed you about this, basically, there is no way "allow" specific actions as yet, but sounds like a good addition for the future.
  11. theChrisWalker said at 20:54, 20th July 2008:

    @itsnotvalid: after successful login, you are redirected using a GET request for the URL, all POST data will be lost - which means the Add scaffold should render a form, not insert a row. Still it will be easy enough to check for valid data before save()'ing the model. The loss of POST is not something easily avoided, so I hope you didn't plan to be able to propagate that.
  12. Lukas said at 16:11, 29th July 2008:

    Hello Chris, I have downloaded your script and I have protected a controller. The login-form appears, but if I submit my username and password, then I get the following error: Fatal error: Cannot use object of type PostsController as array in (...)app\controllers\components\dark_auth.php on line 341 Do you have any advice? thanks, Lukas.
  13. Lukas said at 16:22, 29th July 2008:

    dark_auth.php 341: $this->controller{$this->user_model_name}->belongsTo[$this->group_model_name]['foreignKey']; fix: $this->controller->{$this->user_model_name}->belongsTo[$this->group_model_name]['foreignKey']; Lukas.
  14. Darren said at 08:39, 5th August 2008:

    Great component Chris thanks, just wondering if it was possible to use the component in the cake error pages (404, missing action etc). I've not managed to do it yet. Cheers!

Sorry, comments are closed.

Using DarkAuth with Groups and Roles

I have recently updated the code in /darkauth-2 to be compliant with the newly released CakePHP 1.2 RC. Only a small fix, but it made me think about DarkAuth and how it works best.

When I originally wrote it, I recieved some feedback from several different sources syaing that it was difficult to understand and didn't necessarily work as expected.

This was because DarkAuth has a very specific methodology and and is just as much an Access Control component as an Authentication one.

Authentication and Access Control

  • Authentication is a method of identifying users.
  • Access Control is a method of restricting those user to what they are allowed to do.

DarkAuth has some useful functions that help with both. In the next release of the code I intend to rename all references to "Group" with "Role" as it is really about Role-Based Access Control.

In my usual setup for using DarkAuth I create 5 tables: users, roles, roles_users, groups, groups_roles

The first three are straight forwards, they define the users of the system, any roles that might exist (think roles like "CanAddPosts", "CanEditItems", etc...) and the join table that defines their relationship.

The next two is where I define Groups of Roles. The whole point of this is simply a helper - I can pick which roles I give to my users explicitly, or I can choose a group which contains a certain array of roles. It just makes it easier to manage. Enough talk, on to an example.

Let's see it it action...

Using the following tables:

  1. CREATE TABLE IF NOT EXISTS `users` (
  2.   `id` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `created` DATETIME DEFAULT NULL,
  4.   `modified` DATETIME DEFAULT NULL,
  5.   `email` VARCHAR(64) NOT NULL,
  6.   `pswd` VARCHAR(32) character SET utf8 COLLATE utf8_bin NOT NULL,
  7.   `live` TINYINT(1) NOT NULL DEFAULT '0',
  8.   PRIMARY KEY  (`id`)
  9. ) ENGINE='MyISAM'  DEFAULT CHARSET='utf8';
  10.  
  11. CREATE TABLE IF NOT EXISTS `roles` (
  12.   `id` INT(11) NOT NULL AUTO_INCREMENT,
  13.   `name` VARCHAR(32) NOT NULL,
  14.   PRIMARY KEY  (`id`)
  15. ) ENGINE='MyISAM'  DEFAULT CHARSET='utf8';
  16.  
  17. CREATE TABLE IF NOT EXISTS `roles_users` (
  18.   `role_id` INT(11) NOT NULL,
  19.   `user_id` INT(11) NOT NULL,
  20.   KEY `role_id` (`role_id`,`user_id`)
  21. ) ENGINE='MyISAM'  DEFAULT CHARSET='utf8';
  22.  
  23. CREATE TABLE IF NOT EXISTS `groups` (
  24.   `id` INT(11) NOT NULL AUTO_INCREMENT,
  25.   `name` VARCHAR(24) NOT NULL,
  26.   PRIMARY KEY  (`id`)
  27. ) ENGINE='MyISAM'  DEFAULT CHARSET='utf8';
  28.  
  29. CREATE TABLE IF NOT EXISTS `groups_roles` (
  30.   `group_id` INT(11) NOT NULL,
  31.   `role_id` INT(11) NOT NULL,
  32.   KEY `group_id` (`group_id`,`role_id`)
  33. ) ENGINE='MyISAM'  DEFAULT CHARSET='utf8';

And with some sample data:

  1. INSERT INTO `users` VALUES (1,NOW(),NOW(),'reader@example.com','5f5a3325bce31f27472ececf3f9aee9a',1),  
  2. (2,NOW(),NOW(),'writer@example.com','5f5a3325bce31f27472ececf3f9aee9a',1),
  3. (3,NOW(),NOW(),'moderator@example.com','5f5a3325bce31f27472ececf3f9aee9a',1);
  4. INSERT INTO `roles` VALUES (1, 'Root'), (2, 'CanAddPosts'), (3, 'CanModeratePosts'), (4, 'CanEditOwnPosts'), (5, 'CanEditOtherPeoplesPosts');
  5. INSERT INTO `groups` VALUES (1, 'Reader'), (2, 'Writer'), (3, 'Moderator');
  6. -- Now the clever bit:
  7. INSERT INTO `groups_roles` VALUES (2, 2), (2, 4), (3, 2), (3, 3), (3, 4), (3, 5);

Which creates a mapping of roles to groups. We can then create a function which applies the given set of roles to the user. I put mine in GroupsController for lack of a better place, but I am not sure it should stay there. It goes like this:

  1. function _applyGroup($user_id,$group_id){
  2.     $data['User']['id'] = $user_id;
  3.     $data['Role']['Role'] = array_keys($this->Group->GroupsRole->find('list', array('conditions'=>array('group_id'=>$group_id), 'fields'=>'GroupsRole.role_id,GroupsRole.group_id')));
  4.     if($this->User->exists($user_id)){
  5.       if($this->User->save($data)){
  6.         //Success!
  7.         return true;        
  8.       }else{
  9.         //failure :(
  10.         return false;
  11.       }
  12.     }else{
  13.        //failure, no user found...
  14.        return false;
  15.     }

This function will then allow you to align your users' access to fit all the roles you have associated with the group.

This brings a question, should I links my groups with users directly? and read their security roles from the group. Or do I simply use the groups to define set of roles to Apply to users as I want?

I don't know.

The first sounds better, but then we couldn't do any bespoke customisations (i.e. one-off adding of roles to particular users). The second is what I currently use, but if you update a group the use's dont' automatically update.

I guess there's an answer in there that you update all users' permission's that match the previous role set of a group to the new role set whenever you change a group. Confused? hopefully not too much...

Comments (2):

  1. Bill said at 18:33, 11th July 2008:

    Hi Chris, i dont understand how this modification is usable...only i can see one thing. instead of using groups you are using roles, but the funcionality is the same. I wrong?
  2. theChrisWalker said at 09:16, 14th July 2008:

    You're not wrong, the functionality is the same. I just wanted to point out that DarkAuth is really a role-based authentication system, or was designed as such, where every action that need to be restricted has a "role" which can be granted. This quickly becomes a large set of "roles" and often you apply the same set of access to users. The idea of using the Roles and Groups allows easier management of the system with the benefit of the fine-grained control should you need it.

Sorry, comments are closed.

DarkAuth: Authentication for CakePHP

As I had already written some articles (hard coded too...) I figured it would probably be a good idea to link to them directly. The first is an authentication plugin for CakePHP, DarkAuth.

I wrote DarkAuth as an alternative to the inbuilt "Auth" authentication system in CakePHP 1.2. I never really looked at "Auth" so cannot comment on how good it is. I can say that DarkAuth works for me and how I want it to.

"How I want it to."

That's right, how I want it to. It may be perfect for you, or it may just make your life difficult. That being said, let me walk you through the concepts, then give you the links to the article.

DarkAuth is designed around role-based authentication for actions. I call them "groups" in the tutorial but more often than not I consider them access roles. This means that if you are not using HABTM associations in your app, DarkAuth probably isn't for you. the exception to that is if you don't use groups at all, then it's probably quite good!

The other "feature" of DarkAuth is that you don't have to create a specific "login" URL. If auth is required by your app on a page and the current user is not authenticated then the login is automagically displayed. If the user is logged but doesn't have the correct "role" or "group" then the access denied page is shown instead.

It's quite clever really and allows you to do things like this:

  1. <?php
  2. class ExamplesController extends AppController {
  3.   var $name = 'Examples';
  4.  
  5.   function index(){
  6.     // This function is un-restricted.
  7.   }
  8.  
  9.   function secret(){
  10.     // this function is Auth secured.
  11.     $this->DarkAuth->requiresAuth();
  12.   }
  13.  
  14.   function roleOnly(){
  15.     // this function require the "can_do_this" role
  16.     $this->DarkAuth->requiresAuth("can_do_this");
  17.   }
  18.  
  19.   function variedResult(){
  20.     // this function does one thing is auth and another if not.
  21.     if($this->DarkAuth->isAllowed()){
  22.        // do something
  23.        $this->set('some_data','User Authorised!');
  24.     }else{
  25.       // do something else...
  26.       $this->set('some_data','No Auth!');
  27.     }
  28.   }
  29. }
  30. ?>

So anyway, the reason you're reading this. The article and source code is on this website at /darkauth-1 and also at the bakery.

Hope you like it.

Comments:

Sorry, comments are closed.