2017-08-06 80 views
1

我现在正在与rbac yii2合作。 我定义了数据库中的所有角色和权限。 现在对我来说,问题是我应该在哪里检查访问规则? 例如,作者可以更新他自己的帖子。 我还在rule_name ='isAuthor'中保存了数据库中的规则。 但我对检查条件感到困惑,以访问自己的帖子。如何实现can()方法?

这里是我的actionRule:

<?php 
public function actionRule(){ 
    $auth = Yii::$app->authManager; 
    $rule = new \app\rbac\AuthorRule; 
    $auth->add($rule); 

    $updateMobile = $auth->createPermission('mobile/update'); 

    // add the "updateOwnMobile" permission and associate the rule with it. 
    $updateOwnMobile = $auth->createPermission('updateOwnMobile'); 
    $author = $auth->createPermission('author'); 
    $updateOwnMobile->description = 'Update own mobile'; 
    $updateOwnMobile->ruleName = $rule->name; 
    $auth->add($updateOwnMobile); 

    // "updateOwnMobile" will be used from "updatePost" 
    $auth->addChild($updateOwnMobile, $updateMobile); 

    // allow "author" to update their own posts 
    $auth->addChild($author, $updateOwnMobile); 
} 
?> 

在哪里,我怎么能实现呢? in Controller?行为? 或其他地方?

回答

0

在更新过的对笔者自己的岗位检查(can('author')法)的情况下,至少应该放在控制器有两个原因:

  1. 您应该检查不仅若使用具有作用/许可作者而且如果帖子的所有者是用户
  2. 一旦检查用户是否可以执行相关的代码,您必须驱动正确的响应(如果用户可以或渲染更新表单,否则拒绝访问信息)

这些是t ipically控制器/动作操作方法。

这些都只是一些建议,首先

0

理想情况下,你应该有与规则相关的一类(从Yii\rbac\Rule延伸)。然后执行execute函数,该函数检查用户是否是帖子的作者,并且他有权更新帖子。

事情是这样的:

class SiteRule extends Rule 
{ 

    //you can modify this to suit your needs. 
    public function execute($user, $item, $params) 
    { 
     //get user ie: \dektrium\user\models\User::findIdentity($user) 
     //check if the $user is the author - using defined author or created-by  attribute in $params. 
     //return true/false 
    } 
} 

然后在你的控制器/动作可以用CheckAccess()方法(yii\rbac\ManagerInterface),以检查用户是否有权访问:

if(\yii::$app->user->can('author', ['post'=>\Yii::$app->request->post()(or your model])) 
{//logic here}