Laravel - How to redirect to login if user is not

2019-04-21 12:26发布

I'm trying to use the __constructor from the extended class (AdminController extends AdminBaseController) but aparently it's not working and I have no idea of what can be, here you can see both of my classes:

AdminBaseController.php

class AdminBaseController extends Controller
{
    public function __construct(){
        if (!Auth::user()){
            return view('admin.pages.login.index');
        }
    }
}

AdminController.php

class AdminController extends AdminBaseController
{
    public function __construct(){
        parent::__construct();
    }

    public function index()
    {
        return view('admin.pages.admin.index');
    }

    public function ajuda()
    {
        return view('admin.pages.admin.ajuda');
    }
}

EDIT


This is my admin route group:

Route::group([
    'prefix' => 'admin',
    'middleware' => 'auth'
], function () {
    Route::get('/', 'Admin\AdminController@index');

    Route::get('login', 'Admin\AuthController@getLogin');
    Route::post('login', 'Admin\AuthController@postLogin');
    Route::get('logout', 'Admin\AuthController@getLogout');

    Route::group(['prefix' => 'configuracoes'], function () {
        Route::get('geral', 'Admin\AdminConfiguracoesController@geral');
        Route::get('social', 'Admin\AdminConfiguracoesController@social');
        Route::get('analytics', 'Admin\AdminConfiguracoesController@analytics');
    });

    Route::get('ajuda', 'Admin\AdminController@ajuda');
});

4条回答
孤傲高冷的网名
2楼-- · 2019-04-21 13:17

The controller is not the right place to check if a user is authenticated or not. You should use a middleware for that. To get info on what a middleware is check here

Let's see how you can use the default Laravel's auth middleware for this purpose:

First of all get rid of your AdminBaseController and use only AdminController

Then you have to check that the auth middleware is enabled in the file app\Http\Kernel.php

You should have the line:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,

This means that the middleware is active and usable for your routes.

Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :

//this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
    //check here if the user is authenticated
    if ( ! $this->auth->user() )
    {
        // here you should redirect to login 
    }

    return $next($request);
}

Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:

Route::group( ['middleware' => 'auth' ], function()
{
    Route::get('admin/index', 'AdminController@index');
    Route::get('admin/ajuda', 'AdminController@ajuda');
});
查看更多
淡お忘
3楼-- · 2019-04-21 13:17

The way you extends and execute the parent constrictor is right, however returning a view to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send().

for you purpose I think you should use before for filter http://laravel.com/docs/4.2/routing#route-filters

查看更多
闹够了就滚
4楼-- · 2019-04-21 13:18

Use middleware for this purpose and then in controller constructor use it as in example below.

public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}

And then you need to secure routes where you want from user to be logged in to access.

Route::group(['middleware' => 'auth'], function() {
      Route::get('/dashboard', 'DashboardController@index');
});
查看更多
相关推荐>>
5楼-- · 2019-04-21 13:20

In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationException exception.

protected function authenticate(array $guards)
{
 if (empty($guards))
 {
  return $this->auth->authenticate();
 }
 foreach ($guards as $guard) {
  if ($this->auth->guard($guard)->check()) {
      return $this->auth->shouldUse($guard);
  }
 }
 throw new AuthenticationException('Unauthenticated.', $guards);
}

This will be caught by the app/Exceptions/Handler class which will call its render method which is responsible for converting a given exception into a HTTP response.

public function render($request, Exception $exception)
{
 return parent::render($request, $exception);
}

App/Exceptions/Handler extends 'Illuminate\Foundation\Exceptions\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. It has its own render method. Within that render method, there's a if else statement that says.

elseif ($e instanceof AuthenticationException)
{
 return $this->unauthenticated($request, $e);
}

Below is the ‘unauthenticated‘ method that is called by the above within the same class

protected function unauthenticated($request, AuthenticationException $exception)
{
  return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));
}

within this method is where you redirect an unauthenticated user.

As far as I can see, this is what goes on behind the scenes.

查看更多
登录 后发表回答