Unexpected automatic login Laravel 7x - laravel

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.

Related

Where to check if an User is logged in in a Laravel Application?

I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.

Laravel functionality that always runs

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

Laravel - deleting a guest user after the user logs out

I am using Laravel 5.4 and I want to delete a guest user from the users table after he logs out. So I created a LogoutEventListener class (followed instructions from documentation) and I am able to successfully delete the user in the handle(Logout $event) function.
However I am unable to determine if Laravel's own logout() function in AuthenticatesUsers trait is called either before or after the above handle function. Add(...) statement at the beginning of this function never seems to be called. So I am afraid of any unforeseen sideeffects.
So, is it safe to delete the user in the LogoutEventListener::handle() function?
Those are events for laravel 5.2 +
$events->listen(
'Illuminate\Auth\Events\Logout',
'App\Listeners\UserEventSubscriber#onUserLogout'
);

Laravel update Session manually

I am using Laravel 5.4 and I am using builtin Auth so Logging in - out comping behind the scene and it's storing the session automatically.
How can I add more information to my session ?
If you don't want to build a custom Login function, you could go to
AuthenticatesUsers file which handle this task and inside method called
authenticated(Request $request, $user)
You can add whatever you want.
This file can be found in
vendor->Laravel->framework->src->Illuminate->Foundation->Auth
Nour answer works but it's better if dont write code directly in vendor files, it can be overwritten by any composer update.
Instead you can add a function authenticated(Request $request, $user) directly in your App\Http\Controllers\Auth\LoginController and write your custom code that fires on every successful authentication.
Whatever you store in your user table will be stored in session data after log in you just need to access it like this
Auth::user()->column_name

Laravel logging out on user deleting

I am using Laravel 5.3.
I have an User model extending Authenticatable.
I also have an users panel where the super user can update and delete other users.
However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?
I am deleting on a custom controller "UserController":
public function delete (User $user)
{
$deleted = $user->delete();
return compact('deleted');
}
Found the problem:
When creating a new User using the built-in make:auth register method, the logged user inevitably gets re-logged as the recently created user. So, the logged user was no more the "super user" but the recently created user that, when deleted, gets logged out. Solved by registering in another method.
Without seeing any of your error logs, I'm not aware of Laravel's ability to return a variable from its controllers directly. So unless this feature exists, the issue may (at its core), be occurring due to the line:
return compact('deleted');
Try to return a view with the variable attached, (e.g. - if your view resides in resources/views/users/index.blade.php), replace the aforementioned line with the following:
return view('users.index', compact('deleted'));

Resources