baks-dev/auth-yandex
Laravel/PHP пакет для авторизации пользователей через Yandex ID. Установка через Composer, настройка redirect URL и переменных окружения YANDEX_CLIENT_ID/YANDEX_CLIENT_SECRET. Включает установку ассетов, миграции Doctrine и тесты PHPUnit.
Install the Package
composer require baks-dev/auth-yandex
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.)
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
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']);
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.)
Test the Flow
/auth/yandex to trigger Yandex OAuth.users table with Yandex data.User Initiation
$authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl();
return redirect()->to($authUrl);
Callback Handling
handleCallback():
$token = \BaksDev\AuthYandex\AuthYandex::getAccessToken($request->query('code'));
$userData = \BaksDev\AuthYandex\AuthYandex::getUserData($token);
User Sync
users table:
$user = User::firstOrCreate(
['yandex_id' => $userData['id']],
['email' => $userData['email']]
);
Auth::login($user);
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());
});
Doctrine vs. Eloquent
laravel-doctrine/orm to integrate Doctrine.Schema::table('users', function (Blueprint $table) {
$table->string('yandex_id')->unique()->nullable();
$table->timestamp('yandex_last_login')->nullable();
});
Symfony Console Commands
baks:assets:install won’t work natively. Use:
php artisan vendor:publish --provider="BaksDev\AuthYandex\AuthYandexServiceProvider"
Console namespace.State Parameter Handling
state parameter for CSRF protection. Implement in Laravel:
$state = Str::random(40);
session(['yandex_oauth_state' => $state]);
$authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl(['state' => $state]);
Token Storage
Cache::put('yandex_token_' . $user->id, $token, now()->addHours(1));
Error Handling
try {
$token = \BaksDev\AuthYandex\AuthYandex::getAccessToken($code);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
throw new \App\Exceptions\YandexAuthException($e->getMessage());
}
Asset Paths
asset() helper. Replace with Laravel’s:
// In Blade:
<script src="{{ asset('vendor/baks-dev/auth-yandex/js/yandex-auth.js') }}"></script>
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),
]);
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();
}
}
Additional Scopes Request extra Yandex permissions:
$authUrl = \BaksDev\AuthYandex\AuthYandex::getAuthorizationUrl([
'scope' => ['login:email', 'login:info'],
]);
Post-Auth Actions Trigger actions after Yandex login:
Auth::login($user, function ($user) {
event(new YandexLoginEvent($user));
// Send welcome email, log activity, etc.
});
Multi-Tenant Support Scope Yandex credentials per tenant:
config(['auth-yandex.client_id' => Tenant::current()->yandex_client_id]);
Webhook Integration Listen for Yandex account updates via webhooks:
Route::post('/yandex-webhook', [YandexWebhookController::class, 'handle']);
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.
Lazy-Load User Data Avoid fetching Yandex data on every request:
$user->loadMissing('yandexData');
Batch Token Refresh Refresh
How can I help you explore Laravel packages today?