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

Socialment Laravel Package

chrisreedio/socialment

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chrisreedio/socialment
    

    Publish the config and migrations:

    php artisan vendor:publish --provider="ChrisReedio\Socialment\SocialmentServiceProvider"
    php artisan migrate
    
  2. Configure Providers: Edit config/socialment.php and add your OAuth credentials (e.g., GitHub, Google, etc.) under the providers key:

    'providers' => [
        'github' => [
            'client_id' => env('GITHUB_CLIENT_ID'),
            'client_secret' => env('GITHUB_CLIENT_SECRET'),
            'redirect' => env('GITHUB_REDIRECT_URI'),
        ],
    ],
    
  3. Enable in Filament Panel: Add the Socialment widget to your Filament panel’s login page in app/Providers/Filament/AdminPanelProvider.php:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->widgets([
                \ChrisReedio\Socialment\Widgets\SocialmentWidget::class,
            ]);
    }
    
  4. First Use Case:

    • A user visits the Filament login page and clicks a GitHub button.
    • They’re redirected to GitHub for OAuth, then back to your app.
    • Socialment handles the token exchange, user creation/update, and logs them in automatically.

Implementation Patterns

Core Workflows

  1. Provider Integration:

    • Dynamic Provider Loading: Use the Socialment::providers() helper to fetch configured providers dynamically in Blade or PHP:
      $providers = Socialment::providers();
      foreach ($providers as $provider) {
          echo $provider->getButton();
      }
      
    • Conditional Rendering: Filter providers by panel or user role in the widget’s configure() method:
      public function configure(): array
      {
          return [
              'providers' => fn () => Socialment::providers()->where('enabled', true),
          ];
      }
      
  2. User Mapping:

    • Custom User Creation: Override the default user creation logic by binding an event listener to Socialment\Events\UserCreated:
      Socialment::userCreated(function (User $user, array $attributes) {
          $user->update(['email_verified_at' => now()]);
      });
      
    • Field Mapping: Customize which OAuth fields map to your user model in config/socialment.php:
      'fields' => [
          'github' => [
              'name' => 'name',
              'email' => 'email',
          ],
      ],
      
  3. Panel-Specific Config:

    • Multi-Panel Support: Configure providers per panel by extending the SocialmentWidget:
      class CustomSocialmentWidget extends SocialmentWidget
      {
          protected static ?string $panel = 'admin';
          protected static ?string $navigationIcon = 'heroicon-o-share-social';
      }
      
  4. SPA Authentication:

    • Token-Based Flow: For SPAs, use the Socialment::redirectToProvider() method to generate signed URLs:
      // Frontend (Vue/React)
      const url = `/socialment/github?callback=${encodeURIComponent(window.location.href)}`;
      window.location.href = url;
      
    • Callback Handling: Set up a route in routes/web.php to handle the OAuth callback:
      Route::get('/socialment/{provider}/callback', [SocialmentController::class, 'handleProviderCallback']);
      
  5. Testing:

    • Mock Providers: Use Socialment::fake() in tests to simulate OAuth responses:
      Socialment::fake([
          'github' => ['id' => 123, 'name' => 'Test User', 'email' => 'test@example.com'],
      ]);
      $response = $this->get('/admin/login')->assertSee('Test User');
      

Gotchas and Tips

Pitfalls

  1. Environment Variables:

    • Missing Redirect URIs: Ensure GITHUB_REDIRECT_URI (or equivalent) matches the callback URL in your provider’s dashboard. Use env('APP_URL') to dynamically generate it:
      'redirect' => env('APP_URL') . '/admin/socialment/github/callback',
      
    • Local Development: Add http://localhost to the "Authorized Callback URLs" in your OAuth provider settings.
  2. User Conflicts:

    • Duplicate Accounts: If a user logs in with the same email via multiple providers, Socialment will create separate accounts. Mitigate this by:
      • Adding a provider_id field to your users table and updating the config/socialment.php fields mapping:
        'fields' => [
            'github' => [
                'provider_id' => 'id',
                'provider_name' => 'github',
            ],
        ],
        
      • Using a package like laravel/socialite to merge accounts manually.
  3. CSRF Issues:

    • Callback Failures: If the callback fails with a CSRF error, ensure your APP_URL is consistent across environments and the VerifyCsrfToken middleware is excluded for the callback route:
      Route::middleware(['web', 'throttle:60'])->group(function () {
          Route::get('/socialment/{provider}/callback', [SocialmentController::class, 'handleProviderCallback']);
      });
      
  4. Provider-Specific Quirks:

    • Google Scopes: Google requires explicit scopes. Add them to the provider config:
      'google' => [
          'scopes' => ['profile', 'email'],
      ],
      
    • LinkedIn Limits: LinkedIn has strict rate limits. Cache user data or use their API sparingly.

Debugging

  1. Log OAuth Errors:

    • Enable debug mode in config/socialment.php:
      'debug' => env('APP_DEBUG', false),
      
    • Check storage/logs/laravel.log for Socialite errors (e.g., invalid credentials).
  2. Token Validation:

    • If tokens fail silently, enable Socialite’s debug mode:
      Socialite::with('github')->useDebugMode();
      
  3. Widget Not Showing:

    • Verify the widget is registered in panel()->widgets() and that no Filament middleware (e.g., auth) is blocking the login page.

Extension Points

  1. Custom Providers:

    • Extend ChrisReedio\Socialment\Providers\Provider to support custom OAuth services:
      class CustomProvider extends Provider
      {
          protected string $name = 'custom';
          protected string $clientIdKey = 'CUSTOM_CLIENT_ID';
      
          public function getAuthUrl(): string
          {
              return 'https://custom-provider.com/oauth/authorize?client_id=' . $this->clientId;
          }
      }
      
    • Register it in config/socialment.php:
      'providers' => [
          'custom' => [
              'class' => \App\Providers\CustomProvider::class,
              'client_id' => env('CUSTOM_CLIENT_ID'),
          ],
      ],
      
  2. Post-Auth Logic:

    • Listen for Socialment\Events\Login to trigger actions after successful login:
      Socialment::login(function (User $user) {
          event(new UserLoggedIn($user));
      });
      
  3. UI Customization:

    • Override the widget’s Blade view (resources/views/vendor/socialment/widget.blade.php) to modify button styles or add labels.
    • Use the button_class config option to apply Tailwind classes:
      'providers' => [
          'github' => [
              'button_class' => 'bg-gray-800 hover:bg-gray-700',
          ],
      ],
      
  4. Rate Limiting:

    • Protect the callback route with Laravel’s throttle middleware to prevent abuse:
      Route::middleware(['throttle:10,1'])->group(function () {
          Route::get('/socialment/{provider}/callback', [SocialmentController::class, 'handleProviderCallback']);
      });
      

Performance Tips

  1. Cache Provider Config:

    • Cache the Socialment::providers() result if called frequently (e.g., in a widget):
      $providers = Cache::remember('socialment.providers', now()->addHours(1), function () {
          return Socialment::providers();
      });
      
  2. Lazy-Load Icons:

    • Use Filament’s Icon component with lazy-loaded SVGs to reduce initial load time:
      $provider->getButton()->icon('heroicon-o-globe-alt')->size('lg'),
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours