<?php
 namespace App\Http\Requests\Store; use App\Models\ClientAuthorization; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class SwitchAccountRequest extends FormRequest { public function authorize(): bool { if (! Auth::guard('client')->check()) { return false; } $authenticatedClient = Auth::guard('client')->user(); $targetClientId = $this->input('client_id'); if ($targetClientId == $authenticatedClient->id) { return true; } return ClientAuthorization::where('owner_client_id', $targetClientId) ->where('authorized_client_id', $authenticatedClient->id) ->where('status', 'active') ->whereNull('revoked_at') ->exists(); } public function rules(): array { return [ 'client_id' => [ 'required', 'integer', 'exists:clients,id', function ($attribute, $value, $fail) { $authenticatedClient = Auth::guard('client')->user(); $switchKey = 'client_switch_count:' . $authenticatedClient->id; $switchCount = (int) \Cache::get($switchKey, 0); if ($switchCount >= 20) { $fail('Too many account switches in the past hour. Please wait.'); return; } $currentIp = $this->ip(); $loginIp = session('login_ip', $currentIp); if ($currentIp !== $loginIp) { $fail('IP address mismatch detected.'); return; } $currentUA = $this->userAgent(); $loginUA = session('login_user_agent', $currentUA); if ($currentUA !== $loginUA) { $fail('Session fingerprint mismatch.'); return; } }, ], ]; } public function messages(): array { return [ 'client_id.required' => 'Client ID is required.', 'client_id.integer' => 'Invalid client ID format.', 'client_id.exists' => 'Client account not found.', ]; } protected function failedAuthorization() { \Log::warning('Unauthorized account switch attempt', [ 'authenticated_user' => Auth::guard('client')->id(), 'target_client' => $this->input('client_id'), 'ip' => $this->ip(), 'user_agent' => $this->userAgent(), ]); } } 