navaint1876/gf-identity

1.4 2019-09-18 10:21 UTC

This package is auto-updated.

Last update: 2024-09-18 21:55:40 UTC


README

GF Identity 可复用包

此包用于 EVA 微服务的访问管理。

用法

EvaGuard 是一个特质,用于通过角色检查访问权限,并且可能通过 VoterInterface 的实例提供的附加自定义逻辑进行访问。

用法

在控制器中,我们使用表达式 use EvaGuard; 导入 EvaGuard。然后我们可以在任何操作或 checkAccess() 方法中使用其功能,例如

self::denyAccessUnlessGranted('ROLE_ADMIN');

VoterInterface 接口代表决定是否授予用户访问权限的决策点。可以在实现此接口的类中添加一些逻辑和条件,以检查附加要求。

可以将实例传递给 NavaINT1876\GfIdentity\EvaGuard::denyAccessUnlessGranted() 作为第二个参数,并将 $params 作为第三个参数。

用法示例

 public function checkAccess($action, $model = null, $params = [])
 {
     if ('index' === $action) {
         self::denyAccessUnlessGranted('ROLE_ADMIN');
     }

     if ('view' === $action || 'update' === $action) {
         self::denyAccessUnlessGranted('ROLE_USER', UserVoter::class, ['model' => $model, 'action' => $action]);
     }
 }

投票者示例

 namespace app\modules\v1\voters;

 use Yii;
 use yii\web\ForbiddenHttpException;

 class UserVoter implements VoterInterface
 {
     const ACTION_VIEW = 'view';

     const ACTION_EDIT = 'update';

     const ACTIONS = [
         self::ACTION_VIEW,
         self::ACTION_EDIT,
     ];

     private $params;

     public function __construct(array $params)
     {
         $this->params = $params;
     }

     public function decide(): void
     {
         $action = $this->params['action'];
         $subject = $this->params['model'];
         $currentUser = Yii::$app->identity->getUser();

         if ($currentUser->id === $subject->id && in_array($action, self::ACTIONS)) {
             return;
         }

         throw new ForbiddenHttpException('You do not have permission to view/edit this user details.');
     }
}