2016-10-29 19 views
4

因此,我正在閱讀有關使用laravel策略向授權機構申請我的應用程序的資源,但似乎有一個問題,雖然我跟着教程。在store()方法中使用策略的this-> authorize()檢查laravel控制器

我有一個用戶模型,不能通過HTTP請求創建,除非其他用戶具有'Admin'或'Broker'角色的Entrust角色。我的理解,併成功使其像索引用戶的其他操作的工作是以下幾點:

  1. 私人$policies陣列內AuthServiceProvider.php裏面,我註冊了用戶級與UserPolicy類像

    類AuthServiceProvider延伸的ServiceProvider {

      protected $policies = [ 
    
          'App\Model' => 'App\Policies\ModelPolicy', 
           User::class => UserPolicy::class, 
           Insured::class => InsuredPolicy::class 
         ]; 
    
         public function boot(GateContract $gate) 
         { 
          $this->registerPolicies($gate); 
         } 
    

    }

  2. 定義UserPolicy控制器類

    類UserPolicy {

    use HandlesAuthorization; 
    
    protected $user; 
    
    public function __construct(User $user) { 
        $this->user = $user; 
    } 
    
    public function index(User $user) { 
        $is_authorized = $user->hasRole('Admin'); 
        return $is_authorized; 
    } 
    
    public function show(User $user, User $user_res) { 
    
        $is_authorized = ($user->id == $user_res->id); 
        return $is_authorized;  
    } 
    
    public function store() { 
        $is_authorized = $user->hasRole('Admin'); 
        return $is_authorized; 
    } 
    

    }

  3. 然後我使用this->authorize()檢查以制止或取決於特權進行的UserController類中,在執行關鍵動作之前的用戶

    class UserController extends Controller {

    public function index() 
    { 
        //temporary authentication here 
        $users = User::all(); 
        $this->authorize('index', User::class); 
        return $users; 
    } 
    
    public function show($id) 
    { 
        $user = User::find($id); 
        $this->authorize('show', $user); 
        return $user; 
    } 
    
    public function store(Request $request) { 
    
    
        $user = new User; 
        $user->name = $request->get('name'); 
        $user->email = $request->get('email'); 
        $user->password = \Hash::make($request->get('password')); 
    
        $this->authorize('store', User::class); 
    
        $user->save(); 
    
        return $user; 
    
    } 
    

    }

問題$this->authorize()始終停止在商店動作異常返回的過程:這個動作是未經授權的。

我嘗試多種變化的授權()的參數並不能得到它像索引操作

回答

1

store()UserPolicy::class功能你是不是傳遞用戶模型對象工作:

public function store(User $user) { 
    $is_authorized = $user->hasRole('Admin'); 
    return true; 
} 

缺少參數User $user

也許這是問題的原因。

+0

解決了!我確實記得我嘗試過在這個方法之前傳遞參數,並且當時沒有工作。非常感謝 –

+0

樂意提供幫助,歡迎來到Stack Overflow。如果此答案解決了您的問題,請將其標記爲已接受。 –