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 Bundle Laravel Package

anzusystems/auth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

The AnzuSystems Auth Bundle (v5.0.0) is a Laravel-compatible authentication package designed to simplify user management, role-based access control (RBAC), and multi-factor authentication (MFA). To begin:

  1. Installation:

    composer require anzusystems/auth-bundle
    

    Publish the bundle’s configuration and migrations:

    php artisan vendor:publish --provider="AnzuSystems\AuthBundle\AuthBundleServiceProvider" --tag="config"
    php artisan vendor:publish --provider="AnzuSystems\AuthBundle\AuthBundleServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. First Use Case: Register a user via the bundle’s built-in registration controller (if enabled) or manually:

    use AnzuSystems\AuthBundle\Models\User;
    
    $user = User::create([
        'email' => 'user@example.com',
        'password' => bcrypt('securepassword'),
        'roles' => ['admin'] // Example role assignment
    ]);
    

    Authenticate via Laravel’s default Auth::attempt() or the bundle’s extended methods:

    if (auth()->attempt(['email' => 'user@example.com', 'password' => 'securepassword'])) {
        // User is logged in; check roles/permissions:
        if (auth()->user()->hasRole('admin')) {
            // Grant access
        }
    }
    
  3. Key Files:

    • Configuration: config/auth-bundle.php (updated for Symfony 8 compatibility).
    • Models: app/Models/User (extend AnzuSystems\AuthBundle\Models\User).
    • Migrations: database/migrations/[timestamp]_create_auth_bundle_tables.php.

Implementation Patterns

Core Workflows

  1. Role/Permission Management: Assign roles to users during creation or dynamically:

    $user->assignRole('editor');
    $user->revokeRole('guest');
    

    Check permissions in policies or middleware:

    public function handle(Request $request, Closure $next) {
        if (!auth()->user()->hasPermission('delete_posts')) {
            abort(403);
        }
        return $next($request);
    }
    
  2. MFA Integration: Enable MFA for users via the bundle’s trait:

    use AnzuSystems\AuthBundle\Traits\HasMultiFactorAuth;
    
    class User extends Authenticatable {
        use HasMultiFactorAuth;
    }
    

    Trigger MFA verification during login:

    if (auth()->attempt($credentials) && auth()->user()->requiresMfa()) {
        return redirect()->route('mfa.verify');
    }
    
  3. Customization: Extend the User model or override bundle views (published in resources/views/vendor/auth-bundle). Example: Custom login form:

    // app/Http/Controllers/Auth/LoginController.php
    public function __construct() {
        $this->middleware('guest')->except('logout');
        $this->authenticationGuard = 'auth-bundle'; // Use bundle's guard
    }
    

Integration Tips

  • Laravel Fortify/Sanctum: The bundle plays well with Laravel’s ecosystem. For Sanctum, ensure the auth-bundle guard is configured in config/auth.php.
  • API Routes: Protect API endpoints with the bundle’s middleware:
    Route::middleware(['auth:auth-bundle', 'role:admin'])->group(function () {
        // Admin-only routes
    });
    
  • Event Listeners: Listen to auth events (e.g., LoggedIn, MfaVerified) by extending the bundle’s events:
    use AnzuSystems\AuthBundle\Events\LoggedIn;
    
    LoggedIn::dispatch($user);
    

Gotchas and Tips

Breaking Changes (v5.0.0)

  • Symfony 8 Compatibility:
    • The bundle now drops support for older Symfony components. Ensure your Laravel app (v9+) and dependencies (e.g., symfony/http-foundation) are updated.
    • Action Required: Update composer.json to require ^5.0 of the bundle and resolve Symfony version conflicts:
      composer update anzusystems/auth-bundle --with-dependencies
      

Common Pitfalls

  1. Migration Conflicts:

    • If upgrading from v4.x, reset migrations or merge custom columns (e.g., users table) before running php artisan migrate.
    • Tip: Use --pretend to preview changes:
      php artisan migrate --pretend
      
  2. Guard Configuration:

    • The bundle defaults to auth-bundle guard. If using Laravel’s default web guard, explicitly set:
      Auth::guard('web')->attempt(...); // Fallback
      
    • Tip: Verify config/auth.php includes the bundle’s guard:
      'guards' => [
          'auth-bundle' => [
              'driver' => 'session',
              'provider' => 'auth-bundle',
          ],
      ],
      
  3. Role Hierarchy:

    • Roles are not hierarchical by default. Use the Role model’s children() method to enforce inheritance:
      $adminRole = Role::findByName('admin');
      $editorRole = Role::findByName('editor');
      $adminRole->children()->attach($editorRole); // Editor inherits admin permissions
      

Debugging Tips

  • Log Auth Events: Configure Monolog in config/auth-bundle.php to log failed attempts:
    'logging' => [
        'enabled' => true,
        'channel' => 'auth',
    ],
    
  • MFA Debugging: Clear MFA secrets during testing:
    auth()->user()->clearMfaSecret();
    
  • Permission Caching: Clear cached permissions after role changes:
    auth()->user()->clearPermissionCache();
    

Extension Points

  1. Custom Providers: Override the default UserProvider by binding a custom implementation in the service provider:

    $this->app->bind(
        \AnzuSystems\AuthBundle\Contracts\UserProvider::class,
        \App\Providers\CustomUserProvider::class
    );
    
  2. Database Schema: Extend the users table by publishing and modifying the migration:

    php artisan vendor:publish --tag="auth-bundle-migrations"
    

    Then add columns (e.g., custom_field) and update the model.

  3. API Tokens: Integrate with Laravel Sanctum by extending the User model:

    use Laravel\Sanctum\HasApiTokens;
    
    class User extends Authenticatable {
        use HasApiTokens, HasMultiFactorAuth;
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware