|  | 指定权限
现在 Tor 有多个表示用户的 ARO,并可以创建表示产品的 ACO(按经销商分组)。现在需要通过定义一些权限来整合它们。
权限的工作方式
我们将明确定义哪些人有权对产品执行操作。通过明确允许 ARO(本例中为用户)具有对 ACO(本例中为产品)和一个操作的权限来完成这项任务。操作可以是读取(意味着用户可以查看数据库信息)、创建(用户可以将信息插入数据库中)、更新(用户可以修改信息)、删除(用户可以从数据库中删除信息)或者 *(意味着用户可以执行所有操作)。每个操作都必须单独授权;允许删除并不意味着允许创建或查看。
默认情况下,在检查权限时,如果没有定义权限,则 CakePHP 假定权限为 DENY。
定义策略
定义权限策略不仅仅是编写和执行代码。需要考虑 ACL 实际上要完成哪些功能。如果没有清楚地了解需要阻止哪些人执行哪些操作,就会发现经常需要重新定义权限。
Tor 有用户和产品。为了实现本教程的目的,将允许创建产品的用户具有完全权限,可以编辑和删除产品。任何用户都能够查看产品,除非明确拒绝访问。
在产品 add 函数中添加权限定义
Tor 需要知道在创建产品时如何指定权限。这可以通过在控制器中添加两行来完成。一行用于为用户添加查看权限,另一行用于为创建产品的用户添加完全权限。授予权限的语句如下所示:$this->Acl->allow(ARO, ACO, TYPE);。
如果不指定一种 TYPE(create、read、update 或 delete),则 CakePHP 将假定您要授予完全权限。products 控制器中新的 add 函数应当类似于清单 16:
清单 16. products 控制器中新的 add 函数
function add() {if (!empty($this->data)) {
$this->cleanUpFields();
$this->Product->create();
if ($this->Product->save($this->data)) {
$dealer = $this->Product->Dealer->read(null,
$this->data['Product']['dealer_id']);
$parent = $this->Acl->Aco->findByAlias($dealer
['Dealer']['title']);
$this->Acl->Aco->create(array(
'alias' => $this->Product->id.'-'.$this->data
['Product']['title'],
'model' => 'Product',
'foreign_key' => $this->Product->id,
'parent_id' => $parent['Aco']['id'])
);
$this->Acl->Aco->save();
$this->Acl->allow('Users',
$this->Product->id.'-'.$this->data['Product']['title'],
'read');
$this->Acl->allow($this->Session->read('user'),
$this->Product->id.'-'.$this->data['Product']
['title'],'*');
$this->Session->setFlash('The Product has been saved');
$this->redirect(array('action'=>'index'), null, true);
} else {
$this->Session->setFlash('The Product could not be saved.
Please, try again.');
}
}
$dealers = $this->Product->Dealer->generateList();
$this->set(compact('dealers'));
}
|
OK — 现在可以添加一些产品。作为某一用户登录并添加几个产品,只要看看整个过程有没有问题即可。可以使用 Cake Console 查看在添加新产品时创建的 ACO。现在差不多完成了。已经定义了 ARO、ACO 并指定了权限。现在,在执行与产品相关的各种操作时,Tor 都需要检查权限。
|  |
|