I am trying to implement the Socialite package in my project. Here is my code that works great. However, it duplicates the record in the database, if the user logs out, tries to log in. Also, I cannot get a public username with the name $ userData->. It returns null.
Here is my controller;
namespace App\Http\Controllers; use App\AuthenticateUser; use App\AuthenticateUserListener; use App\Http\Requests; use Illuminate\Http\Request; class SocialLoginsController extends Controller implements AuthenticateUserListener { public function socialLogin(AuthenticateUser $authenticateUser, Request $request) { $hasCode = $request->has('code'); return $authenticateUser->execute($hasCode, $this); } public function userHasLoggedIn($user) { return redirect('student'); }
My custom repository;
namespace App\Repositories; use App\User; class UserRepository { public function findByUsernameOrCreate($userData) { return User::firstOrCreate([ 'username' => $userData->name, 'email' => $userData->email, ]); } }
User Class Authentication;
<?php namespace App; use Illuminate\Contracts\Auth\Guard; use App\Repositories\UserRepository; use Laravel\Socialite\Contracts\Factory as Socialite; class AuthenticateUser { private $users; private $socialite; private $auth; public function __construct(UserRepository $users, Socialite $socialite, Guard $auth) { $this->users = $users; $this->socialite = $socialite; $this->auth = $auth; } public function execute($hasCode, AuthenticateUserListener $listener) { if ( ! $hasCode) return $this->getAuthorizationFirst(); elseif($hasCode) { $user = $this->users->findByUsernameOrCreate($this->getGoogleUser()); $this->auth->login($user, true); return $listener->userHasLoggedIn($user); } } private function getAuthorizationFirst() { return $this->socialite->driver('google')->redirect(); } private function getGoogleUser() { return $this->socialite->driver('google')->user(); } }
source share