Skip to content

Instantly share code, notes, and snippets.

@Hujjat
Last active November 21, 2018 08:11
Show Gist options
  • Save Hujjat/16bd20b89b36a148d12ef5ed24bd4a22 to your computer and use it in GitHub Desktop.
Save Hujjat/16bd20b89b36a148d12ef5ed24bd4a22 to your computer and use it in GitHub Desktop.
// Database Structure
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->nullable();
$table->string('password', 60)->nullable();
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
// Update your fillable property
protected $fillable = [
'name', 'email', 'password', 'provider', 'provider_id'
];
// Open your config/services.php AND add any
'facebook' => [
'client_id' => env('FACEBOOK_ID'),
'client_secret' => env('FACEBOOK_SECRET'),
'redirect' => env('FACEBOOK_URL'),
],
'twitter' => [
'client_id' => env('TWITTER_ID'),
'client_secret' => env('TWITTER_SECRET'),
'redirect' => env('TWITTER_URL'),
],
'google' => [
'client_id' => env('GOOGLE_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('GOOGLE_URL'),
],
// Add the Keys to .env
// for facebook
FACEBOOK_ID=API_Key
FACEBOOK_SECRET=API_secret
FACEBOOK_URL=callbackurl
// for twitter
TWITTER_ID=API_Key
TWITTER_SECRET=API_secret
TWITTER_URL=callbackurl
// for google
GOOGLE_ID=API_Key
GOOGLE_SECRET=API_secret
GOOGLE_URL=callbackurl
// add the routes app/Http/routes.php
Route::get('auth/{provider}', 'Auth\AuthController@redirectToProvider');
Route::get('auth/{provider}/callback', 'Auth\AuthController@handleProviderCallback');
// update your auth controller app/Http/Controllers/Auth/AuthController.php
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)
->stateless()
->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
// Lastly, the links
<a href="{{ url('/auth/facebook') }}" class="btn btn-primary">Facebook Login</a>
<a href="{{ url('/auth/twitter') }}" class="btn btn-primary">Twitter Login</a>
<a href="{{ url('/auth/google') }}" class="btn btn-primary">Google Login</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment