【CakePHP1.3】_ACL和auth

准备前工作:

最好是能配置好bake,使bake命名有效,虽然这个不是必须的,不过有这个命令行工具以后我们会方便很多

在你的数据库中导入下面的sql语句


CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
	username VARCHAR(255) NOT NULL UNIQUE,
    password CHAR(40) NOT NULL,
    group_id INT(11) NOT NULL,
    created DATETIME,
    modified DATETIME
);

 
CREATE TABLE groups (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    created DATETIME,
    modified DATETIME
);


CREATE TABLE posts (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    user_id INT(11) NOT NULL,
    title VARCHAR(255) NOT NULL,
    body TEXT,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE widgets (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    part_no VARCHAR(12),
    quantity INT(11)
);

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

【CakePHP1.3】_ACL和auth_第1张图片

下一步,

准备使用auth组件认证

首先我们打开users_controller.php在UsersController类中增加登录登出动作

function login() {
    //Auth Magic
}
 
function logout() {
    //Leave empty for now.
}
然后创建视图文件app/views/users/login.ctp
<?php
$session->flash('auth');
echo $form->create('User', array('action' => 'login'));
echo $form->inputs(array(
	'legend' => __('Login', true),
	'username',
	'password'
));
echo $form->end('Login');

?>

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

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

    function beforeFilter() {
        //Configure AuthComponent
        $this->Auth->authorize = 'actions';
        $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
        $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
        $this->Auth->loginRedirect = array('controller' => 'posts', 'action' => 'add');
    }
}
?>

接下来我们需要修改GroupsController和UsersController,这两个文件的目录大家应该都知道在哪里吧..

在这两个控制器中分别添加以下代码

function beforeFilter() {
    parent::beforeFilter(); 
    $this->Auth->allowedActions = array('*');
}

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

接下来我们要初始化acl

因为现在我们的数据库中就只有四个表,还没有导入acl

我们用下面语句导入acl表到数据库中

在命令行中输入cake schema  create DbAcl

【CakePHP1.3】_ACL和auth_第2张图片

我们根据提示导入表

接下来我们需要修改usergroup模型

首先我们打开model目录下的user.php增加以下代码(事实上你可以用下面代码替换)

var $name = 'User';
var $belongsTo = array('Group');
var $actsAs = array('Acl' => 'requester');
 
function parentNode() {
    if (!$this->id && empty($this->data)) {
        return null;
    }
    $data = $this->data;
    if (empty($this->data)) {
        $data = $this->read();
    }
    if (!$data['User']['group_id']) {
        return null;
    } else {
        return array('Group' => array('id' => $data['User']['group_id']));
    }
}
然后修改group模型

var $actsAs = array('Acl' => array('requester'));
 
function parentNode() {
    return null;
}

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

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

到目前为止和acl有关的表,就只有aros表中存在记录

在我们以后修改每一个user用户时,我们也必须修改aros表记录

所有我们应该做user模型中增加下面代码

/**    
 * After save callback
 *
 * Update the aro for the user.
 *
 * @access public
 * @return void
 */
function afterSave($created) {
        if (!$created) {
            $parent = $this->parentNode();
            $parent = $this->node($parent);
            $node = $this->node();
            $aro = $node[0];
            $aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
            $this->Aro->save($aro);
        }
}

到这里我们aro创建已经完成,

接下来我们应该创建aco

我们应该知道其实acl的本质是用来定义一个ARO在什么时候可以访问一个aco的组件,明白了这一点一切就变的很简单了

为了简单我们使用命令行执行cake acl create aco root controllers

【CakePHP1.3】_ACL和auth_第3张图片

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

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

下面是重点,在我们的app项目中可能会存在很多的控制器和方法,我们需要把每个action都添加到acors表中来

实现权限控制,

当然如果你不怕麻烦的话可以一个一个手动添加,但我想大多数程序员还是很懒的,所有我们这里需要使用自动生成工具

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

下面我就在users_controller.php中增加下面代码

function build_acl() {
        if (!Configure::read('debug')) {
            return $this->_stop();
        }
        $log = array();

        $aco =& $this->Acl->Aco;
        $root = $aco->node('controllers');
        if (!$root) {
            $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
            $root = $aco->save();
            $root['Aco']['id'] = $aco->id; 
            $log[] = 'Created Aco node for controllers';
        } else {
            $root = $root[0];
        }   

        App::import('Core', 'File');
        $Controllers = Configure::listObjects('controller');
        $appIndex = array_search('App', $Controllers);
        if ($appIndex !== false ) {
            unset($Controllers[$appIndex]);
        }
        $baseMethods = get_class_methods('Controller');
        $baseMethods[] = 'buildAcl';

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

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

            // Do all Plugins First
            if ($this->_isPlugin($ctrlName)){
                $pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
                if (!$pluginNode) {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
                    $pluginNode = $aco->save();
                    $pluginNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
                }
            }
            // find / make controller node
            $controllerNode = $aco->node('controllers/'.$ctrlName);
            if (!$controllerNode) {
                if ($this->_isPlugin($ctrlName)){
                    $pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
                    $aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
                } else {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $ctrlName;
                }
            } else {
                $controllerNode = $controllerNode[0];
            }

            //clean the methods. to remove those in Controller and private actions.
            foreach ($methods as $k => $method) {
                if (strpos($method, '_', 0) === 0) {
                    unset($methods[$k]);
                    continue;
                }
                if (in_array($method, $baseMethods)) {
                    unset($methods[$k]);
                    continue;
                }
                $methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
                if (!$methodNode) {
                    $aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
                    $methodNode = $aco->save();
                    $log[] = 'Created Aco node for '. $method;
                }
            }
        }
        if(count($log)>0) {
            debug($log);
        }
    }

    function _getClassMethods($ctrlName = null) {
        App::import('Controller', $ctrlName);
        if (strlen(strstr($ctrlName, '.')) > 0) {
            // plugin's controller
            $num = strpos($ctrlName, '.');
            $ctrlName = substr($ctrlName, $num+1);
        }
        $ctrlclass = $ctrlName . 'Controller';
        $methods = get_class_methods($ctrlclass);

        // Add scaffold defaults if scaffolds are being used
        $properties = get_class_vars($ctrlclass);
        if (array_key_exists('scaffold',$properties)) {
            if($properties['scaffold'] == 'admin') {
                $methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
            } else {
                $methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
            }
        }
        return $methods;
    }

    function _isPlugin($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) > 1) {
            return true;
        } else {
            return false;
        }
    }

    function _getPluginControllerPath($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0] . '.' . $arr[1];
        } else {
            return $arr[0];
        }
    }

    function _getPluginName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0];
        } else {
            return false;
        }
    }

    function _getPluginControllerName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[1];
        } else {
            return false;
        }
    }

/**
 * Get the names of the plugin controllers ...
 * 
 * This function will get an array of the plugin controller names, and
 * also makes sure the controllers are available for us to get the 
 * method names by doing an App::import for each plugin controller.
 *
 * @return array of plugin names.
 *
 */
    function _getPluginControllerNames() {
        App::import('Core', 'File', 'Folder');
        $paths = Configure::getInstance();
        $folder =& new Folder();
        $folder->cd(APP . 'plugins');

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

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

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

                // Get the controller name
                $file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
                if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
                    if (!App::import('Controller', $pluginName.'.'.$file)) {
                        debug('Error importing '.$file.' for plugin '.$pluginName);
                    } else {
                        /// Now prepend the Plugin name ...
                        // This is required to allow us to fetch the method names.
                        $arr[] = Inflector::humanize($pluginName) . "/" . $file;
                    }
                }
            }
        }
        return $arr;
    }

增加好以后我们打开浏览器访问刚才的方法

比如我的http://localhost/cakephp/users/build_acl

运行后程序会自动把所有controller下的action都添加到acos表中,你现在打开acos表应该就会看到很多记录了

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

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

拒绝访问$this->Acl->deny($aroAlias, $acoAlias);

你先打开aros_acos表中看下,到目前为止该表应该还是没有记录的

我们可以写一个初始化函数

我同样把这段代码放在user控制器中

function initDB() {
    $group =& $this->User->Group;
    //Allow admins to everything
    $group->id = 1;     
    $this->Acl->allow($group, 'controllers');
 
    //allow managers to posts and widgets
    $group->id = 2;
    $this->Acl->deny($group, 'controllers');
    $this->Acl->allow($group, 'controllers/Posts');
    $this->Acl->allow($group, 'controllers/Widgets');
 
    //allow users to only add and edit on posts and widgets
    $group->id = 3;
    $this->Acl->deny($group, 'controllers');        
    $this->Acl->allow($group, 'controllers/Posts/add');
    $this->Acl->allow($group, 'controllers/Posts/edit');        
    $this->Acl->allow($group, 'controllers/Widgets/add');
    $this->Acl->allow($group, 'controllers/Widgets/edit');
}

接下来我们在浏览器中访问这个initDBhttp://localhost/cakephp/users/initDB

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

接下来你可以使用不同组的用户名登录访问,你还可以修改initDB里面的代码进行测试,至于实际工作中如何使用,那就要看你自己的了,最后祝大家工作愉快!





你可能感兴趣的:(acl,cakephp)