Laravel 5中间件“所有者”?

时间:2015-04-19 18:02:13

标签: php laravel permissions laravel-5 middleware

我在创建“所有者”中间件方面遇到了麻烦。

例如,我有一个与Articles密钥相关联的Useruser_id模型。

我想将“所有者”中间件添加到ArticlesController,因此该文章的唯一所有者可以编辑,更新和删除它。

我一直在寻找这个问题,但从未找到过可行的代码。 他们中的一些人试图使其与Form Requests一起使用,但我对使用中间件感兴趣。

2 个答案:

答案 0 :(得分:8)

  1. 创建中间件:
  2. php artisan make:middleware OwnerMiddleware
    
    namespace App\Http\Middleware;
    
    use App\Article;
    use Closure;
    use Illuminate\Contracts\Auth\Guard;
    
    class OwnerMiddleware
    {
        /**
         * The Guard implementation.
         *
         * @var Guard
         */
        protected $auth;
    
        /**
         * Create a new filter instance.
         *
         * @param  Guard  $auth
         * @return void
         */
        public function __construct(Guard $auth)
        {
            $this->auth = $auth;
        }
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $articleId = $request->segments()[1];
            $article = Article::findOrFail($articleId);
    
            if ($article->user_id !== $this->auth->getUser()->id) {
                abort(403, 'Unauthorized action.');
            }
    
            return $next($request);
        }
    }
    
    1. 将其添加到app\Http\Kernel.php
    2. protected $routeMiddleware = [
          'owner' => 'App\Http\Middleware\OwnerMiddleware',
      ];
      
      1. 在路线中使用中间件:
      2. Route::group(['middleware' => ['owner']], function() {
            // your route
        });
        

答案 1 :(得分:5)

或者你可以使用路由和middleware parameters,它有一些优点:

  • 即使请求结构发生变化,您的中间件仍可正常工作
  • 中间件可以重用不同的资源
  • 您可以在控制器内使用它

这是中间件(app/Http/Middleware/AbortIfNotOwner.php):

<?php

namespace App\Http\Middleware;

use Closure;

class AbortIfNotOwner
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string    $resourceName
     * @return mixed
     */
    public function handle($request, Closure $next, $resourceName)
    {
        $resourceId = $request->route()->parameter($resourceName);

        $user_id = \DB::table($resourceName)->find($resourceId)->user_id;

        if ($request->user()->id != $user_id) {
            abort(403, 'Unauthorized action.');
        }

        return $next($request);
    }
}

内部app\Http\Kernel.php

protected $routeMiddleware = [
     'owner' => 'App\Http\Middleware\AbortIfNotOwner',
];

在路径文件(app/Http/routes.php)中:

Route::group(['middleware' => ['owner:articles']], function() {
    // your route
});

并可选择在控制器中调用它:

public function __construct()
{
    $this->middleware('owner:articles', ['only' => ['edit', 'update']]);
}