2017-03-08 7 views
0

私はユーザーが存在し、ユーザーには多くのユーザー役割を持つシステムを作成しています。ユーザーロールにもアクセス許可が含まれています。一部のフィールドは保護されているため、ユーザーが特定の権限を持っていなければ上書きできません。ユーザーロールに基づいてLaravel stopモーダル属性が更新されています

たとえば、ユーザーが「電子メール」という属性を持つことができます。この属性は、ユーザーが「update-email-address」というアクセス許可を持っていない限り変更できません。

私は当初、このコンセプトを特性や抽象クラスとして実装しようとしていましたが、Eloquent Modelコンストラクタメソッドをオーバーロードしたり、別のメソッドを完全にオーバーロードしたりすることを伴わない方法を考え出すことはできません。私がやることを望んだ何

、以下のようなモデルで配列を指定し、管または拡張子を使用することによって、何とかモデル属性の更新を防ぐことができるようにすることです:

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

これを達成する方法はありますか?

+0

POST/PUT要求にミドルウェアを追加してから、コントローラ/モデルにキーが送信されないように要求を変更できます。 – Ian

+0

@ian私の状況では、更新可能な属性や、指定されたユーザー権限に基づくことができない属性が存在する可能性があります。私は解決策に私を導いた何かにつまずいた、私はそれを下に与えた – kirgy

+1

ああ、私は理解していないようだ、あなたのソリューションを投稿していただきありがとうございます。 – Ian

答えて

1

私はモデルを拡張する形質についてのブート方法を提供する方法に出くわして、次を介してこれを達成することができました。多くの雄弁モデルに使用

形質:

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'], 
    ]; 
} 
関連する問題