发新话题
打印

CakePHP里如何实现每个用户管理(修改/删除)自己创建的内容

CakePHP里如何实现每个用户管理(修改/删除)自己创建的内容

作者:老王

CakePHP内置的权限处理模块是Auth/Acl组件,相对而言,在大部分时候,因为复杂性的关系,我不推荐使用Acl组件来管理权限,只要可能,尽量使用Auth来做,它完全能实现一般的权限管理。

Auth组件的使用有以下几种方式:

1. $this->Auth->authorize = 'controller':
复制内容到剪贴板
代码:
validate against Controller::isAuthorized() if controller instance is passed in $object
2. $this->Auth->authorize = 'actions':
复制内容到剪贴板
代码:
validate Controller::action against an AclComponent::check()
3. $this->Auth->authorize = 'crud':
复制内容到剪贴板
代码:
validate mapActions against an AclComponent::check()
4. $this->Auth->authorize = 'object':
复制内容到剪贴板
代码:
validate Controller::action against object::isAuthorized(user, controller, action)
这里假设一个常见的权限需求:每个用户仅可以管理(修改/删除)自己创建的内容。

我使用第一种方法解决,唉,代码改了好几遍才有了现在的样子,基本功能已经实现得不错了。
复制内容到剪贴板
代码:
<?php
class AppController extends Controller {

    var $helpers = array('Html', 'Form');

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

    function beforeFilter() {
        if (isset($this->Auth)) {
            $this->Auth->authorize = 'controller';
        }
    }

    function isAuthorized() {
        if (!array_key_exists($this->action, $this->Auth->actionMap)) {
            return true;
        }

        $crud = $this->Auth->actionMap[$this->action];

        if (!in_array($crud, array('update', 'delete'))) {
            return true;
        }

        if (!count($this->params['pass'])) {
            return true;
        }

        $model = $this->{$this->modelClass};

        foreach ($model->belongsTo as $association) {
            if ($association['className'] == $this->Auth->userModel) {
                $foreignKey = $association['foreignKey'];
            }

            break;
        }

        if (!isset($foreignKey)) {
            return true;
        }

        $schema = $model->schema();

        if ('integer' == $schema->value[$model->primaryKey]['type']) {
            $this->params['pass'][0] = intval($this->params['pass'][0]);
        }

        $model->recursive = -1;

        $data = $model->find(array(
            $model->name . '.' . $model->primaryKey => $this->params['pass'][0]
        ));

        if (!$model->getNumRows()) {
            return false;
        }

        if (array_key_exists($foreignKey, $data[$this->modelClass])) {
            $user = $this->Auth->getModel($this->Auth->userModel);

            if ($this->Auth->user($user->primaryKey)
                != $data[$this->modelClass][$foreignKey]) {

                return false;
            }
        }

        return true;
    }
}
?>
收工!

TOP

TOP

对不起,请问代码放在app目录下吗?

TOP

引用:
原帖由 phpx 于 2007-11-30 20:51 发表
对不起,请问代码放在app目录下吗?
恩,是的。CakePHP允许自定义AppController的内容,把上面代码保存为app_controller.php文件放在app目录就ok了。

TOP

非常感谢

TOP

发新话题