Laravel Socialite callback auth('customer')->user() is null - laravel

Laravel 6
There are 2 possible scenario:
Logged in user connect to Google account
Guest user connect to Google account (will create a new user if not exists)
Let's talk about the first scenario
In my routes/web.php, no middleware
Route::get('connect/{provider}', [ConnectController::class, 'connect'])
->name('connect');
Route::get('connect/{provider}/callback', [ConnectController::class, 'callback'])
->name('connect.callback');
In ConnectController.php
class ConnectController extends Controller
{
public function connect(Request $request, $provider)
{
$scopes = config('services.google.scopes');
// dump(auth('customer')->user()); <------- this 1 has value
return Socialite::driver($provider)
->scopes($scopes)
->redirect();
}
public function callback(Request $request, $provider)
{
$oauthUser = Socialite::driver($provider)->stateless()->user();
$user = auth('customer')->user();
debugbar()->log('callback user: ' . ($user->name ?? 'null'));
// ...
if (!auth('customer')->check()) {
debugbar()->log('user not logged in, log in now: ' . $u->name);
auth('customer')->login($u);
}
return redirect()->route('accounts');
}
Then the debugbar output is
log callback user: null
Suppose the user is logged in, and try to connect with google, but when reached the callback, the user session gone. What am I missing?
P/S: The default auth driver is admin, cannot be changed.

After a day of research, I found out that the session ID is different from before navigate out to Google, and in the callback request.
Just update config/session.php, and set to lax (originally was strict)
[
// ...
'same_site' => 'lax',
]

Related

stay login laravel 9

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

Get Auth User ID Laravel

I Made Laravel Project And install the Breeze package for multi authentication And the Create a guard call admin in order to control user assess to dashboard It works fine Here is the route
Route::get('/dashbord',[AdminController::class, 'Dashbord'])
->name('admin.dashbord')
->middleware('Admin');
Route::get('/profile/edit',[AdminProfileSettings::class, 'index'])
->name('admin.profile.settings')
->middleware('Admin');
Here Is the middleware
public function handle(Request $request, Closure $next)
{
if(!Auth::guard('admin')->check()) {
return redirect()->route('login_form')->with('error','please Login First');
}
return $next($request);
}
This code works fine but the problem is when I log in to the dashboard and try to get admin ID to admin.profile.settings route it wont get the Id, I Passed the logged admin id by using AdminProfileSettings controller like this
public function index()
{
$id=Auth::user()->id;
$adminData = Admin::find($id);
return view('admin.admin_profile_settings',compact('adminData'));
}
But, when I try to access it in the admin.admin_profile_settings view it show me this error:
Trying to get property 'id' of non-object
But, if I use $adminData = Admin::find(1); it get the Id without any problem but when I try to get auth user id it show me the error and if I have logged in using default guard this error wont show but it get the id from users table
You're not using the auth:admin middleware, so the Auth facade is going to pull the user from the default guard defined in the config (which is web, unless you've changed it).
Without using the auth:admin middleware, you'll need to specify the guard for which to get the user.
$adminUser = Auth::guard('admin')->user();
Note 1: if you have the $request variable, you can also pull the user off of the $request with $request->user(), instead of reaching out to the Auth facade. It's just a matter of preference. The user() method also takes a guard as a parameter, if needed.
$adminUser = $request->user('admin');
Note 2: the user() method (Auth and request) returns the fully hydrated model. There is no need to get the id and re-retrieve the model.

Do I need to store the FB access token on the backend in my Laravel Socialite+JWT and Ionic app?

I am slightly confused about the correct flow to Register and Login a user with cordova-plugin-facebook4 and Laravel Socialite + tymondesigns/jwt-auth. My front end is in Ionic 2 and the backend is in Laravel 5.4
My flow: (heavily borrowed from this blog post)
Using the cordova-plugin-facebook4 , perform a FB.login(). This returns the following json
{
status: "connected",
authResponse: {
session_key: true,
accessToken: "EAACgZAhHOaPsBAIjUUASeKSLnbEkashdkashdkhakdhakdh",
expiresIn: 5183979,
sig: "...",
secret: "...",
userID: "634565435"
}
}
Post the "accessToken" to http:///auth/facebook
Retrieve the user profile using the Socialite "userFromToken" method.
$profile = Socialite::driver('facebook')->userFromToken($token);
Check if the user exists in the DB.
IF it does create and return a new access token using JWTAuth
ELSE create a new user in the DB and return a new access token using JWTAuth
$provider = "facebook"
try{
$profile = Socialite::driver($provider)->userFromToken($token);
}
catch(Exception $exception)
{
return response()->json([
'error'=>'User retrieval failed from provider'
],401);
}
//Check if the user registered earlier with this provider.
try{
$existingUser = User::where('provider','=',$provider)
->where('provider_id','=',$profile->getId())
->firstOrFail();
//If user is found and no exception was raised
if ($existingUser)
{
return response()->json([
'token'=>JWTAuth::fromUser($existingUser),
'user'=>$existingUser
]);
}
}
catch (ModelNotFoundException $exception)
{
$user=new User();
$user->email=$profile->getEmail();
$user->name=$profile->getName();
$user->password=$this->random_password();
$user->provider=$provider;
$user->provider_id=$profile->getId();
$user->save();
return response()->json([
'token'=>JWTAuth::fromUser($user),
'user'=>$user
]);
}
My Confusion:
Are the "Login with Facebook" and "Register/Signup with Facebook" two exclusive functions? How would subsequent logins work for a mobile app after the user registers on Laravel the first time?
In Step 4 when I check if the user exists in the backend I'm querying the table on the "provider_id" returned by Socialite::driver($provider)->userFromToken($token)->getId(). I don't understand how this value is unique to a particular user.
In both cases for step 2 - a new JWT Auth token is created from the user and returned to the front end. I plan to save this token on the front end and use it for protected resource access. However, I'm not sure if I need to store the FB Access_Token in the DB and share it with the front end to be cached as well.
How will the login process work when the app is reopened. The user should be auto logged in but would this happen via Facebook, via Laravel Social or just the locally stored JWT?
Thanks
Sam

Disabled user / Validation Email

I've added a column (is_activated) in user DB to add verification email in registration process.
I follow this tutorial:
Tutorial
It works but an user that is not activated can bypass login function using the reset password form.
How can I resolve this problem?
You should create middleware and redirect all not activated users back to home page, for example:
public function handle($request, Closure $next)
{
if (!auth()->user()->is_activated) {
return redirect('/');
}
return $next($request);
}
Then register this middleware and apply it to all non public routes with Route::group()
If user is activated the value is 1, so integrate in your function the next validation:
// if user not have value 1 (is not activated)
if (auth()->user()->is_activated != 1) {
// user is not activated so redirect to index
return redirect('/');
}
// user is activated so redirect to account
return redirect('account');
}
you need check is "is_actived" have the value 1 or not.

Laravel - Deleting auth user account while user is logged in

I'm trying to build a function where a user can delete their own account while they are logged in. I'm struggling to find any example or logic/best practices.
The controller looks like this:
public function postDestroy() {
$user = User::find(Auth::user()->id);
$user = DB::delete('delete from users')->user(id);
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
I'm trying to grab the current Auth (logged in) user and use their id to delete them from the database. Then send them to the home page with a message.
Also, do I need to make sure the session is properly closed during this process, such as Auth::logout(); ?
I'm pretty new to Laravel, so any help would be appreciated.
Not sure how your routing looks like, but this should do the job.
$user = \User::find(Auth::user()->id);
Auth::logout();
if ($user->delete()) {
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
You should logout user before delete.
You merely gotta do like this:
$user=auth()->user();
$user->delete();

Resources