stay login laravel 9 - laravel

can't stay login in project,
this is my code in appserviceprovider.php ,
Auth::loginUsingId(18876 ,true);
is true and login and get ,
dd(auth()->user()->id);
my output,
^ 18876
this picture,
and my export in website user is loggedin,
if comment this
Auth::loginUsingId(18876 ,true);
and write dd(auth()->user()->id);
and check user is login
if (Auth::check()) {
dd(1);
} else {
dd(2);
}
output

Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute before the middleware in the request lifecycle
You should use a middleware to share your varibles from the session
However, If for some other reason you want to do it in a service provider, you can do it using a view composer with a callback, like this:
public function boot()
{
//compose all the views....
view()->composer('*', function ($view)
{
auth()->user();
});
}
The callback will be executed only when the view is actually being composed, so middleware will be already executed and session will be available

Related

Verify access token with Database in laravel

In my laravel project, I am allowing user to generate a token which will be stored in tenants Database. Now when an API is called ,at that time I want to verify this token with the token stored in DB. How to do that ?? How can I achieve this using middleware ?? Please advise
You could verify it in middleware as follows:
create a middleware file with command php artisan make:middleware EnsureTokenIsValid
Now go to app/Http/Middleware and find EnsureTokenIsValid middleware. Then, on handle method you should implement your logic with something like:
public function handle($request, Closure $next)
{
// you have to get token from database below line is just an example
$tokenInDatabase = TenanentModel::find(1);
if ($request->input('token') !== $tokenInDatabase) {
// if token not match redirect to home page
// or implement your logic
return redirect('home');
}
return $next($request);
}
Next, you need to register your middleware on app/Http/Kernel.php as mentioned in https://laravel.com/docs/9.x/middleware#assigning-middleware-to-routes. Example:
'ensureTokenIsValid' => \App\Http\Middleware\EnsureTokenIsValid::class,
Next, add to the route. Example:
Route::get('/profile', function () {
//
})->middleware('ensureTokenIsValid');
You could find more details about this on: https://laravel.com/docs/9.x/middleware#defining-middleware

Laravel middleware to check user has access - if not do not proceed with controller method?

Googled and tried for hours now, i need help. Laravel 9.x here.
I use ajax calls which are handled by controllers.
Before the controller handles them, i need to check if the user has indeed access to the administration the user is requesting data for.
The problem is the return false in the middleware class. How can i return a response to the browser without executing any method inside the requested controller class?
The middleware i'm using:
namespace App\Http\Middleware;
use Closure;
class CheckUserAccessToAdministration {
public function handle($request, Closure $next)
{
// Check if the user has access rights to the requested administration
$allowedAdministrations = $request->session()->get('allowed_administrations');
$administration = $request->adm;
if(!in_array($administration, $allowedAdministrations)){
// the idea is that i stop execution of the call, not execute controller method
and just return a message to the browser. i use return false atm, but that isn't right,
i think.
return false;
}
return $next($request);
} }

LImit Access on pages. to prevent access pages without login

as we know when we code on localhost we can go directly to dashboard admin on our website without login first by typing the link. so how we can stop that? so if we want to access the admin dashboard we really have to log in first
use laravel middleware to limit accesses ... you can use auth middleware like:
Route::get('/profile', function () {
//
})->middleware('auth');
for more info visit laravel docs
use laravel middleware in your web.php if you are using a simple function for your route
Route::get('/admin/dashboard',function () {
return view....``
})->middleware('auth');
Or you can use a constructor in your Controller to limit access for all function in this controller
public function __construct()
{
$this->middleware('auth');
}

Laravel Auth::id() return null after login

I have a login form to access to my web page.
In my local computer everything works fine. But now I upload my project to my server and when I login the directive #auth() is null.
I put in my controller this: dd(Auth::id()); and in my local server returns a Id but in the production server returns null...
in web.php I have tis code:
Route::group(['middleware' => 'role:admin' OR 'role:user'], function () {
Route::get('/users/inicio', function(){
dd(Auth::id());
return view('frontend.dashboardUser');});
});
This return null
Can you help me?
Thank you
I think there might be some session problem, It might not be maintaining the session state.
My suggestion:
Try echo session_id() multiple times, If every time different id is generated then there will be some problem with the session on server otherwise not.
Have you registered a new user after you pushed your code to the production? I mean have you logged in using an existing user on production? I believe your production and local Database is different and the user who exists on local does not exist on production DB.
Register a new user and login as the new user and then try accessing the route to see if you get the auth id.
For a security reason, you can't access the login user or any other session into the web.php file as well as a constructor of the class.
To archive this you can use middleware something like this:
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
This link can help you more. Good luck!!!

php laravel preventing multiple logins of a user from different devices/browser tabs at a given time

Does laravel provide a way to prevent multiple logins of a user from different devices / browsers at a given time? If yes then how can i force a user to logged in from a single device at a single time. I am developing a online quiz app using laravel 5.6 where users can logged in from a single place and take test.
laravel provide this method to invalidating and "logging out" a user's sessions that are active on other devices logoutOtherDevices()
to work with this method you need also to make sure that the
Illuminate\Session\Middleware\AuthenticateSession
middleware is present and un-commented in your app/Http/Kernel.php class' web middleware group:
'web' => [
// ...
\Illuminate\Session\Middleware\AuthenticateSession::class,
// ...
],
then you can use it like this
use Illuminate\Support\Facades\Auth;
Auth::logoutOtherDevices($password);
Perhaps this should get you started:
Add a column in users_table.php
$table->boolean('is_logged_in')->default(false);
When a user logs in: LoginController.php
public function postLogin()
{
// your validation
// authentication check
// if authenticated, update the is_logged_in attribute to true in users table
auth()->user()->update(['is_logged_in' => true]);
// redirect...
}
Now, whenever a user tries to login from another browser or device, it should check if that user is already logged in. So, again in LoginController.php
public function index()
{
if (auth()->check() && auth()->user()->is_logged_in == true) {
// your error logic or redirect
}
return view('path.to.login');
}
When a user logs out: LogoutController.php
public function logout()
{
auth()->user()->update(['is_logged_in' => false]);
auth()->logout();
// redirect to login page...
}

Resources