Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Auth Google Laravel Package

baks-dev/auth-google

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/auth-google
    php bin/console baks:assets:install
    
  2. Configure Google OAuth Credentials Add these to .env:

    GOOGLE_CLIENT_ID=your_client_id.apps.googleusercontent.com
    GOOGLE_CLIENT_SECRET=your_client_secret
    
  3. Set Redirect URI In Google Cloud Console, add https://{your-domain}/google/auth to Authorized Redirect URIs.

  4. Run Migrations

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  5. First Use Case Trigger the auth flow via a route or button:

    // In a controller or Blade template
    return redirect()->route('google.auth.login');
    

Implementation Patterns

Core Workflow

  1. Initiate Login Redirect users to Google’s OAuth endpoint:

    use BaksDev\AuthGoogle\Auth\GoogleAuth;
    
    $auth = new GoogleAuth();
    $authUrl = $auth->getAuthorizationUrl();
    return redirect($authUrl);
    
  2. Handle Callback Process the OAuth response in a route:

    Route::get('/google/auth/callback', [AuthController::class, 'handleCallback']);
    
    public function handleCallback(GoogleAuth $auth)
    {
        $userData = $auth->handleCallback(request());
        // Save user data to your DB (e.g., via a User model)
        return redirect()->route('dashboard');
    }
    
  3. User Data Mapping Customize how Google data maps to your user model:

    $auth->setUserMapper(function (array $googleData) {
        return User::updateOrCreate(
            ['email' => $googleData['email']],
            [
                'name' => $googleData['name'],
                'google_id' => $googleData['sub'],
            ]
        );
    });
    

Integration Tips

  • Symfony Forms: Attach a "Login with Google" button to forms:
    <a href="{{ path('google.auth.login') }}" class="btn-google">Sign in with Google</a>
    
  • Middleware: Protect routes requiring Google auth:
    Route::middleware(['auth:google'])->group(function () {
        // Protected routes
    });
    
  • Custom Scopes: Extend default scopes (e.g., for profile/email):
    $auth->setScopes(['profile', 'email', 'openid']);
    

Gotchas and Tips

Pitfalls

  1. Redirect URI Mismatch

    • Issue: Google rejects callbacks if the redirect URI doesn’t match exactly (including http vs https).
    • Fix: Use environment variables for URIs and validate in .env:
      APP_URL=https://your-domain.com
      GOOGLE_REDIRECT_URI={{ APP_URL }}/google/auth
      
  2. Missing Migrations

    • Issue: The package creates a google_users table. Skipping migrations will cause handleCallback() to fail.
    • Fix: Always run php bin/console doctrine:migrations:migrate after installation.
  3. CORS Errors

    • Issue: If using APIs post-auth, ensure your frontend allows requests to Google’s endpoints.
    • Fix: Configure CORS headers in your Symfony app or proxy requests.
  4. Google Workspace Restrictions

    • Issue: Using "Internal" audience requires Google Workspace setup. Public apps must use "External" audience.
    • Fix: Double-check Google Cloud Console settings for your use case.

Debugging

  • Enable Logging Add to config/packages/dev/monolog.yaml:

    handlers:
        google_auth:
            type: stream
            path: "%kernel.logs_dir%/google_auth.log"
            level: debug
    

    Then log auth events:

    $auth->setLogger($this->container->get('logger'));
    
  • Test Locally Use Google’s OAuth Playground to validate scopes/secrets before deploying.

Extension Points

  1. Custom User Model Override the default user mapping:

    $auth->setUserModel(\App\Entity\CustomUser::class);
    
  2. Post-Auth Actions Hook into the auth flow:

    $auth->onAuthSuccess(function ($user) {
        event(new GoogleAuthSuccess($user));
    });
    
  3. Token Refresh Handle token expiration by extending the GoogleAuth class:

    class CustomGoogleAuth extends GoogleAuth {
        public function refreshToken($refreshToken) {
            // Implement custom logic
        }
    }
    
  4. Multi-Tenant Support Add tenant ID to the user mapper:

    $auth->setUserMapper(function (array $googleData) use ($tenantId) {
        return TenantUser::updateOrCreate(
            ['email' => $googleData['email'], 'tenant_id' => $tenantId],
            ['google_id' => $googleData['sub']]
        );
    });
    

Configuration Quirks

  • Environment Variables The package expects GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET without spaces. Validate with:
    php bin/console debug:container | grep google
    
  • Asset Installation Running baks:assets:install is required for templates/JS. Skip it only if you’re not using the default frontend assets.
  • PHP 8.4+ Only The package uses typed properties and attributes. Downgrading will cause runtime errors.

Performance

  • Caching Tokens Cache the OAuth access token to avoid repeated API calls:
    $token = $auth->getAccessToken();
    Cache::put('google_token', $token, now()->addHours(1));
    
  • Lazy Loading Avoid fetching user data on every request. Use a session or cache:
    $user = session('google_user') ?? $auth->getUserData();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor