`
sbguh
  • 浏览: 48428 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
最近访客 更多访客>>
社区版块
存档分类
最新评论

cakephp中acl和auth详解

阅读更多

自学习cakephp 以来,一直没有完成搞懂acl,也查过了很多资料,但对它的用法也是一知半解,acl应该是cakephp中一个比较难懂的地方,这几天又重新看了下手册,发现acl没有相信中的难,但比我想象中的好用.欢迎大家转载和访问我的网站http://www.batterylaptops.co.uk
下面让我说说它的具体用法已经使用过程中应该注意到问题
准备前工作:
最好是能配置好bake,使bake命名有效,虽然这个不是必须的,不过有这个命令行工具以后我们会方便很多
在你的数据库 中导入下面的sql语句

  1. CREATE TABLE users (
  2.     id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  3.         username VARCHAR(255) NOT NULL UNIQUE,
  4.     password CHAR(40) NOT NULL,
  5.     group_id INT(11) NOT NULL,
  6.     created DATETIME,
  7.     modified DATETIME
  8. );


  9. CREATE TABLE groups (
  10.     id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  11.     name VARCHAR(100) NOT NULL,
  12.     created DATETIME,
  13.     modified DATETIME
  14. );


  15. CREATE TABLE posts (
  16.     id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  17.     user_id INT(11) NOT NULL,
  18.     title VARCHAR(255) NOT NULL,
  19.     body TEXT,
  20.     created DATETIME,
  21.     modified DATETIME
  22. );

  23. CREATE TABLE widgets (
  24.     id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  25.     name VARCHAR(100) NOT NULL,
  26.     part_no VARCHAR(12),
  27.     quantity INT(11)
  28. );

在这里我们使用cake bake all命令工具快速生成models, controllers, 和 views(在这里我就详细介绍怎么使用cakephp中的bake命令了)


下一步,准备使用auth组件认证
首先我们打开users_controller.php在UsersController类中增加登录登出动作

  1. function login() {
  2.     //Auth Magic
  3. }

  4. function logout() {
  5.     //Leave empty for now.
  6. }
  7. 然后创建视图文件 app/views/users/login.ctp
  8. <?php
  9. $session->flash('auth');
  10. echo $form->create('User', array('action' => 'login'));
  11. echo $form->inputs(array(
  12.         'legend' => __('Login', true),
  13.         'username',
  14.         'password'
  15. ));
  16. echo $form->end('Login');

  17. ?>

下一步我们需要修改AppController(/app/app_controller.php),如果你的app目录下面没有app_controller.php文件的话,你可以自己创建一个

  1. <?php
  2. class AppController extends Controller {
  3.     var $components = array('Acl', 'Auth');

  4.     function beforeFilter() {
  5.         //Configure AuthComponent
  6.         $this->Auth->authorize = 'actions';
  7.         $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
  8.         $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
  9.         $this->Auth->loginRedirect = array('controller' => 'posts', 'action' => 'add');
  10.     }
  11. }
  12. ?>

接下来我们需要修改GroupsController和UsersController,这两个文件的目录大家应该都知道在哪里吧..
在这两个控制器中分别添加以下代码

  1. function beforeFilter() {
  2.     parent::beforeFilter();
  3.     $this->Auth->allowedActions = array('*');
  4. }

其实这段代码的意思是允许用户访问所有user和group下的action,当然这个后面是要改回来的

接下来我们要初始化acl表
因为现在我们的数据 库中就只有四个表,还没有导入acl表
我们用下面语句导入acl表到数据库中
在命令行中输入cake schema run create DbAcl

我们根据提示导入表

接下来我们需要修改user和group模型
首先我们打开model目录下的user.php增加以下代码(事实上你可以用下面代码替换)

  1. var $name = 'User';
  2. var $belongsTo = array('Group');
  3. var $actsAs = array('Acl' => 'requester');

  4. function parentNode() {
  5.     if (!$this->id && empty($this->data)) {
  6.         return null;
  7.     }
  8.     $data = $this->data;
  9.     if (empty($this->data)) {
  10.         $data = $this->read();
  11.     }
  12.     if (!$data['User']['group_id']) {
  13.         return null;
  14.     } else {
  15.         return array('Group' => array('id' => $data['User']['group_id']));
  16.     }
  17. }
复制代码

然后修改group模型

  1. var $actsAs = array('Acl' => array('requester'));

  2. function parentNode() {
  3.     return null;
  4. }

好 了,到这一步我们需要暂时停一下了,现在在浏览器中打开相应的user和group页面,增加user和group,比如我的,我打开 http://localhost/cakephp/groups增加组,打开http://localhost/cakephp/users/ 增加用户,在这里我们增加三个组和三个用户

添加完以后你可以打开phpmyadmin看下aros表看下是不是多了些记录

是不是觉得很神奇不可思议啊,哈哈,这就是框架的魅力,到目前为止和acl有关的表,就只有aros表中存在记录

在我们以后修改每一个user用户时,我们也必须修改aros表记录
所有我们应该做user模型中增加下面代码

  1. /**   
  2. * After save callback
  3. *
  4. * Update the aro for the user.
  5. *
  6. * @access public
  7. * @return void
  8. */
  9. function afterSave($created) {
  10.         if (!$created) {
  11.             $parent = $this->parentNode();
  12.             $parent = $this->node($parent);
  13.             $node = $this->node();
  14.             $aro = $node[0];
  15.             $aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
  16.             $this->Aro->save($aro);
  17.         }
  18. }

到这里我们aro创建已经完成,接下来我们应该创佳aco了
我们应该知道其实acl的本质是用来定义一个ARO在什么时候可以访问一个aco的组件,明白了这一点一切就变的很简单了。
为了简单我们使用命令行执行cake acl create aco root controllers

你现在再用phpmyadmin打开acors表,你应该会看到表中已经有一条记录了,这条记录就是刚刚执行这个命令的结果,当然我们不一定非得用命令行工具的。

接下来我们还需要修改下AppController,在里面的beforeFilter方法中我们需要增加一行$this->Auth->actionPath = 'controllers/';

下面是重点,在我们的app项目中可能会存在很多的控制器和方法,我们需要把每个action都添加到acors表中来实现权限控制,当然如果你不怕麻烦的话可以一个一个手动添加,但我想大多数程序员还是很懒的,所有我们这里需要使用自动生成工具

这里我们添加下面代码放在users_controller.php中,当然你也可以放在其他的控制器中
下面我就在users_controller.php中增加下面代码

  1. function build_acl() {
  2.                 if (!Configure::read('debug')) {
  3.                         return $this->_stop();
  4.                 }
  5.                 $log = array();

  6.                 $aco =& $this->Acl->Aco;
  7.                 $root = $aco->node('controllers');
  8.                 if (!$root) {
  9.                         $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
  10.                         $root = $aco->save();
  11.                         $root['Aco']['id'] = $aco->id;
  12.                         $log[] = 'Created Aco node for controllers';
  13.                 } else {
  14.                         $root = $root[0];
  15.                 }   

  16.                 App::import('Core', 'File');
  17.                 $Controllers = Configure::listObjects('controller');
  18.                 $appIndex = array_search('App', $Controllers);
  19.                 if ($appIndex !== false ) {
  20.                         unset($Controllers[$appIndex]);
  21.                 }
  22.                 $baseMethods = get_class_methods('Controller');
  23.                 $baseMethods[] = 'buildAcl';

  24.                 $Plugins = $this->_getPluginControllerNames();
  25.                 $Controllers = array_merge($Controllers, $Plugins);

  26.                 // look at each controller in app/controllers
  27.                 foreach ($Controllers as $ctrlName) {
  28.                         $methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

  29.                         // Do all Plugins First
  30.                         if ($this->_isPlugin($ctrlName)){
  31.                                 $pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
  32.                                 if (!$pluginNode) {
  33.                                         $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
  34.                                         $pluginNode = $aco->save();
  35.                                         $pluginNode['Aco']['id'] = $aco->id;
  36.                                         $log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
  37.                                 }
  38.                         }
  39.                         // find / make controller node
  40.                         $controllerNode = $aco->node('controllers/'.$ctrlName);
  41.                         if (!$controllerNode) {
  42.                                 if ($this->_isPlugin($ctrlName)){
  43.                                         $pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
  44.                                         $aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
  45.                                         $controllerNode = $aco->save();
  46.                                         $controllerNode['Aco']['id'] = $aco->id;
  47.                                         $log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
  48.                                 } else {
  49.                                         $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
  50.                                         $controllerNode = $aco->save();
  51.                                         $controllerNode['Aco']['id'] = $aco->id;
  52.                                         $log[] = 'Created Aco node for ' . $ctrlName;
  53.                                 }
  54.                         } else {
  55.                                 $controllerNode = $controllerNode[0];
  56.                         }

  57.                         //clean the methods. to remove those in Controller and private actions.
  58.                         foreach ($methods as $k => $method) {
  59.                                 if (strpos($method, '_', 0) === 0) {
  60.                                         unset($methods[$k]);
  61.                                         continue;
  62.                                 }
  63.                                 if (in_array($method, $baseMethods)) {
  64.                                         unset($methods[$k]);
  65.                                         continue;
  66.                                 }
  67.                                 $methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
  68.                                 if (!$methodNode) {
  69.                                         $aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
  70.                                         $methodNode = $aco->save();
  71.                                         $log[] = 'Created Aco node for '. $method;
  72.                                 }
  73.                         }
  74.                 }
  75.                 if(count($log)>0) {
  76.                         debug($log);
  77.                 }
  78.         }

  79.         function _getClassMethods($ctrlName = null) {
  80.                 App::import('Controller', $ctrlName);
  81.                 if (strlen(strstr($ctrlName, '.')) > 0) {
  82.                         // plugin's controller
  83.                         $num = strpos($ctrlName, '.');
  84.                         $ctrlName = substr($ctrlName, $num+1);
  85.                 }
  86.                 $ctrlclass = $ctrlName . 'Controller';
  87.                 $methods = get_class_methods($ctrlclass);

  88.                 // Add scaffold defaults if scaffolds are being used
  89.                 $properties = get_class_vars($ctrlclass);
  90.                 if (array_key_exists('scaffold',$properties)) {
  91.                         if($properties['scaffold'] == 'admin') {
  92.                                 $methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
  93.                         } else {
  94.                                 $methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
  95.                         }
  96.                 }
  97.                 return $methods;
  98.         }

  99.         function _isPlugin($ctrlName = null) {
  100.                 $arr = String::tokenize($ctrlName, '/');
  101.                 if (count($arr) > 1) {
  102.                         return true;
  103.                 } else {
  104.                         return false;
  105.                 }
  106.         }

  107.         function _getPluginControllerPath($ctrlName = null) {
  108.                 $arr = String::tokenize($ctrlName, '/');
  109.                 if (count($arr) == 2) {
  110.                         return $arr[0] . '.' . $arr[1];
  111.                 } else {
  112.                         return $arr[0];
  113.                 }
  114.         }

  115.         function _getPluginName($ctrlName = null) {
  116.                 $arr = String::tokenize($ctrlName, '/');
  117.                 if (count($arr) == 2) {
  118.                         return $arr[0];
  119.                 } else {
  120.                         return false;
  121.                 }
  122.         }

  123.         function _getPluginControllerName($ctrlName = null) {
  124.                 $arr = String::tokenize($ctrlName, '/');
  125.                 if (count($arr) == 2) {
  126.                         return $arr[1];
  127.                 } else {
  128.                         return false;
  129.                 }
  130.         }

  131. /**
  132. * Get the names of the plugin controllers ...
  133. *
  134. * This function will get an array of the plugin controller names, and
  135. * also makes sure the controllers are available for us to get the
  136. * method names by doing an App::import for each plugin controller.
  137. *
  138. * @return array of plugin names.
  139. *
  140. */
  141.         function _getPluginControllerNames() {
  142.                 App::import('Core', 'File', 'Folder');
  143.                 $paths = Configure::getInstance();
  144.                 $folder =& new Folder();
  145.                 $folder->cd(APP . 'plugins');

  146.                 // Get the list of plugins
  147.                 $Plugins = $folder->read();
  148.                 $Plugins = $Plugins[0];
  149.                 $arr = array();

  150.                 // Loop through the plugins
  151.                 foreach($Plugins as $pluginName) {
  152.                         // Change directory to the plugin
  153.                         $didCD = $folder->cd(APP . 'plugins'. DS . $pluginName . DS . 'controllers');
  154.                         // Get a list of the files that have a file name that ends
  155.                         // with controller.php
  156.                         $files = $folder->findRecursive('.*_controller\.php');

  157.                         // Loop through the controllers we found in the plugins directory
  158.                         foreach($files as $fileName) {
  159.                                 // Get the base file name
  160.                                 $file = basename($fileName);

  161.                                 // Get the controller name
  162.                                 $file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
  163.                                 if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
  164.                                         if (!App::import('Controller', $pluginName.'.'.$file)) {
  165.                                                 debug('Error importing '.$file.' for plugin '.$pluginName);
  166.                                         } else {
  167.                                                 /// Now prepend the Plugin name ...
  168.                                                 // This is required to allow us to fetch the method names.
  169.                                                 $arr[] = Inflector::humanize($pluginName) . "/" . $file;
  170.                                         }
  171.                                 }
  172.                         }
  173.                 }
  174.                 return $arr;
  175.         }

增加好以后我们打开浏览器访问刚才的方法
比如我的http://localhost/cakephp/users/build_acl
运行后程序会自动把所有controller下的action都添加到acos表中,你现在打开acos表应该就会看到很多记录了,如


接下来应该是做我们最兴奋的事情了,就是实现权限控制,因为我们前期准备工作都做好了,最终我们都是为了实现可以控制权限

1.        先来介绍下语法,允许访问$this->Acl->allow($aroAlias, $acoAlias);
拒绝访问$this->Acl->deny($aroAlias, $acoAlias);

你先打开aros_acos表中看下,到目前为止该表应该还是没有记录的
我们可以写一个初始化函数
我同样把这段代码放在user控制器中

  1. function initDB() {
  2.     $group =& $this->User->Group;
  3.     //Allow admins to everything
  4.     $group->id = 1;     
  5.     $this->Acl->allow($group, 'controllers');

  6.     //allow managers to posts and widgets
  7.     $group->id = 2;
  8.     $this->Acl->deny($group, 'controllers');
  9.     $this->Acl->allow($group, 'controllers/Posts');
  10.     $this->Acl->allow($group, 'controllers/Widgets');

  11.     //allow users to only add and edit on posts and widgets
  12.     $group->id = 3;
  13.     $this->Acl->deny($group, 'controllers');        
  14.     $this->Acl->allow($group, 'controllers/Posts/add');
  15.     $this->Acl->allow($group, 'controllers/Posts/edit');        
  16.     $this->Acl->allow($group, 'controllers/Widgets/add');
  17.     $this->Acl->allow($group, 'controllers/Widgets/edit');
  18. }

接下来我们在浏览器中访问这个action

这个是时候你就应该发现你的aros_acos表中多了很多条记录,哈哈,这个就是acl的秘密所在.

接下来你可以使用不同组的用户名登录访问,你还可以修改initDB里面的代码进行测试,至于实际工作中如何使用,那就要看你自己的了,最后祝大家工作愉快!最后我把文档放在这里,有兴趣的朋友可以下载 cakephp中acl详解.rar

转载自: Batterylaptops

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics