Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Auth in Exceptions\Handler.php

I'm trying to access the Auth class from within the render method of the App\Exceptions\Handler class (app/Exceptions/Handler.php) to determine if the User is currently logged in, using the Auth::check() method.

This worked fine in 5.1, but I've upgraded to 5.2 and it no longer works.

To debug this, I've been printing Auth::user() to the logs (which returns NULL), then returning a redirect() to another view.

Then from the view/controller the redirect goes to, printing the same Auth::user() to the logs, which works as expected and returns the logged in user.

So it seems there's no problem accessing the Auth class or the user() method from within the Exceptions\Handler class, it's just that it returns NULL for some reason, whereas other parts of the app return the User..

Thanks for any info on this!

like image 271
Graham T Avatar asked Jan 24 '16 22:01

Graham T


2 Answers

This happens because StartSession middleware is inside $middlewareGroups (the application's route middleware groups), so you don't have access to the authenticated user because the middlewares that initialize your session starts later in the lifecycle than the ExceptionHandler.

In app\Kernel.php file, move this line:

 \Illuminate\Session\Middleware\StartSession::class,

from $middlewareGroups to the global stack $middleware. These middleware are run during every request to your application so, after this, Auth::user() will works.


WARNING: With this solution you will not be able to use the cookie session driver. Works well with file and others.


UPDATE:

If you still need to use StartSession inside global stack $middleware and also you need cookie session driver, you must move three middlewares from $middlewareGroup to $middleware in the next order:

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class
like image 94
tomloprod Avatar answered Sep 24 '22 04:09

tomloprod


After some research, it seems the 404 errors are the only culprits. If it's a 500 error, Auth::user() works. So, in my routes.php file, I added this at the bottom

Route::any('{page}', 'ErrorController@Error404')->where('page', '(.*)');

to catch any unhandled endpoints. In that ErrorController@Error404 method, I can access the Auth class. So whatever logic you have in your App\Exceptions\Handler, you can duplicate it in the ErrorController@Error404 method. (Or better: extract it to some other entity that can be referenced in both places.)

like image 36
murribu Avatar answered Sep 22 '22 04:09

murribu