Laravel functionality that always runs - laravel

I was wondering if laravel has a function or constructor that always runs on all files.
I want to use this function (if it exist) to make the administrator logged in at all times while I am developing.
public function runsAlways()
{
Auth::loginUsingId(1);
}

The boot function in the AppServiceProvider will be executed on every request.
But adding a custom provider or a middleware to all your routes would be a much cleaner solution.

If you want the default for authentication to last for longer example two weekes , you can adjust the session lifetime in the session.php config file.
'lifetime' => 20160, // 60 * 24 * 14
And log in user on boot method as #Jerodev mentioned

Related

Laravel - How to disable session for specific route?

Session driver is set to database currently. Now I want to disable session for some route. I am using laravel 7 in my project. What is the best way to disable the session?
I have tried: in StartSession.php file: \Config::set('session.driver', 'array');
Seems like it doesn't work for me, is there any better way?
Trying to modify code in files within vendor directory is not a good practice as it will get overridden whenever the package is updated.
If you want to remove a middleware from a specific route you can use withoutMiddleware
Route::get('/some-endpoint', function () {
//
})->withoutMiddleware([StartSession::class]);
Laravel Docs - Middleware - Excluding Middleware

defining route with 'auth:web' middleware in laravel service provider boot() method

im using a package called https://github.com/garygreen/pretty-routes
there is line in its service provider boot() method (here the code)
it is defining a get route with middlewares from its config file(link to the code) I just added 'auth:web' to its config file but it seems the 'auth:web' middleware is called as soon as code reaches the line before Laravel bootstraps its session and etc. when the auth('web')->user() is yet null
What I can not understand is that I do the same exact thing (here the code)with laravel/telescope but it works. why ???
also changing :
Route::get(config('pretty-routes.url'), 'PrettyRoutes\PrettyRoutesController#show')
->name('pretty-routes.show')
->middleware(config('pretty-routes.middlewares'));
to :
$this->app['router']->get(config('pretty-routes.url'), 'PrettyRoutes\PrettyRoutesController#show')
->name('pretty-routes.show')
->middleware(config('pretty-routes.middlewares'));
in service provider seems to solve the problem and make this code behave like the way telescope package use 'auth:web' as middleware.
what's happening ?
You need to have the web middleware applied to any routes you need sessions for, which is what the default authentication system is using. When you apply the auth middleware without this it can't possibly resolve a user since there is no session to be authenticated against.
You need to apply the web middleware and then what ever other middleware you want:
'middlewares' => [
'web', 'auth:web',
],
If you look at the telescope example you provided you will see they also add the web middleware. So you didn't quite "do the same exact thing" as the telescope config.

Unexpected automatic login Laravel 7x

My Laravel application automatically logs in after registering which I do not want. I use the default app/Http/Controllers/Auth/RegisterController.php and inside that file I wrote my own register() method. There is no $this->guard()->login($user); inside this method. Automatic login only happens occasionally but every time it happens the application 'loaded' for a long time after registering.

Laravel 5.7: User Not Set When Throwing NotFoundHttpException

I am overriding the rendering of a couple of exceptions in the App\Exceptions\Handler so I can return custom error pages. However, on some of the exceptions the auth()->user() is not set.
In the render-method, I am just dumping the user like this:
public function render($request, Exception $exception)
{
dd(auth()->user());
return parent::render($request, $exception);
}
When the exceptions are of the type NotFoundHttpException, the user isn't set. What would be the best solution for getting the user in these exceptions?
Here's the solution, but read on for a different recommendation.
By default, Laravel's authentication runs via the session. The session is explicitly started in the web middleware group.
If a route is not wrapped in the web middleware group (as a non-existent / 404 route would be), the middleware doesn't run, and the session isn't started. Therefore Laravel can't know if there is a session user.
Best solution: define a fallback route which was built for exactly this purpose.
Another solution, with gotchas: move the StartSession middleware into the global group that runs on every request.
/app/Http/Kernel.php:
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
// +++ MOVED SESSION START HERE BELOW +++
\Illuminate\Session\Middleware\StartSession::class,
];
But, should you...?
First, there's a reason the session doesn't load on every request by default: it creates extra overhead that might not be needed on every request. For example, if your website is configured to always use Laravel as the request handler, every 404 will route through Laravel. And there are a lot - crawlers and bots are constantly scouring the web for known insecure web paths. Take a look at your access logs.
Also, if you create self-contained error pages that don't depend on external application logic, you can reuse them at the server level. If Apache or Nginx throws an error, Laravel won't be there at all to dictate the output.
TL;DR: You can enable sessions on 404 and other pages, but understand the trade-offs. Personally, I recommend avoiding application logic on error pages.
Try:
Auth::user()
It should work the same way. Make sure you're including the Auth library.

Enabling session in lumen framework

I have two (but let's image more) micro-services (API) which need to be aware of authenticated user. Ideally I would simple like to resume their sessions.
All micro-services are using same storage for sessions: redis.
All API calls will have Cookie header, so all services will be able to resume sessions based on that cookie. I have successfully implemented this via PHP $_SESSIONs.
Now the question: how would you go about implementing this with Laravel/Lumen?
Last update on 5th of March 2021
(This answer was getting a lot of attention from Laravel community so I thought of updating it.)
Laravel has officially stopped supporting sessions & views in laravel/lumen framework from version 5.2 and on wards.
But laravel still have a component illuminate/session which can be installed in lumen/framework and we can play around with this.
Step - 1
install illuminate/session using
composer require illuminate/session
Step - 2
Now goto bootstrap/app.php and add this middleware
$app->middleware([
\Illuminate\Session\Middleware\StartSession::class,
]);
Purpose of adding the above middleware is to start session on every request and save session before serving response.
Step - 3
Now add config/session.php, since it is not present in Lumen by default. You can take session.php from Laravel official repo.
Step - 4
Create framework session storage directory by
mkdir -p storage/framework/sessions
Thanks to DayDream
Step - 5
In bootstrap/app.php add bindings for \Illuminate\Session\SessionManager
$app->singleton(Illuminate\Session\SessionManager::class, function () use ($app) {
return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session');
});
$app->singleton('session.store', function () use ($app) {
return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session.store');
});
Thanks to #xxRockOnxx for finding loadComponent method.
It takes 3 arguments,
first one is config file name. (file should be present in config/ directory)
second is ServiceProvider FQN
third is return of this method.
loadComponent just calls the $app->register and inject $app while building the ServiceProvider
How to Use
// Save Session
$router->get('/', function (\Illuminate\Http\Request $request) {
$request->session()->put('name', 'Lumen-Session');
return response()->json([
'session.name' => $request->session()->get('name')
]);
});
// Test session
$router->get('/session', function (\Illuminate\Http\Request $request) {
return response()->json([
'session.name' => $request->session()->get('name'),
]);
});
I've also added example over github supporting from lumen framework v5.6 to all the way to current version v8.0.
https://github.com/rummykhan/lumen-session-example
It is important to that you also use $request->session(), otherwise it will not work.
I tried the solution mentioned above, however, it's also required to create a folder storage/framework/sessions if using the default settings.
The accepted answer is outdated.
I answered and explained a bit how to properly do it in my answer on this question
I also posted what is the problem on my question at Laracasts
To quote:
the solution that is found in the link you gave is that, first it tells you to manually register the SessionManager to prevent the unresolvable depedency parameter #0 $app then also register the existing SessionServiceProvider which also binds another instance SessionManager.
Problem with that is, some components use the other instance and other parts use the new one which causes my auth attempt session not being save despite actually being put inside.

Resources