【问题标题】:Laravel stop modal attribute being updated based on user roleLaravel 停止模式属性根据用户角色更新
【发布时间】:2017-03-08 14:14:58
【问题描述】:

我正在创建一个系统,其中有用户,并且用户有许多用户角色。用户角色还包含权限。某些字段受到保护,因此在没有用户拥有特定权限的情况下无法覆盖它们。

例如,一个用户可能有一个属性“email”,该属性不能被用户更改,除非用户拥有“update-email-address”权限。

我原本打算将这个概念实现为特征或抽象类,但我想不出一种不涉及重载 Eloquent Model 构造函数方法或完全重载​​另一个方法的方法。

我希望做的是能够在如下模型中指定一个数组,并通过使用 tract 或 extension,以某种方式阻止更新模型属性:

/**
 * The attributes that should only be updatable by given user with the 
 * specified permission
 *
 */    
public $update_only_by_permission = [
    'email'          => ['update-email-address'], 
];

有没有办法做到这一点?

【问题讨论】:

  • 您可以在 POST/PUT 请求上添加一个中间件,然后修改请求,使密钥永远不会发送到控制器/模型。
  • @ian 在我的情况下,根据给定的用户权限,可能有一些属性可以更新,而另一些则不能。我偶然发现了一些导致我找到解决方案的东西,我在下面给出了它,
  • 啊,我好像理解错了,谢谢你发布你的解决方案。

标签: php laravel laravel-5.3


【解决方案1】:

我偶然发现了一种为扩展模型的特征提供引导方法的方法,并且能够通过以下方式实现此目的:

用于许多 Eloquent 模型的特征:

use Auth;
trait AttributeVisibleByPermissionTrait {

    /**
    *   Stops updating of the object attributes if the authenticated 
    *   user does not have the given permission provided in the 
    *   $object->update_only_by_permission array.
    */
    public static function bootAttributeVisibleByPermissionTrait(){

        static::updating(function($object){ 
            foreach ($object->update_only_by_permission as $attribute => $permissions) {
                foreach ($permissions as $permission) {
                    if(!Auth::User()->can($permission)) {
                        unset($object->$attribute);
                    }
                }
            }
        });

    }
}

用户模型:

class User extends Authenticatable
{
    use AttributeVisibleByPermissionTrait;
    /**
     * The attributes that should only be updated by given user auth permissions
     *
     * @var array
     */    
    public $update_only_by_permission = [
        'email'              => ['update-email-address'], 
    ];
}

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多