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

User Laravel Package

inisiatif/user

inisiatif/user adalah paket autentikasi untuk aplikasi Inisiatif Zakat Indonesia. Mendukung Laravel 9–11 dan PHP 8.1–8.3, menyediakan migrasi, konfigurasi nama tabel, serta opsi mengganti model (User, Branch, Employee, dll).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require inisiatif/user
    php artisan vendor:publish --tag=user-migrations
    php artisan vendor:publish --tag=user-config
    php artisan migrate
    
  2. Configure Authentication Provider Update config/auth.php:

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => Inisiatif\Package\User\Models\User::class,
        ],
    ],
    
  3. Register Routes Add to routes/api.php:

    use Inisiatif\Package\User;
    User\Routes::authToken();
    User\Routes::userToken();
    User\Routes::userProfile();
    User\Routes::personalIdentification();
    

First Use Case

Login via Token API

POST /auth/token
Headers: Accept: application/json
Body: { "email": "user@example.com", "password": "password123" }

Implementation Patterns

Core Workflows

1. User Management

  • Create/Update Users Extend Inisiatif\Package\User\Models\User or use its traits for custom logic.

    $user = new \Inisiatif\Package\User\Models\User();
    $user->name = 'John Doe';
    $user->email = 'john@example.com';
    $user->password = bcrypt('password123');
    $user->save();
    
  • Role-Based Access Use branch_id and employee_id/volunteer_id fields to associate users with roles:

    $user->branch()->associate($branch);
    $user->employee()->associate($employee); // or volunteer()
    $user->save();
    

2. Token-Based Authentication

  • Generate/Revoke Tokens

    // Generate token (via API POST /auth/token)
    $token = $user->createToken('API Token')->accessToken;
    
    // Revoke token (via API DELETE /auth/token)
    $user->tokens()->where('id', $tokenId)->delete();
    
  • List User Tokens

    $tokens = auth()->user()->tokens;
    

3. PIN Management

  • Update PIN
    $user->update(['pin' => '1234']);
    
    Validate via API PUT /personal-identification-number with:
    {
      "current_pin": "old_pin",
      "new_pin": "new_pin"
    }
    

4. Passport OAuth2 (v3.3+)

  • Configure OAuth Update config/services.php:
    'passport' => [
        'client_id' => env('INISIATIF_PASSPORT_CLIENT_ID'),
        'callback_url' => env('INISIATIF_PASSPORT_CALLBACK_URL'),
        'base_url' => env('INISIATIF_PASSPORT_BASE_URL', 'http://me.inisiatif.id'),
    ],
    
    Register routes in routes/web.php:
    User\Routes::passport();
    
    Redirect users to /oauth/passport/redirect for OAuth flow.

Integration Tips

Laravel Sanctum

  • Disable SSL Verification (Dev Only) Set in .env:
    INISIATIF_PASSPORT_SSL_DISABLE=true
    
    Configure Sanctum middleware in app/Http/Kernel.php:
    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Inisiatif\Package\User\Http\Middleware\VerifyUser::class,
    ],
    

Custom Guards

  • Extend Default Guard Override app/Providers/AuthServiceProvider.php:
    public function boot()
    {
        $this->app['auth']->extend('custom', function ($app) {
            return new \Inisiatif\Package\User\Auth\CustomGuard(
                $app['auth']->createUserProvider(),
                $app['request']
            );
        });
    }
    

API Rate Limiting

  • Limit Token Endpoints Add to app/Http/Kernel.php:
    'api' => [
        \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    
    Configure in app/Providers/RouteServiceProvider.php:
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • Issue: Running php artisan migrate without publishing migrations may cause conflicts if table names differ.
    • Fix: Always publish migrations first:
      php artisan vendor:publish --tag=user-migrations
      
  2. PIN Validation Bypass

    • Issue: Directly updating pin in the database bypasses validation (e.g., max attempts).
    • Fix: Use the API endpoint PUT /personal-identification-number or call the updatePin method in the service layer.
  3. Passport SSL Errors (Dev)

    • Issue: Local Passport OAuth fails due to SSL verification.
    • Fix: Enable INISIATIF_PASSPORT_SSL_DISABLE=true in .env (for development only).
  4. Model Binding Quirks

    • Issue: auth()->user() may return null if the guard isn’t properly configured.
    • Fix: Ensure auth.providers.users.model points to Inisiatif\Package\User\Models\User.
  5. Token Expiry Handling

    • Issue: Tokens with expired_at = null never expire.
    • Fix: Set a default expiry in the createToken call:
      $token = $user->createToken('API Token')->accessToken;
      $token = $user->createToken('API Token', ['expires_at' => now()->addDays(30)])->accessToken;
      

Debugging Tips

  1. Log Failed Logins

    • Enable debug mode in .env:
      APP_DEBUG=true
      
    • Check logs for PIN attempt failures:
      tail -f storage/logs/laravel.log | grep "pin_attempt"
      
  2. Inspect Token Generation

    • Dump token payload:
      $token = auth()->user()->createToken('Test')->plainTextToken;
      \Log::info('Token Payload:', ['token' => $token]);
      
  3. Verify Route Registration

    • Check if routes are loaded:
      php artisan route:list | grep "auth/token\|user-token\|user-information"
      

Extension Points

  1. Custom User Attributes

    • Extend the User model:
      namespace App\Models;
      
      use Inisiatif\Package\User\Models\User as BaseUser;
      
      class User extends BaseUser
      {
          protected $casts = [
              'is_active' => 'boolean',
              'custom_field' => 'string',
          ];
      }
      
    • Update config/user.php:
      'models' => [
          'user' => App\Models\User::class,
      ],
      
  2. Override PIN Logic

    • Extend the PinAttempt logic in app/Providers/AppServiceProvider.php:
      use Inisiatif\Package\User\Services\PinService;
      
      public function register()
      {
          $this->app->bind(PinService::class, function ($app) {
              return new class extends PinService {
                  protected function maxAttempts(): int
                  {
                      return 5; // Custom max attempts
                  }
              };
          });
      }
      
  3. Add Custom Routes

    • Extend the Routes class:
      namespace App\Providers;
      
      use Inisiatif\Package\User\Routes as BaseRoutes;
      
      class RouteServiceProvider extends ServiceProvider
      {
          public function boot()
          {
              BaseRoutes::authToken();
              Route::prefix('custom')->group(function () {
                  Route::get('/profile', [UserController::class, 'customProfile']);
              });
          }
      }
      
  4. Custom Passport Scopes

    • Add scopes to the User model:
      use Laravel\Passport\HasApiTokens;
      
      class User extends BaseUser
      {
          use HasApiTokens;
      
          public function getScopesAttribute()
          {
              return ['read', 'write']; // Custom scopes
          }
      }
      

Configuration Quirks

  1. Table Name Overrides
    • Use dot notation for PostgreSQL schemas:
      INISIATIF_USER_TABLE_NAME_USERS=public.users
      
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.
iio/libmergepdf
redaxo/project
zatona-eg/zatona-eg-api
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
ardenexal/fhir-models
ardenexal/fhir-validation
dpfx/laravel-livewire-wizards
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
crudly/encrypted
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony