只有经过认证的用户才能访问的模型创建他们(Laravel)

时间:2016-09-09 08:23:43

标签: laravel authentication laravel-5 repository repository-pattern

我正在编写一个软件应用程序,让人们拥有自己的烹饪食谱私人档案。

RecipeController 构造函数包含:

$this->middleware('auth') 

因为只有注册用户可以使用食谱,但我还需要保护对模型的访问

关键是用户只能查看和修改自己的食谱

示例:用户TortelliEngineer可以使用模型 Recipe 创建食谱“Tortelli Secret Recipe”;他可以查看,更新和删除他的食谱,但没有其他人能看到他珍贵的“Tortelli Secret Recipe”。

那么,这是最干净的方式?

  • 我在模型食谱中添加了 user_id 属性。
  • 每次我向数据库询问食谱(再见ID依赖“findOrFail”)时,我必须使用此参数
  • 这意味着我每次发出请求时都必须访问包含User_id的User对象
  • 使用Auth :: id()每个单一时间,我需要一个(或n)食谱

像这样:

class RecipeRepository{


public function all(){
    return Recipe::where('user_id', Auth::id())
                ->orderBy('created_at', 'asc')
                ->get();
}

public function find($recipe_id){
    return Recipe::where('user_id', Auth::id())
                ->where('id', $recipe_id)
                ->firstOrFail();
}

这是对的吗?你恨我吗?你知道更好或更正确的方法吗?

2 个答案:

答案 0 :(得分:0)

大部分时间我在模型中创建一个方法来检查某人是否被授权,所有者等等。

一个例子是:

// User model

public function owns_recipe($recipe)
{

    return ($recipe->user_id == $this->id);

}

您可以在控制器方法的最开头调用它:

// Controller

public function index (Request $request)
{

    $recipe = Recipe::find($request->id); // Get recipe

    $user = ... // Get user somehow

    if (!$recipe) App::abort(404); // Show 404 not found, or something

    if (!$user->owns_recipe($recipe)) App::abort(403); // Show 403 permission denied, or something


    ... // Do whatever you want :)

}

答案 1 :(得分:0)

虽然有很多方法可以解决这个问题,但Laravel确实提供了一些内置的方法来处理动作的一般认证。首先,我按照您的意图行事(在RecipeRepository中有一个getRecipesByOwner方法),然后您可以从注入的Request对象将用户传递给它:

// RecipeController

public function index(Request $request)
{
    $recipes = $this->recipeRepo->findRecipesByOwner($request->user());
}

此外,我建议创建策略来管理用户是否能够更新/删除/查看单个食谱。然后,您可以在控制器/刀片模板/等中授权其操作。通过内置方法,如:

// Controller

public function update(Request $request, Recipe $recipe)
{
    $this->authorize('update', $recipe);
}

// Blade template

@can('update', $recipe)

@endcan

文档位于:https://laravel.com/docs/5.3/authorization#creating-policies

相关问题