Authorization via social networks

28 views Asked by At

I have a Laravel project where I log into the system via social networks.

web.php (Route)

Route::get('social-auth/{provider}', [SocialController::class, 'redirectToProvider'])->name('auth.social');

Route::get('social-auth/{provider}/callback', [SocialController::class, 'handleProviderCallback'])->name('auth.social.callback');

Controller (SocailController.php)

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

public function handleProviderCallback($provider)
{
    $socialiteUser = Socialite::driver($provider)->user();

    $user = $this->findOrCreateUser($provider, $socialiteUser);

    auth()->login($user, true);

    return redirect()->route('index');
}

public function findOrCreateUser($provider, $socialiteUser)
{
    if ($user = $this->findUserBySocialId($provider, $socialiteUser->getId())) {
        return $user;
    }

    if ($user = $this->findUserByEmail($provider, $socialiteUser->getEmail())) {
        $this->addSocialAccount($provider, $user, $socialiteUser);

        return $user;
    }

    $user = User::create([
        'name' => $socialiteUser->getName(),
        'email' => $socialiteUser->getEmail(),
        'password' => bcrypt(Str::random(25)),
    ]);

    $this->addSocialAccount($provider, $user, $socialiteUser);

    return $user;
}

public function findUserBySocialId($provider, $id)
{
    $socialAccount = SocialAccounts::where('provider', $provider)
        ->where('provider_id', $id)
        ->first();

    return $socialAccount ? $socialAccount->user : false;
}

public function findUserByEmail($provider, $email)
{
    return !$email ? null : User::where('email', $email)->first();
}

public function addSocialAccount($provider, $user, $socialiteUser)
{
    SocialAccounts::create([
        'user_id' => $user->id,
        'provider' => $provider,
        'provider_id' => $socialiteUser->getId(),
        'token' => $socialiteUser->token,
    ]);
}

Model 'SocialAccounts' linked to table 'Socual_account'

When I log in through the social networks VKontakte or Google, I end up redirecting to the main page with get parameters. No additions to the database occur. How to authorize route auth.social.callback?

0

There are 0 answers