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

Ti Ext Socialite Laravel Package

tastyigniter/ti-ext-socialite

TastyIgniter Socialite extension adds social login/registration for customers via Laravel Socialite. Supports Facebook, Google, Twitter and more, with an extensible adapter-based approach and customizable integration for your TastyIgniter site.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Install the Package

    composer require tastyigniter/ti-ext-socialite
    

    Publish the configuration and migrations:

    php artisan vendor:publish --provider="TastyIgniter\Socialite\SocialiteServiceProvider"
    php artisan migrate
    
  2. Configure Providers Add your OAuth credentials to .env:

    SOCIALITE_FACEBOOK_CLIENT_ID=your_app_id
    SOCIALITE_FACEBOOK_CLIENT_SECRET=your_app_secret
    SOCIALITE_GOOGLE_CLIENT_ID=your_client_id
    SOCIALITE_GOOGLE_CLIENT_SECRET=your_client_secret
    
  3. Add Routes Include the package routes in routes/web.php:

    Route::socialite();
    
  4. Add Login Buttons Use the provided Blade components in your login view:

    @socialiteButton('facebook')
    @socialiteButton('google')
    
  5. Handle User Creation Override the default user mapping in app/Providers/SocialiteServiceProvider.php:

    public function mapFacebookUserToModel(User $user, array $attributes)
    {
        $user->name = $attributes['name'];
        $user->email = $attributes['email'] ?? $attributes['email_verified'] ? $attributes['email'] : null;
        $user->save();
    }
    
  6. Test the Flow

    • Visit your login page and click a social button.
    • Verify the redirect and user creation in your database.

First Use Case: Quick Social Login for E-Commerce

For a TastyIgniter-based e-commerce site, implement social login on the checkout page to reduce cart abandonment:

  1. Add social buttons to the checkout view:
    @socialiteButton('google', ['class' => 'btn btn-primary'])
    
  2. Redirect authenticated users to their cart:
    // In SocialiteServiceProvider.php
    public function handleSuccessfulLogin(User $user)
    {
        return redirect()->route('cart.show');
    }
    
  3. Use events to auto-assign roles:
    // In EventServiceProvider.php
    public function boot()
    {
        SocialiteEvents::registered(function ($user) {
            $user->assignRole('customer');
        });
    }
    

Implementation Patterns

Core Workflows

1. Provider-Specific Authentication

  • Pattern: Use the Socialite facade to handle OAuth flows:
    use TastyIgniter\Socialite\Facades\Socialite;
    
    $user = Socialite::driver('facebook')->stateless()->user();
    
  • When to Use: For custom logic outside the default flow (e.g., admin dashboards).

2. User Mapping and Registration

  • Pattern: Override the default user mapping in SocialiteServiceProvider:
    public function mapGoogleUserToModel(User $user, array $attributes)
    {
        $user->name = $attributes['name'];
        $user->email = $attributes['email'];
        $user->avatar = $attributes['picture'] ?? null;
        $user->save();
    }
    
  • When to Use: When social provider fields don’t align with your User model.

3. Event-Driven Extensions

  • Pattern: Listen to built-in events for custom logic:
    SocialiteEvents::registered(function ($user) {
        // Send welcome email
        Mail::to($user->email)->send(new WelcomeEmail($user));
    });
    
    SocialiteEvents::failed(function ($exception) {
        Log::error('Socialite failed: ' . $exception->getMessage());
    });
    
  • When to Use: To trigger actions like email verification, role assignment, or analytics.

4. Multi-Tenant Support

  • Pattern: Scope users to tenants in the map*UserToModel methods:
    public function mapFacebookUserToModel(User $user, array $attributes)
    {
        $tenant = Tenant::find(request('tenant_id'));
        $user->tenant_id = $tenant->id;
        $user->save();
    }
    
  • When to Use: For SaaS or multi-tenant applications.

5. Custom Provider Integration

  • Pattern: Use Socialite Providers to add unsupported providers:
    composer require socialiteproviders/manager
    composer require socialiteproviders/github
    
    Then register the provider in config/socialite.php:
    'providers' => [
        'github' => [
            'client_id' => env('GITHUB_CLIENT_ID'),
            'client_secret' => env('GITHUB_CLIENT_SECRET'),
            'redirect' => env('GITHUB_REDIRECT_URI'),
        ],
    ],
    
  • When to Use: To support providers like GitHub, LinkedIn, or Discord.

Integration Tips

Blade Components

  • Use the provided components for consistent UI:
    @socialiteButton('twitter', [
        'class' => 'btn btn-twitter',
        'title' => 'Login with Twitter'
    ])
    
  • Customize the component in resources/views/vendor/socialite/button.blade.php.

Route Caching

  • After adding routes, run:
    php artisan route:cache
    

Testing

  • Use the SocialiteTestCase trait for unit tests:
    use TastyIgniter\Socialite\Tests\SocialiteTestCase;
    
    class SocialiteTest extends SocialiteTestCase
    {
        public function testGoogleLogin()
        {
            $response = $this->get('/auth/google');
            $response->assertRedirect();
        }
    }
    

Debugging OAuth Flows

  • Enable Socialite logging in .env:
    SOCIALITE_DEBUG=true
    
  • Check logs for redirect URIs and token errors.

Gotchas and Tips

Pitfalls

1. CSRF Token Mismatches

  • Issue: Social login routes may fail with TokenMismatchException if CSRF protection is too strict.
  • Fix: Exclude social routes from CSRF verification in app/Http/Middleware/VerifyCsrfToken.php:
    protected $except = [
        'socialite/*',
    ];
    

2. Provider-Specific Field Mappings

  • Issue: Some providers (e.g., Facebook) return email_verified instead of email. Unverified emails may cause registration failures.
  • Fix: Validate and handle missing/verified fields in map*UserToModel:
    $user->email = $attributes['email_verified'] ? $attributes['email'] : null;
    

3. State Parameter Attacks

  • Issue: Socialite uses a state parameter for CSRF protection, but custom implementations may break this.
  • Fix: Ensure your custom routes include the state parameter:
    Route::get('/auth/{provider}/callback', [SocialiteController::class, 'handleProviderCallback']);
    

4. Database Schema Conflicts

  • Issue: The package’s migrations may conflict with existing users table extensions.
  • Fix: Manually adjust the migration or use a custom user model:
    // In SocialiteServiceProvider.php
    protected $userModel = App\Models\CustomUser::class;
    

5. Rate Limiting and Throttling

  • Issue: Social providers (e.g., Google) may throttle requests during testing.
  • Fix: Use the --mock flag in tests:
    $this->mockGoogle();
    

6. Hyphenated Provider Names

  • Issue: Routes like /auth/google-oauth2 may fail if not configured properly.
  • Fix: Ensure your config/socialite.php uses the correct provider name:
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
    ],
    

Debugging Tips

Enable Verbose Logging

Add to config/logging.php:

'socialite' => [
    'driver' => 'single',
    'path' => storage_path('logs/socialite.log'),
    'level' => 'debug',
],

Check Redirect URIs

  • Ensure the redirect URI in .env matches exactly what the provider expects (e.g., https://your-app.com/auth/google/callback).
  • Use SOCIALITE_DEBUG=true to log the full redirect URL.

Test with Mock Providers

Use the SocialiteTestCase trait to mock providers:

public function testFacebookLogin()
{
    $this->mockFacebook();
    $response = $this->get('/auth/facebook');
    $response->assert
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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