Weave 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

Userauthcenter Laravel Package

mediadotonedev/userauthcenter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require mediadotonedev/userauthcenter:dev-main
    php artisan vendor:publish --tag=userauthcenter-migrations
    php artisan migrate
    

    Publish only the essentials (migrations + config) initially.

  2. Configure API Endpoint Edit config/userauthcenter.php to set your UserAuthCenter API credentials (e.g., base_url, api_key).

  3. First Use Case: OTP Login

    • Publish the controllers and requests (optional for now):
      php artisan vendor:publish --tag=userauthcenter-controllers
      php artisan vendor:publish --tag=userauthcenter-requests
      
    • Add a route in routes/api.php:
      Route::post('/login/otp', [\App\Http\Controllers\Auth\LoginController::class, 'sendOtp']);
      
    • Test with a POST request to /login/otp with a phone field.

Implementation Patterns

Core Workflows

  1. OTP Authentication Flow

    • Send OTP: Use SendOtpRequest (published) or manually validate a phone field. Call the service:
      $response = \App\Services\UserAuthCenterService::sendOtp($phone);
      
    • Verify OTP: Use VerifyOtpRequest and:
      $response = \App\Services\UserAuthCenterService::verifyOtp($phone, $otp);
      
    • Handle Response: Parse the JSON response (e.g., auth_token, user_id) and store it in Laravel’s session or Sanctum.
  2. Password Authentication

    • Use LoginRequest for traditional email/password login:
      $response = \App\Services\UserAuthCenterService::login($email, $password);
      
    • Integrate with Laravel’s Auth::loginUsingId() if syncing local users.
  3. User Management

    • Create User:
      $response = \App\Services\UserAuthCenterService::createUser($data);
      
    • Update User:
      $response = \App\Services\UserAuthCenterService::updateUser($userId, $data);
      

Integration Tips

  • Laravel Auth Integration: Extend App\Models\User to include auth_token and user_id from UserAuthCenter. Override Laravel’s AuthenticatesUsers trait to handle token-based auth:

    protected function guard() {
        return auth()->guard('api'); // Use Sanctum/Passport
    }
    
  • Middleware: Create a middleware to validate UserAuthCenter tokens:

    public function handle($request, Closure $next) {
        $token = $request->bearerToken();
        $response = \App\Services\UserAuthCenterService::validateToken($token);
        if (!$response->success) return redirect('login');
        return $next($request);
    }
    
  • API Routes: Group routes under api.php and prefix with /auth for clarity:

    Route::prefix('auth')->group(function () {
        Route::post('/otp', [LoginController::class, 'sendOtp']);
        Route::post('/verify-otp', [LoginController::class, 'verifyOtp']);
    });
    

Gotchas and Tips

Pitfalls

  1. API Rate Limiting: UserAuthCenter may throttle requests. Cache OTP responses or implement exponential backoff in your service layer:

    try {
        $response = \App\Services\UserAuthCenterService::sendOtp($phone);
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        if ($e->getCode() === 429) {
            sleep(5); // Retry after delay
        }
    }
    
  2. Token Expiry: UserAuthCenter tokens expire. Store expires_at in your database and refresh tokens proactively:

    if (auth()->user()->expires_at < now()) {
        $newToken = \App\Services\UserAuthCenterService::refreshToken(auth()->user()->auth_token);
    }
    
  3. Database Sync: Avoid syncing all UserAuthCenter users locally. Use a sync_users flag in your users table to track which records are managed externally.

  4. Published Files Overwrite: Customizing published files (e.g., LoginController) will be overwritten on updates. Use traits or decorator pattern to extend functionality:

    // app/Http/Controllers/Auth/LoginController.php
    use \App\Http\Controllers\Auth\UserAuthCenterLoginTrait;
    
    class LoginController extends Controller {
        use UserAuthCenterLoginTrait;
    }
    

Debugging

  • Enable Logging: Add this to config/userauthcenter.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  • Mock API Calls: For testing, mock the service layer:

    $mock = Mockery::mock('\App\Services\UserAuthCenterService');
    $mock->shouldReceive('sendOtp')->andReturn(['success' => true]);
    $this->app->instance('\App\Services\UserAuthCenterService', $mock);
    

Extension Points

  1. Custom Rules: Extend UserAuthCenterRules (published) to add validation logic:

    namespace App\Rules;
    use \Mediadotonedev\UserAuthCenter\Rules\UserAuthCenterRules as BaseRules;
    
    class CustomRules extends BaseRules {
        public function phoneExists($attribute, $value) {
            return UserAuthCenterService::checkPhoneExists($value);
        }
    }
    
  2. Webhooks: Listen for UserAuthCenter events (e.g., user.created) via their API webhook endpoint. Store events in Laravel’s failed_jobs table for reprocessing.

  3. Multi-Tenant Support: Override the UserAuthCenterService to include a tenant_id in API requests:

    public static function sendOtp($phone, $tenantId = null) {
        $data = ['phone' => $phone];
        if ($tenantId) $data['tenant_id'] = $tenantId;
        return self::callApi('otp/send', $data);
    }
    
  4. Fallback Mechanisms: Implement a fallback to Laravel’s default auth if UserAuthCenter is down:

    try {
        $response = UserAuthCenterService::verifyOtp($phone, $otp);
    } catch (\Exception $e) {
        return back()->withError('Service unavailable. Using local auth.');
    }
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style