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

baks-dev/auth-yandex

Laravel/PHP пакет для авторизации пользователей через Yandex ID. Установка через Composer, настройка redirect URL и переменных окружения YANDEX_CLIENT_ID/YANDEX_CLIENT_SECRET. Включает установку ассетов, миграции Doctrine и тесты PHPUnit.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require baks-dev/auth-yandex
    
  2. Run Asset Installation

    php artisan baks:assets:install
    

    (Note: Requires Symfony CLI or Laravel to bridge Symfony commands. Use php artisan vendor:publish --provider="BaksDev\AuthYandex\AuthYandexServiceProvider" if assets fail.)

  3. Configure .env

    YANDEX_CLIENT_ID=your_yandex_client_id
    YANDEX_CLIENT_SECRET=your_yandex_client_secret
    YANDEX_REDIRECT_URI=https://yourdomain.com/auth/yandex/callback
    
  4. Add Routes In routes/web.php:

    Route::get('/auth/yandex', [\BaksDev\AuthYandex\Controller\AuthController::class, 'redirectToYandex']);
    Route::get('/auth/yandex/callback', [\BaksDev\AuthYandex\Controller\AuthController::class, 'handleCallback']);
    
  5. Run Migrations

    php artisan doctrine:migrations:diff
    php artisan doctrine:migrations:migrate
    

    (For Laravel, translate Doctrine migrations to Eloquent or use laravel-doctrine/orm bridge.)

  6. Test the Flow

    • Visit /auth/yandex to trigger Yandex OAuth.
    • Verify the callback populates the users table with Yandex data.

Implementation Patterns

Core Workflow

  1. User Initiation

    • Redirect to Yandex with state parameter:
      $authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl();
      return redirect()->to($authUrl);
      
  2. Callback Handling

    • Exchange code for token in handleCallback():
      $token = \BaksDev\AuthYandex\AuthYandex::getAccessToken($request->query('code'));
      $userData = \BaksDev\AuthYandex\AuthYandex::getUserData($token);
      
  3. User Sync

    • Link Yandex data to Laravel’s users table:
      $user = User::firstOrCreate(
          ['yandex_id' => $userData['id']],
          ['email' => $userData['email']]
      );
      Auth::login($user);
      

Integration Tips

  • Laravel-Symfony Bridge Use symfony/http-client for OAuth requests:

    use Symfony\Contracts\HttpClient\HttpClientInterface;
    $client = app(HttpClientInterface::class);
    
  • Asset Management Replace baks:assets:install with Laravel Mix/Vite:

    // resources/js/yandex-auth.js
    import { YandexAuth } from 'baks-dev/auth-yandex/assets';
    YandexAuth.init({ clientId: 'YANDEX_CLIENT_ID' });
    
  • Custom User Mapping Extend the User model to handle Yandex-specific fields:

    class User extends Authenticatable {
        protected $casts = [
            'yandex_last_login' => 'datetime',
        ];
    }
    
  • Event Listeners Hook into Laravel’s auth events for post-login actions:

    Auth::attempting(function ($user) {
        if ($user->yandex_id) {
            event(new YandexLoginEvent($user));
        }
    });
    
  • Rate Limiting Throttle Yandex API calls:

    use Illuminate\Cache\RateLimiter;
    RateLimiter::for('yandex-auth', function () {
        return Limit::perMinute(5)->by($this->userId());
    });
    

Gotchas and Tips

Pitfalls

  1. Doctrine vs. Eloquent

    • The package uses Doctrine migrations. For Laravel:
      • Option 1: Use laravel-doctrine/orm to integrate Doctrine.
      • Option 2: Manually create Eloquent migrations:
        Schema::table('users', function (Blueprint $table) {
            $table->string('yandex_id')->unique()->nullable();
            $table->timestamp('yandex_last_login')->nullable();
        });
        
  2. Symfony Console Commands

    • Commands like baks:assets:install won’t work natively. Use:
      php artisan vendor:publish --provider="BaksDev\AuthYandex\AuthYandexServiceProvider"
      
    • Or rewrite commands in Laravel’s Console namespace.
  3. State Parameter Handling

    • Yandex OAuth requires a state parameter for CSRF protection. Implement in Laravel:
      $state = Str::random(40);
      session(['yandex_oauth_state' => $state]);
      $authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl(['state' => $state]);
      
  4. Token Storage

    • The package may store tokens in Symfony’s cache. Replace with Laravel’s cache:
      Cache::put('yandex_token_' . $user->id, $token, now()->addHours(1));
      
  5. Error Handling

    • Yandex API errors may not integrate with Laravel’s exception handler. Extend:
      try {
          $token = \BaksDev\AuthYandex\AuthYandex::getAccessToken($code);
      } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
          throw new \App\Exceptions\YandexAuthException($e->getMessage());
      }
      
  6. Asset Paths

    • Published assets may use Symfony’s asset() helper. Replace with Laravel’s:
      // In Blade:
      <script src="{{ asset('vendor/baks-dev/auth-yandex/js/yandex-auth.js') }}"></script>
      

Debugging Tips

  • Enable Yandex Debug Mode Add to .env:

    YANDEX_DEBUG=true
    

    (If supported; check package docs for custom debug flags.)

  • Log OAuth Responses Use Laravel’s logging to inspect Yandex API responses:

    \Log::debug('Yandex User Data', $userData);
    
  • Test with Mock API Mock Yandex’s OAuth endpoint in Laravel’s Http facade:

    Http::fake([
        'oauth.yandex.ru' => Http::response(['id' => '123'], 200),
    ]);
    

Extension Points

  1. Custom User Provider Extend Laravel’s UserProvider to fetch users via Yandex:

    class YandexUserProvider implements UserProvider {
        public function retrieveByYandexId($identifier) {
            return User::where('yandex_id', $identifier)->first();
        }
    }
    
  2. Additional Scopes Request extra Yandex permissions:

    $authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl([
        'scope' => ['login:email', 'login:info'],
    ]);
    
  3. Post-Auth Actions Trigger actions after Yandex login:

    Auth::login($user, function ($user) {
        event(new YandexLoginEvent($user));
        // Send welcome email, log activity, etc.
    });
    
  4. Multi-Tenant Support Scope Yandex credentials per tenant:

    config(['auth-yandex.client_id' => Tenant::current()->yandex_client_id]);
    
  5. Webhook Integration Listen for Yandex account updates via webhooks:

    Route::post('/yandex-webhook', [YandexWebhookController::class, 'handle']);
    

Configuration Quirks

  • Redirect URI Validation Yandex’s dashboard strictly validates redirect URIs. Ensure:

    YANDEX_REDIRECT_URI=https://yourdomain.com/auth/yandex/callback
    

    Matches exactly (including https vs. http).

  • CORS Issues If using SPA, ensure Yandex’s CORS policy allows your domain. Add to .env:

    YANDEX_ALLOWED_DOMAINS=yourdomain.com,staging.yourdomain.com
    
  • PHP Version Mismatch The package requires PHP 8.4+. If using Laravel 10 (PHP 8.2), pin dependencies or use a polyfill like php84-polyfill.

Performance Optimizations

  • Lazy-Load User Data Avoid fetching Yandex data on every request:

    $user->loadMissing('yandexData');
    
  • Batch Token Refresh Refresh

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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony