cakephpでアクション別にアクセス権を設定してみた
Cakephp 2.2.1
ちょっと簡単なACLを以前実装してみてたのでその手順を。 コントローラーのアクション別にACLを割り当てる内容です。
acl.iniも同じ要領だと思いますが想像です。
app/Config/core.php
Configure::write('Acl.classname', 'PhpAcl');
初期でこういう記述があります。
$config['map'] = array(
'User' => 'User/username',
'Role' => 'User/group_id',
);
$config['alias'] = array(
'Role/4' => 'Role/editor',
);
$config['roles'] = array(
'Role/admin' => null,
);
$config['rules'] = array(
'allow' => array(
'*' => 'Role/admin',
),
'deny' => array(),
);
- $config['map']
'User/username' はユーザーモデルのusernameカラムを
'User/group_id' はユーザーモデルのgroup_idカラムを - $config['alias']
ここはスルーしてしまいました $config['roles']
権限を階層的に?$config['rules']
ここで設定するだけで!
と、いうわけでこんな設定にしました。
$config['map'] = array(
'User' => 'User/mailaddress',
'Role' => 'User/role',
);
$config['roles'] = array(
'Role/admin' => null,
'Role/staff' => null,
);
$config['rules']['allow'] = array(
'/*' => 'Role/admin',
'/pages/display' => 'Role/staff',
'/users/logout' => 'Role/staff',
'/posts/index' => 'Role/staff',
'/posts/search' => 'Role/staff',
'/posts/edit' => 'Role/staff',
'/posts/history' => 'Role/staff',
'/posts/view' => 'Role/staff',
'/users/profile' => 'Role/staff',
'/users/changepassword' => 'Role/staff',
);
まずDBにroleというカラムを追加しました。 ここには admin または staff という値が入ってます そして、スタッフのユーザーにはallowのアクションだけ許可するようにしてます。 逆にdenyでダメなアクションだけも有りかもしれません。
そしてコントローラー
AppController.php
public $components = array('Acl','Auth');
public function beforeFilter(){
if($this->Auth->loggedIn()){
$check_resource = $this->request->controller.DS.$this->request->action;
if(!$this->Acl->check(AuthComponent::user(),$check_resource)){
throw new MethodNotAllowedException();
}
if(AuthComponent::user('role')=='staff'){
$this->layout = 'staff';
}
}
}
ログイン中ならURLでACLチェック!
ちょっとした権限を付けたい時はいかかでしょうか。
$config['roles']を上手く使えば階層的なアクセス権もいけるんじゃないかと。
そのうち掘り下げたいと思います。