Login to another Social Account while logged in

Posted 9 months ago by mlazuardy

I have 2 Socialite driver , facebook and google. While i'm logged in with facebook. in the users setting page i want to connect with google too, but it throw to the /home again maybe because middleware. So how to connect with another social driver while in logged in ? sorry bad english. this is my LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\User;
use App\Jobs\SendVerificationEmail;
use Socialite;
use Auth;
use App\SocialAccount;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/@';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function resend()
    {
        return view('auth.resend');
    }
    /**
     * middleware jika user belum verifikasi email
     */
    protected function authenticated(Request $request,$user)
    {
        if($user->verified == 0){
            $this->guard()->logout();
            return redirect('/login')->withErrors('Akun ini belum terverifikasi, silahkan cek email anda atau kirim ulang verifikasi');
        }
    }

    public function resendEmail(Request $request)
    {
        $email = $request->email;
        $user = User::where(['verified' => 0,'email'=> $email])->first();
        if (!$user){
            return redirect('/resend')->with('error','Invalid Email or Already Verified');
        }
        $user->email_token = base64_encode($request->email);
        $user->save();
        dispatch(new SendVerificationEmail($user));
        return redirect('/resend')->with('success','Verification successfully resend to your email');

    }
    /**
     * redirect to provider
     * @param Provider
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
    /**
     * get data from social driver
     */
    public function handleProviderCallback($provider)
    {
        $user = $this->createOrGetUser(Socialite::driver($provider)->user(),$provider);
        Auth::login($user);
        return redirect('/@')->with('success',"Sukses login melalui {$provider}");
    }
    /**
     * buat jika akun user dari provider belum terdaftar
     */
    private function createOrGetUser($providerUser, $provider)
    {
        $account = SocialAccount::where('provider', $provider)
            ->where('provider_user_id', $providerUser->getId())
            ->first();
        if ($account) {
            //return account jika ditemukan
            return $account->user;
        } else {
            //Check jika terdapat email yang sama 
            $user = User::where('email', $providerUser->getEmail())->first();
            //buat user jika tidak ada email yang terdaftar, wow lihat ada if didalam else
            if (!$user) {
                $user = User::create([
                    'username' => str_random(10),
                    'first_name' => str_random(7),
                    'last_name' => str_random(7),
                    'email' => $providerUser->getEmail(),
                    'verified' => true,
                    'password' => null
                ]);
            }
            $user->socials()->create([
                'provider_user_id' => $providerUser->getId(),
                'provider' => $provider
            ]);
            return $user;
        }
    }
}

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.