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

Sentinel Laravel Package

laravel/sentinel

Laravel package providing Sentinel integration for authentication and authorization in Laravel apps. Adds user management, roles and permissions, login/registration flows, and easy setup for Cartalyst Sentinel-backed projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel/sentinel
    php artisan sentinel:install
    
    • Publishes migrations, config, and views to your project.
    • Runs migrations to create Sentinel’s database tables (users, roles, permissions, throttle, etc.).
  2. Configuration:

    • Publish the config file:
      php artisan vendor:publish --provider="Sentinel\SentinelServiceProvider" --tag="config"
      
    • Update config/sentinel.php to match your app’s needs (e.g., throttle settings, remember_token expiry).
  3. First Use Case:

    • Authenticate a user:
      use Sentinel\Sentinel;
      
      $credentials = ['email' => 'user@example.com', 'password' => 'password123'];
      $user = Sentinel::authenticate($credentials);
      
      if ($user) {
          // User is authenticated
          return redirect()->intended('/dashboard');
      }
      
    • Check permissions:
      if (Sentinel::check('edit_posts')) {
          // User has permission
      }
      
    • Protect a route (in routes/web.php):
      Route::get('/admin', function () {
          // Admin-only content
      })->middleware('auth:sentinel');
      
  4. Create a User:

    $user = Sentinel::registerAndActivate([
        'email'    => 'user@example.com',
        'password' => 'password123',
        'first_name' => 'John',
        'last_name'  => 'Doe',
    ]);
    
  5. Assign Roles/Permissions:

    $role = Sentinel::findRoleByName('admin');
    $user->roles()->attach($role);
    
    $permission = Sentinel::findPermissionByName('edit_posts');
    $user->givePermissionTo($permission);
    

Where to Look First

  • Documentation: Start with the official docs for setup and core concepts.
  • Config File: config/sentinel.php – Customize throttling, remember tokens, and other settings.
  • Migrations: database/migrations/ – Review Sentinel’s schema to avoid conflicts with existing tables.
  • Middleware: app/Http/Middleware/ – Check for custom auth middleware extending Sentinel’s functionality.
  • Events: app/Providers/EventServiceProvider.php – Listen to Sentinel events (e.g., auth.attempting, auth.failed) for custom logic.

Implementation Patterns

Usage Patterns

1. Authentication Workflows

  • Basic Login:
    $user = Sentinel::authenticate($credentials);
    if ($user) {
        // Success
    }
    
  • Remember Me:
    $user = Sentinel::authenticate($credentials, true); // Second param enables "remember me"
    
  • Logout:
    Sentinel::logout();
    

2. Role-Based Access Control (RBAC)

  • Check Role:
    if (Sentinel::check('admin')) {
        // Admin-only logic
    }
    
  • Assign Role to User:
    $user->roles()->attach(Sentinel::findRoleByName('editor'));
    
  • Check Permission:
    if (Sentinel::check('publish_articles')) {
        // User has permission
    }
    

3. Throttling and Security

  • Throttle Failed Attempts: Sentinel automatically throttles failed login attempts (configurable in config/sentinel.php).
  • Check Throttle Status:
    if (Sentinel::throttler()->isThrottled($credentials['email'])) {
        abort(429, 'Too many attempts. Try again later.');
    }
    

4. Password Management

  • Reset Password:
    $user = Sentinel::findById(1);
    $user->password = 'new_secure_password';
    $user->save();
    
  • Generate Reset Link: Use the built-in Password facade or extend with custom logic.

5. API Authentication

  • Generate API Tokens:
    $token = Sentinel::personalAccessTokens()->create([
        'name' => 'API Token',
        'abilities' => ['read', 'write'],
    ]);
    
  • Authenticate API Requests: Use Laravel’s built-in auth:sanctum or auth:api middleware alongside Sentinel for hybrid auth.

6. Testing

  • Mock Authentication:
    $user = Sentinel::findById(1);
    Sentinel::actingAs($user);
    
  • Test Throttling:
    $this->actingAs($user);
    $this->post('/login', $credentials)->assertSessionHasErrors();
    

Workflows

1. User Onboarding

  • Registration: Use Sentinel::registerAndActivate() for manual registration or extend with a form handler.
  • Email Verification: Integrate with Laravel’s MustVerifyEmail or custom logic to send verification emails.

2. Admin Panel

  • Role-Based Routes:
    Route::group(['middleware' => ['auth:sentinel', 'role:admin']], function () {
        // Admin-only routes
    });
    
  • Permission Checks:
    if (Sentinel::check('manage_users')) {
        // Show user management UI
    }
    

3. Multi-Factor Authentication (MFA)

  • Enable MFA: Extend Sentinel with a custom guard or use a package like laravel-two-factor-auth alongside Sentinel.
  • Verify MFA:
    if (Sentinel::mfa()->verify($user, $code)) {
        // MFA successful
    }
    

4. Social Logins

  • OAuth Integration: Use laravel/socialite alongside Sentinel to handle social logins, then attach Sentinel roles/permissions post-login.
  • Example:
    $socialUser = Socialite::driver('github')->user();
    $user = Sentinel::findByCredentials(['email' => $socialUser->email]);
    if (!$user) {
        $user = Sentinel::registerAndActivate([
            'email' => $socialUser->email,
            'password' => Str::random(16), // Dummy password
            'first_name' => $socialUser->name,
        ]);
    }
    Sentinel::login($user);
    

5. Audit Logging

  • Listen to Events:
    Event::listen('auth.attempting', function ($credentials) {
        Log::info('Login attempt for: ' . $credentials['email']);
    });
    
  • Track Failed Logins: Sentinel logs failed attempts to the throttle table by default.

Integration Tips

1. Leverage Laravel’s Ecosystem

  • Use Laravel Mixins: Extend Sentinel’s user model with custom methods:
    namespace App\Extensions;
    
    use Sentinel\User;
    
    class UserExtension {
        public function extend(User $user) {
            $user->macro('isPremium', function () {
                return $this->roles()->where('name', 'premium')->exists();
            });
        }
    }
    
  • Integrate with Notifications: Send password reset emails or MFA codes using Laravel’s Notification system.

2. Custom Guards

  • Extend Sentinel’s Guard: Create a custom guard for specific use cases (e.g., API-only auth):
    namespace App\Guards;
    
    use Sentinel\Guards\Guard;
    
    class ApiGuard extends Guard {
        public function check() {
            // Custom logic
        }
    }
    
  • Register Guard:
    Sentinel::extend('api', function ($app) {
        return new ApiGuard();
    });
    

3. Database Drivers

  • Switch Drivers: Configure config/sentinel.php to use Redis or another driver for throttling:
    'throttle' => [
        'driver' => 'redis',
        'key' => 'sentinel.throttle',
    ],
    

4. Testing Strategies

  • Unit Tests: Mock Sentinel’s authentication:
    $this->actingAs($user, 'sentinel');
    
  • Feature Tests: Test login flows with throttling:
    $this->post('/login', $credentials)
         ->assertSessionHasErrors()
         ->assertStatus(429); // Throttled
    

5. Performance Optimization

  • Cache Roles/Permissions: Cache role and permission lookups in
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai