Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth::login() not working properly laravel 5.7

I'm trying to setup 'Login with facebook' using laravel socialite. When I try to login, it gets a successful callback from the facebook, I'm storing the data fetched into the database and try to redirect to home page. While doing so, I am redirected back to the login page and never reaching the homepage.

While debugging the error I found that my Auth::login($user) is not working properly.

Here is the code-

AuthController.php

use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
    $user = Socialite::driver($provider)->user();
    // dd($user);
    $authUser = $this->findOrCreateUser($user, $provider);
    // dd($authUser);
    if(Auth::login($authUser, true)){            // here is the error
      return redirect($this->redirectTo);
    }
    else{
      return 'Login not done';                 //this prints out to the screen
    }
}

public function findOrCreateUser($user, $provider)
 {
     $authUser = User::where('id', $user->id)->first();
     if ($authUser) {
         return $authUser;
     }
     return User::create([
         'name'     => $user->name,
         'email'    => $user->email,
         'avatar'    => $user->avatar,
         'password'    => bcrypt('password'),
         'provider' => $provider,
         'id' => $user->id
     ]);
 }

Do let me know what am I doing wrong.

This is what I'm getting while dd($authUser)

enter image description here

like image 747
Ujjwal Verma Avatar asked Nov 26 '22 00:11

Ujjwal Verma


1 Answers

Since you are grabbing user details and saving them to your database you in order to login you need to use attempt and passing the details that you get from $authUser variable, but you need a way to get the password since the attempt convert the password string to the hash in order to login the user

$authUser = $this->findOrCreateUser($user, $provider);
  $credentials = $request->only($authUser->email, 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
like image 83
Gozbeth Stanslaus Avatar answered Nov 29 '22 04:11

Gozbeth Stanslaus