douzhuo8312 2017-01-13 10:39
浏览 96

在所有控制器的操作中检查用户的身份验证

I use Laravel 5.3 and I have the following problem.

[UPDATE]

My initial trouble was the appearance of an error when performing actions on the site when the user was not logged in the system.

This happened when the browser is started, where cached information is displayed by default on the page. Site interface displayed for logged users, and in his system was not. At the same time, producing some action, I get an error that the user is not authorized.

I also have group auth middleware for all my routes. When I reboot page of the site, the middleware is activated and redirectedme to the login page. The main problem is the browser shows the cached information.

So, in addition to middleware for routes I decided to make auth check in controllers.

[/UPDATE]

I want to check user's auth in every controller's action. Making the auth check in every controllers' action manually isn't a solution, because there are many controllers and actions.

So I decided to make it globally.

As all controllers extends Main Controller (App\Http\Controllers\Controller.php), I decided write the auth()->check() in constructor:

function __construct()
{
    if(auth()->check()) dd('success');
}

But... nothing happened((( Then I found the callAction method in BaseController which Main Controller extends and made checking here:

public function callAction($method, $parameters)
{
    if(auth()->check()) dd('success');
    return call_user_func_array([$this, $method], $parameters);
}

This time everything's OK, but I don't like this solution, because editing the core files isn't good.

Finally, I redeclared callAction method in Main Controller with auth checking, but I don't like this way too.

Is any solution?

  • 写回答

3条回答 默认 最新

  • dongxie9169 2017-01-13 10:42
    关注

    if there is a group of routes this would be the easiest way

    Route::group(['middleware' => ['auth']], function()
    {
        // here all of the routes that requires auth to be checked like this
        Route::resource('user','UsersController');
    }
    

    another ways

    function __construct()
    {
        $this->middleware('auth');
    }
    

    another way is specified on controller routes

    Route::get('profile', [
        'middleware' => 'auth',
        'uses' => 'UserController@showProfile'
    ]);
    

    see documentation

    https://laravel.com/docs/5.0/controllers#controller-middleware

    评论

报告相同问题?