Skip to content

Instantly share code, notes, and snippets.

@sethsandaru
Last active May 4, 2019 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethsandaru/0bf2c6ce14519f827a4b108c7fc3ec6e to your computer and use it in GitHub Desktop.
Save sethsandaru/0bf2c6ce14519f827a4b108c7fc3ec6e to your computer and use it in GitHub Desktop.
Laravel Socialite Github Login Demo
<?php
/**
* Created by PhpStorm.
* User: Seth Phat
* Date: 5/4/2019
* Time: 3:41 PM
*/
namespace App\Http\Controllers\Social;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Socialite;
class GithubAuthController extends Controller
{
const SERVICE = "github";
public function redirectLogin()
{
return Socialite::driver(static::SERVICE)->redirect();
}
public function handleCallback() {
try {
// get user information
/**
* @var $user \Laravel\Socialite\Two\User
*/
$user = Socialite::driver(static::SERVICE)->user();
// check if user registered or not in the system
$userDB = User::query()->where('email', $user->getEmail())->first();
// if not registered yet, create a new user record
if (empty($userDB)) {
$userDB = new User;
$userDB->name = $user->getName();
$userDB->email = $user->getEmail();
// more info if you have any
// if db error
if (!$userDB->save()) {
throw new \Exception('Create user failed due to DB Error...');
}
// ok, it saved. login now
}
// login to the system now
Auth::loginUsingId($userDB->id);
// redirect back to homepage with success
return redirect()
->to('/')
->with('success', 'Login successfully!');
} catch (\Exception $e) {
return redirect()
->to('/')
->with('error', 'Login via Github failed. Please try again.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment