-
composer.json
Open in GitHub{ // "require": { "php": "^7.4", // "laravel/socialite": "^5.2" }, // }
-
routes/web.php
Open in GitHubuse Illuminate\Support\Facades\Route; // Route::get('login/github', 'Auth\LoginController@redirectToProvider')->name('login'); Route::get('login/github/callback', 'Auth\LoginController@handleProviderCallback'); //
-
app/Http/Controllers/Auth/LoginController.php
Open in GitHubuse App\Events\NewUserSignedUp; use App\Http\Controllers\Controller; use App\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; use Laravel\Socialite\Facades\Socialite; class LoginController extends Controller { // public function redirectToProvider() { session()->flash('url.intended', url()->previous()); return Socialite::driver('github')->redirect(); } public function handleProviderCallback() { $user = $this->createOrUpdateUser(Socialite::driver('github')->user()); if ($user->wasRecentlyCreated) { event(new NewUserSignedUp($user)); } Auth::login($user, false); return redirect()->intended(); } private function createOrUpdateUser($socialiteUser) { if (is_null($user = User::forSocialiteUser($socialiteUser))) { return User::create($this->socialiteUserAttributes($socialiteUser)); } $user->update($this->socialiteUserAttributes($socialiteUser)); return $user; } private function socialiteUserAttributes($socialiteUser) { return [ 'name' => $socialiteUser->getName() ?: $socialiteUser->getNickname(), 'email' => $socialiteUser->getEmail(), 'avatar' => $socialiteUser->getAvatar(), 'github_username' => $socialiteUser->getNickname(), 'github_user_id' => $socialiteUser->getId(), ]; } }