Policies
Policies は与えられたオブジェクトの権限を解決するクラスです。
Policies を作成する
src/Policy ディレクトリに policy を作成します。解決方法については ポリシーリゾルバー を参照してください。
php
<?php
namespace App\Policy;
use App\Model\Entity\Article;
use Authorization\IdentityInterface;
class ArticlePolicy
{
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
クエリやテーブルにも policy を定義できます。
bash
bin/cake bake policy --type entity Article
bin/cake bake policy --type table Articles1
2
2
ポリシーメソッドの書き方
php
public function canUpdate(IdentityInterface $user, Article $article)
{
return $user->id == $article->user_id;
}1
2
3
4
2
3
4
ポリシーの Result オブジェクト
php
use Authorization\Policy\Result;
public function canUpdate(IdentityInterface $user, Article $article)
{
if ($user->id == $article->user_id) {
return new Result(true);
}
return new Result(false, 'not-owner');
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
ポリシーのスコープ
php
namespace App\Policy;
class ArticlesTablePolicy
{
public function scopeIndex($user, $query)
{
return $query->where(['Articles.user_id' => $user->getIdentifier()]);
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
ポリシーの前提条件
php
namespace App\Policy;
use Authorization\IdentityInterface;
use Authorization\Policy\BeforePolicyInterface;
use Authorization\Policy\ResultInterface;
class ArticlesPolicy implements BeforePolicyInterface
{
public function before(?IdentityInterface $identity, mixed $resource, string $action): ResultInterface|bool|null
{
if ($identity->getOriginalData()->is_admin) {
return true;
}
return null;
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17