Social Login Documentation

This document covers the setup and implementation of social login (OAuth) for Google and Facebook in the Universal Bookshelf platform.

Overview

The Universal Bookshelf platform supports social login through OAuth 2.0 for Google and Facebook. This allows users to authenticate using their existing social media accounts, providing a seamless login experience.

Supported Providers

  • Google OAuth 2.0 - Most popular and widely used
  • Facebook OAuth 2.0 - Large user base integration

Google OAuth Setup

Step 1: Create Google OAuth Credentials

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the Google+ API
  4. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client IDs"
  5. Set application type to "Web application"
  6. Add authorized redirect URIs:
    • http://localhost:8000/auth/google/callback (for local development)
    • https://yourdomain.com/auth/google/callback (for production)
  7. Copy the Client ID and Client Secret

Step 2: Configure Environment Variables

Add the following to your .env file:

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://localhost:8000/auth/google/callback

Step 3: Install Required Packages

Install Laravel Socialite:

composer require laravel/socialite

Facebook OAuth Setup

Step 1: Create Facebook App

  1. Go to Facebook Developers
  2. Click "Create App"
  3. Choose "Consumer" as the app type
  4. Fill in the app details
  5. Go to "Facebook Login" → "Settings"
  6. Add OAuth redirect URIs:
    • http://localhost:8000/auth/facebook/callback (for local development)
    • https://yourdomain.com/auth/facebook/callback (for production)
  7. Copy the App ID and App Secret

Step 2: Configure Environment Variables

Add the following to your .env file:

FACEBOOK_CLIENT_ID=your_facebook_app_id
FACEBOOK_CLIENT_SECRET=your_facebook_app_secret
FACEBOOK_REDIRECT_URI=http://localhost:8000/auth/facebook/callback

Configuration Files

config/services.php

Add the following configuration to your services config file:

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT_URI'),
],

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT_URI'),
],

API Endpoints

GET /auth/google

Redirect user to Google OAuth consent screen

Description:

This endpoint initiates the Google OAuth flow by redirecting the user to Google's consent screen where they can authorize the application to access their basic profile information.

Response:

Redirects to Google OAuth consent screen

GET /auth/google/callback

Handle Google OAuth callback

Description:

This endpoint processes the callback from Google after successful authorization. It creates or updates the user account and logs them in.

Query Parameters:
  • code - Authorization code from Google
  • state - CSRF protection state parameter
Success Response:

Redirects to dashboard or specified redirect URL

GET /auth/facebook

Redirect user to Facebook OAuth consent screen

Description:

This endpoint initiates the Facebook OAuth flow by redirecting the user to Facebook's consent screen.

Response:

Redirects to Facebook OAuth consent screen

GET /auth/facebook/callback

Handle Facebook OAuth callback

Description:

This endpoint processes the callback from Facebook after successful authorization.

Query Parameters:
  • code - Authorization code from Facebook
  • state - CSRF protection state parameter

Implementation Example

SocialAuthController

Here's an example of how to implement the social login controller:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SocialAuthController extends Controller
{
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        try {
            $user = Socialite::driver('google')->user();
            
            $finduser = User::where('google_id', $user->id)->first();
            
            if ($finduser) {
                Auth::login($finduser);
                return redirect('/dashboard');
            } else {
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id' => $user->id,
                    'password' => Hash::make(Str::random(24)),
                    'email_verified_at' => now(),
                ]);
                
                Auth::login($newUser);
                return redirect('/dashboard');
            }
        } catch (\Exception $e) {
            return redirect('/auth/google')->with('error', 'Google login failed');
        }
    }

    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function handleFacebookCallback()
    {
        try {
            $user = Socialite::driver('facebook')->user();
            
            $finduser = User::where('facebook_id', $user->id)->first();
            
            if ($finduser) {
                Auth::login($finduser);
                return redirect('/dashboard');
            } else {
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'facebook_id' => $user->id,
                    'password' => Hash::make(Str::random(24)),
                    'email_verified_at' => now(),
                ]);
                
                Auth::login($newUser);
                return redirect('/dashboard');
            }
        } catch (\Exception $e) {
            return redirect('/auth/facebook')->with('error', 'Facebook login failed');
        }
    }
}

Database Schema

You'll need to add social login fields to your users table:

Migration Example

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id')->nullable()->unique();
            $table->string('facebook_id')->nullable()->unique();
            $table->string('avatar')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['google_id', 'facebook_id', 'avatar']);
        });
    }
};

Frontend Integration

Login Buttons

Add social login buttons to your login form:

<div class="social-login-buttons">
    <a href="/auth/google" class="btn btn-danger">
        <i class="fab fa-google me-2"></i>Login with Google
    </a>
    
    <a href="/auth/facebook" class="btn btn-primary">
        <i class="fab fa-facebook me-2"></i>Login with Facebook
    </a>
</div>

Security Considerations

Important Security Notes

  • Always validate the OAuth state parameter to prevent CSRF attacks
  • Store sensitive credentials in environment variables, never in code
  • Implement proper error handling for OAuth failures
  • Consider implementing additional verification for critical operations
  • Regularly rotate OAuth client secrets

Troubleshooting

Common Issues

  • Invalid redirect URI - Ensure redirect URIs in OAuth apps match exactly
  • Missing scopes - Configure required OAuth scopes in your app settings
  • HTTPS requirement - Facebook requires HTTPS in production
  • Rate limiting - OAuth providers may limit requests

Need Help?

For additional support or questions about social login implementation, please contact our development team.

Back to Documentation