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

Bartender Laravel Package

directorytree/bartender

Opinionated Laravel Socialite auth starter. Ships ready-made routes (/auth/{driver}/redirect, /callback), controller, and user columns for provider ID/name plus optional access/refresh tokens. Highly customizable; supports soft deletes and email verification.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require directorytree/bartender
    php artisan vendor:publish --provider="DirectoryTree\Bartender\BartenderServiceProvider"
    php artisan migrate
    
  2. Configure Routes: In routes/web.php:

    use DirectoryTree\Bartender\Facades\Bartender;
    Bartender::routes();
    
  3. Register Providers: In AppServiceProvider:

    Bartender::serve('google'); // Replace 'google' with your provider
    
  4. Add Login Links (Blade):

    <a href="{{ route('auth.driver.redirect', 'google') }}">Login with Google</a>
    

First Use Case: Google OAuth Login

  • Add a Google provider link to your login page.
  • Clicking it redirects to Google for authentication.
  • After successful auth, the user is automatically registered/logged in and redirected to the default route (e.g., dashboard).

Implementation Patterns

Core Workflow

  1. Provider Registration:

    • Use Bartender::serve('provider_name') in AppServiceProvider to enable a provider (e.g., Google, Microsoft).
    • Configure the provider in config/services.php with the correct redirect URL (e.g., /auth/google/callback).
  2. Customizing User Creation:

    • Override the default ProviderRepository to customize user creation logic (e.g., linking existing users, setting attributes).
    • Bind your custom repository in AppServiceProvider:
      $this->app->bind(ProviderRepository::class, CustomUserProviderRepository::class);
      
  3. Handling Tokens:

    • Implement StoresProviderTokens in your User model to store access/refresh tokens.
    • Secure tokens with $hidden and $casts:
      protected $hidden = ['provider_access_token', 'provider_refresh_token'];
      protected function casts(): array { return ['provider_access_token' => 'encrypted']; }
      
  4. Redirect Logic:

    • Customize redirects (e.g., after login, failed auth) by implementing ProviderRedirector.
    • Bind your custom redirector in AppServiceProvider:
      $this->app->bind(ProviderRedirector::class, CustomProviderRedirector::class);
      
  5. Scopes and Provider-Specific Logic:

    • Extend UserProviderHandler for provider-specific behavior (e.g., scopes for Microsoft):
      class MicrosoftUserHandler extends UserProviderHandler {
          public function redirect(Provider $provider, string $driver): RedirectResponse {
              $provider->scopes(['Mail.ReadWrite']);
              return parent::redirect($provider, $driver);
          }
      }
      
    • Register the handler:
      Bartender::serve('microsoft', MicrosoftUserHandler::class);
      

Integration Tips

  • Leverage Socialite Providers: Ensure you’ve installed and configured the base Socialite provider (e.g., socialiteproviders/google).
  • Session Security: Always regenerate the session after login to prevent session fixation:
    Session::regenerate();
    
  • Testing: Use Bartender::fake() in tests to mock provider responses:
    Bartender::fake('google')->shouldReturnUser([
        'id' => 123,
        'name' => 'Test User',
        'email' => '[email protected]',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Missing Provider Setup:

    • Error: Driver [X] not supported.
    • Fix: Ensure you’ve installed the Socialite provider package (e.g., socialiteproviders/google) and registered it with Bartender::serve().
  2. Route Requirements:

    • Error: Routing requirement for "driver" cannot be empty.
    • Fix: Forgetting to register the provider with Bartender::serve() in AppServiceProvider.
  3. Token Storage:

    • If you don’t need tokens, delete the migration 2024_10_27_131354_add_provider_token_columns_to_users_table.php and omit StoresProviderTokens.
  4. Guarded Attributes:

    • Issue: User attributes not updating due to $guarded in the model.
    • Fix: Use forceFill() in your custom ProviderRepository:
      $user->forceFill(['email' => $user->email])->save();
      
  5. Email Verification:

    • By default, Bartender auto-verifies emails. To disable, override updateOrCreate() in ProviderRepository.

Debugging Tips

  • Check Provider Responses: Use dd($socialiteUser) in a custom ProviderHandler to inspect the raw provider data.
  • Log Redirects: Add dd($driver) in ProviderRedirector methods to debug redirect paths.
  • Test Locally: Use Bartender::fake() to simulate provider responses without hitting external APIs.

Extension Points

  1. Custom User Model:

    • Set the user model via Bartender::setUserModel(User::class) if it’s not in App\Models\User.
  2. Password Handling:

    • Override hashPassword() in ProviderRepository to use a custom hashing mechanism:
      public function hashPassword(string $password): string {
          return Hash::make($password . '_custom_salt');
      }
      
  3. Soft Deletes:

    • Disable auto-restoring soft-deleted users by modifying exists() in ProviderRepository:
      public function exists(string $driver, SocialiteUser $user): bool {
          return User::where('email', $user->email)->doesntExist(); // Custom logic
      }
      
  4. Multi-Provider Merging:

    • Extend ProviderRepository to merge users from multiple providers (e.g., Google + Microsoft):
      public function updateOrCreate(string $driver, SocialiteUser $user): Authenticatable {
          return User::firstOrCreate(
              ['email' => $user->email],
              ['provider_id' => $user->id, 'provider_name' => $driver]
          );
      }
      

Performance

  • Avoid N+1 Queries: Use withTrashed() sparingly in ProviderRepository to minimize queries.
  • Cache Provider Config: Cache the Socialite provider instances if using multiple providers frequently.

Security

  • Token Encryption: Always encrypt provider_access_token and provider_refresh_token if storing them.
  • Scopes: Limit provider scopes to only what’s necessary (e.g., avoid openid profile email if you only need email).
  • CSRF: Ensure your provider callbacks are protected by CSRF middleware (Bartender handles this by default).
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle