如何在Laravel 5.3中执行授权策略?

时间:2017-03-04 17:11:00

标签: php laravel authorization laravel-5.3 policies

我在这里阅读:https://laravel.com/docs/5.3/authorization#writing-policies

我试着喜欢这个

My FavoritePolicy是这样的:

<?php
namespace App\Policies;
use App\User;
use App\Models\Favorite;
use Illuminate\Auth\Access\HandlesAuthorization;
class FavoritePolicy
{
    use HandlesAuthorization;
    public function view(User $user, Favorite $favorite)
    {
        return $user->id === $favorite->user_id;
    }
}

我的FavoriteController是这样的:

<?php
use App\Models\Favorite;
...
class FavoriteController extends ApiController
{
    ...
    public function index(Favorite $favorite)
    {
        $this->authorize('view', $favorite);
        return view('profile.favorite');
    }
}

我的AuthServiceProvider是这样的:

<?php
namespace App\Providers;
use App\Models\Favorite;
use App\Policies\FavoritePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Favorite::class => FavoritePolicy::class,
    ];
    public function boot()
    {
        $this->registerPolicies();
    }
}

当我运行系统显示收藏列表时,会出现如下错误:

  

糟糕,看起来出了问题。

     

Handler.php第115行中的1/1 HttpException:此操作为   未经授权的

授权政策的实施是正确的?

我在view方法(FavoritePolicy)中尝试dd($user),结果显示正在记录用户数据。这是真的

但是我尝试dd($favorite),结果不会显示当前登录用户的收藏数据。我检查表格时,当前登录的用户的最喜欢的数据是存在的

我该如何解决这个问题?

更新

dd($favorite)

的结果
Favorite {#498 ▼
  #fillable: array:3 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
}

1 个答案:

答案 0 :(得分:1)

感谢您提供更新中的其他信息!

那么,您想要显示一个特定Favorite实体的详细信息页面,但前提是用户是该实体的所有者?

首先是一个次要的“问题”:通常在Laravel中,显示特定实体细节的控制器方法称为show,而不是indexindex是显示实体列表的方法的名称(在您的示例中:收藏列表)。

关于你的问题:
您的策略会检查当前登录的用户是否可以查看空的$favorite(请参阅更新后的dd($favorite)输出)。这意味着,$favorite方法中也未设置index

我想,你的路线定义与此相似:

Route::get('favorite/{id}', 'FavoriteController@index');

这意味着id的值作为参数注入到index方法中,而不是Favorite实体。要查询Favorite实体,您需要在方法中执行此操作。

所以,你的方法应该更像这样:

public function index($favoriteId)
{
    $favorite = Favorite::findOrFail($favoriteId);
    $this->authorize('view', $favorite);
    return view('profile.favorite')->with('favorite', $favorite);
}

希望有所帮助!如果没有,请添加评论!

相关问题