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 Sentinel provides a simple, lightweight way to build and manage API health/status endpoints in Laravel. Define checks, aggregate results, and expose a consistent response for monitoring systems and uptime tools, with easy configuration and extensible check classes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/sentinel
    php artisan sentinel:install
    
    • Publishes migrations, config, and views to config/sentinel.php, database/migrations/, and resources/views/vendor/sentinel/.
  2. Database Migration:

    php artisan migrate
    
    • Creates tables for users, roles, permissions, throttle, and reminders.
  3. First Use Case:

    • Authenticate a user:
      use Cartalyst\Sentinel\Sentinel;
      
      $credentials = ['email' => 'user@example.com', 'password' => 'password'];
      $user = Sentinel::authenticate($credentials);
      
    • Check roles/permissions in middleware:
      use Cartalyst\Sentinel\Checkpoints\ThrottlingCheckpoint;
      use Cartalyst\Sentinel\Checkpoints\RoleCheckpoint;
      
      public function handle($request, Closure $next)
      {
          Sentinel::check()->role('admin')->throttle()->pass();
          return $next($request);
      }
      
  4. Key Config:

    • Update config/sentinel.php for:
      • reminder (password reset settings).
      • throttling (failed login attempts).
      • password (strength requirements).

Implementation Patterns

Core Workflows

1. Authentication Flow

  • Login:
    $user = Sentinel::authenticateAndRemember($credentials);
    
  • Logout:
    Sentinel::logout();
    
  • Remember Me:
    $user = Sentinel::authenticate($credentials, true); // Persistent cookie
    

2. Role-Based Access Control (RBAC)

  • Assign Roles:
    $user->roles()->attach($roleId);
    
  • Check Roles in Controllers/Middleware:
    if (Sentinel::check()->role('admin')->pass()) {
        // Admin-only logic
    }
    
  • Dynamic Role Checks:
    $user = Sentinel::getUser();
    if ($user->hasRole('editor') || $user->hasRole('admin')) {
        // Allow access
    }
    

3. Permissions

  • Grant Permissions:
    $permission = Sentinel::getRepository('permission')->create(['name' => 'edit_articles']);
    $user->permissions()->attach($permission);
    
  • Check Permissions:
    if (Sentinel::check()->permission('edit_articles')->pass()) {
        // Allow edit
    }
    

4. Throttling & Security

  • Throttle Logins:
    // Config: config/sentinel.php
    'throttling' => [
        'max_attempts' => 5,
        'lockout_time' => 15, // minutes
    ],
    
  • Check Throttle in Middleware:
    Sentinel::check()->throttle()->pass();
    

5. Password Reminders

  • Trigger Reset:
    $user = Sentinel::findByCredentials(['email' => 'user@example.com']);
    Sentinel::reminder()->send($user);
    
  • Customize Reminder Views: Override resources/views/vendor/sentinel/reminder.blade.php.

6. Social Authentication (Custom)

  • HybridAuth Integration:
    use Hybrid_Auth\HybridAuth;
    
    $hybridauth = new HybridAuth(config('hybridauth'));
    $adapter = $hybridauth->authenticate('Google');
    $userProfile = $adapter->getUserProfile();
    $user = Sentinel::findByCredentials(['email' => $userProfile->email]);
    if (!$user) {
        $user = Sentinel::registerAndActivate($userProfile->email, $password);
    }
    Sentinel::login($user);
    

7. API Token Generation (Sanctum/Passport)

  • Generate Token for Sentinel User:
    use Laravel\Sanctum\PersonalAccessToken;
    
    $user = Sentinel::getUser();
    $token = PersonalAccessToken::createToken($user);
    

Integration Tips

Middleware

  • Replace auth middleware with auth:sentinel in app/Http/Kernel.php:
    'auth:sentinel' => \Cartalyst\Sentinel\Middleware\Authenticate::class,
    
  • Combine with other middleware:
    Route::get('/admin', function () {
        // ...
    })->middleware(['auth:sentinel', 'role:admin']);
    

Events

  • Listen to Auth Events:
    // EventServiceProvider
    protected $listen = [
        'auth.attempting' => ['App\Listeners\LogLoginAttempt'],
        'auth.failed' => ['App\Listeners\AlertOnFailedLogin'],
    ];
    

Testing

  • Mock Auth in Tests:
    use Cartalyst\Sentinel\Testing\SentinelTestCase;
    
    class UserTest extends SentinelTestCase
    {
        public function testAdminAccess()
        {
            $admin = Sentinel::findByCredentials(['email' => 'admin@example.com']);
            $this->actingAs($admin, 'sentinel');
            $this->visit('/admin')->see('Dashboard');
        }
    }
    

CLI Management

  • Manage Roles/Permissions:
    php artisan sentinel:roles
    php artisan sentinel:permissions
    

Gotchas and Tips

Pitfalls

  1. Schema Conflicts:

    • Issue: Existing users table with custom fields may clash with Sentinel’s schema.
    • Fix: Extend the User model or use a custom driver:
      class User extends \Cartalyst\Sentinel\Users\Eloquent\UserModel
      {
          protected $table = 'custom_users';
      }
      
  2. Session Driver Mismatch:

    • Issue: Sentinel defaults to file session driver, which may not scale.
    • Fix: Configure session.driver in .env (e.g., redis) and ensure Sentinel’s remember cookie uses the same driver.
  3. Throttling Database Locks:

    • Issue: Database-backed throttling can block containers in Docker.
    • Fix: Use Redis for throttling:
      'throttling' => [
          'driver' => 'redis',
      ],
      
  4. HybridAuth Deprecation:

    • Issue: hybridauth/hybridauth is unmaintained; social auth requires custom OAuth logic.
    • Fix: Use Laravel Socialite or a maintained OAuth library.
  5. Legacy cartalyst/sentinel Migration:

    • Issue: Some methods (e.g., Sentinel::getUser()) may behave differently.
    • Fix: Test thoroughly and update deprecated method calls.
  6. Permission Caching:

    • Issue: Frequent hasRole()/hasPermission() checks can bloat queries.
    • Fix: Cache roles/permissions in the user model:
      public function getRolesAttribute()
      {
          return $this->roles()->pluck('name')->toArray();
      }
      
  7. Password Reset Token Expiry:

    • Issue: Default token expiry (60 mins) may be too short/long.
    • Fix: Customize in config/sentinel.php:
      'reminder' => [
          'expire' => 30, // minutes
      ],
      
  8. Middleware Order:

    • Issue: auth:sentinel must run before role/permission middleware.
    • Fix: Group middleware in Kernel.php:
      $middlewareGroups['web'] = [
          \App\Http\Middleware\EncryptCookies::class,
          \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
          \Illuminate\Session\Middleware\StartSession::class,
          // Sentinel middleware must come after session starts
          \Cartalyst\Sentinel\Middleware\Authenticate::class,
          \App\Http\Middleware\CheckForRoles::class,
      ];
      

Debugging Tips

  1. Enable Sentinel Logging:

    'logging' => [
        'enabled' => true,
        'path' => storage_path('logs/sentinel.log'),
    ],
    
  2. Check Throttle Status:

    $throttle = Sentinel::getThrottle();
    dd($throttle->getAttempts(), $throttle->isLocked());
    
  3. Inspect Failed Logins:

    php artisan sentinel:throttle-list
    
  4. Verify User Roles/Permissions:

    dd(Sentinel::getUser()->roles, Sentinel::getUser()->permissions);
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony