【问题标题】:How to remove permission from a role only for a particular user in spatie/laravel-permission?如何仅针对 spatie/laravel-permission 中的特定用户从角色中删除权限?
【发布时间】:2020-05-22 09:10:26
【问题描述】:

假设我的系统中有三个用户Sam、John 和Sarah。 这三个人都有editor 的角色,这使他们可以访问create article、edit article、publish article 和delete article。 现在由于某种原因,我不希望Sam 拥有delete article 的权限,但仍然拥有editor 的角色。

如何使用这个 spatie/laravel-permission 包在 Laravel 中实现这一点? (假设我可能需要定期进行此类操作,并且在一段时间后我可能会再次将delete article 分配回Sam。并且任何角色都有太多权限,所以我不能手动完成。)

【问题讨论】:

    标签: php laravel laravel-permission


    【解决方案1】:

    您可以创建自定义策略。

    在策略中,您为您的用户或用户组设置了例外。

    创建和保存您的策略。(https://laravel.com/docs/6.x/authorization#creating-policies)

    示例政策

    <?php
    
    namespace App\Policies;
    
    use App\User;
    use App\Article;
    use Illuminate\Auth\Access\HandlesAuthorization;
    
    class ArticlePolicy
    {
        use HandlesAuthorization;
    
    
        /**
         * Determine whether the user can delete the article.
         *
         * @param  \App\User $user
         * @param  \App\Post $post
         * @return mixed
         */
        public function delete(User $user, Article $article)
        {
            // retrieve the user as you wish.
            // I just did a check with his name but it is preferable to have a more 
            // advanced identification.
    
            if ($user->name = 'SAM')) {
                return false;
            }
    
            if ($user->can('delete article')) {
                return true;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2020-11-01
      • 2021-05-29
      • 1970-01-01
      相关资源
      最近更新 更多