如何检查中间件laravel 5.2中的数据库值

时间:2017-01-16 11:40:53

标签: laravel laravel-5.2 middleware

我有一个视图,只有拥有" role = interviewer"的用户才能访问该视图。在数据库中。我创建了中间件并注册了它,但它似乎没有按预期工作。它允许所有用户,无论他们的角色存储在数据库中。

这是我的中间件

class Interviewer
{
    public function handle($request, Closure $next)
    {
        if($request->user()->role == "interviewer"){
             return $next($request);
        }           
    }
}

我不知道方法是否正确我也尝试了

if($request->\Auth::user()->role == "interviewer")

这个也不起作用。如果用户没有角色访问员,则admin应该是限制的视图。这是我的路线

Route::get('/candidates', [
    'uses' => 'candidateController@showProfile',
    ])->middleware('auth','interviewer');

我的路线中间件

    protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'interviewer'=> \App\Http\Middleware\Interviewer::class,
];

2 个答案:

答案 0 :(得分:0)

如果需要失败,您需要在中间件中返回一些内容,在您的情况下是错误响应。

namespace App\Core\Http\Middleware;

use Tymon\JWTAuth\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class Employee extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next, $role = null)
    {
        $user = $request->user();

        if (! ($user->authenticable instanceof \App\Core\Entities\User)) {
            return response([
                'title'  => 'You may not call this API as a non-employee.',
                'error'  => 'invalid_user_type'
            ], 401); // <-- See? I returned an error!
        }

        if ($role) {
            if (strtolower($user->authenticable->role->name) !== strtolower($role)) {
                return response([
                    'title'  => "You may not call this API as a \"{$user->authenticable->role->name}\".",
                    'error'  => 'unnecessary_permissions'
                ], 401); // And also here!
            }
        }

        return $next($request);
    }
}

答案 1 :(得分:0)

在您的中间件中,您始终需要returnnext($request)

class Interviewer { 
    public function handle($request, Closure $next) { 
        if($request->user()->role != "interviewer"){
             return back(); 
        } 
        return $next($request);
    } 
}

同时修改您的routes.php。中间件需要在一个数组中:

Route::get('/candidates', [
    'uses' => 'candidateController@showProfile',
])->middleware(['auth','interviewer']);