Laravel - 我怎样才能避免用户看到不属于他们的内容(和关系)

Laravel - How can I avoid users to see content not owned by them (and relations)

在一个 Laravel 5.1 项目中我有:

Videos 属于 PagesPages 属于 用户。 我想确保用户不能访问不属于他们的视频和页面。管理员用户可以查看所有页面和视频。

如何解决?

我已经在使用中间件并将用户 ID 作为参数传递,但我不知道如何在视频构造器中获取用户 ID。 我可能需要 Constructor Injection 之类的东西,但文档不是很清楚。


编辑: 正如@tommy 所推荐的,我使用 Laravel 授权来检查用户是否有权限。 我决定使用单个存储库,因为检查总是相同的(与用户匹配的页面)

在\App\Providers\AuthServiceProvider

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    $gate->define('check-owner', function ($user, $page) {
        return $user->id === $page->user_id;
    });
}

在App\Repositories\OwnerRepository

namespace App\Repositories
use App\Page;
use Gate;
   class OwnerRepository
   {
      public function CheckifOwns(Page $page){
         if (Gate::denies('check-owner', $page)) 
         {
           abort(403, 'Unauthorized action.');
         }
      }
   }

在视频控制器中

use App\Repositories\OwnerRepository;
private $repository;

public function __construct(OwnerRepository $repository)
{
    $this->repository = $repository;
    $this->middleware('auth');
}

public function show($id)
{
    $video= Video::findOrFail($id);
    $this->repository->CheckifOwns($video->Page);
    return view('videos.view',compact('video'));
}

Laravel 5.1.11 引入了新的授权系统。您可以使用 Policies 轻松检查是否允许用户访问特定资源:

http://laravel.com/docs/5.1/authorization