init
This commit is contained in:
34
app/Http/Controllers/Api/ContactEnquiryController.php
Normal file
34
app/Http/Controllers/Api/ContactEnquiryController.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Enums\ResponseStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ContactEnquiryRequest;
|
||||
use App\Models\ApiRequest;
|
||||
use App\Models\Website;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ContactEnquiryController extends Controller
|
||||
{
|
||||
public function __invoke(ContactEnquiryRequest $request): JsonResponse
|
||||
{
|
||||
$website = $request->user();
|
||||
$registrationNumber = strtoupper(str_replace(' ', '', $request->validated('registration_number')));
|
||||
|
||||
ApiRequest::create([
|
||||
'website_id' => $website->id,
|
||||
'registration_number' => $registrationNumber,
|
||||
'ip_address' => $request->ip(),
|
||||
'contact_data' => $request->validated('contact_data'),
|
||||
'response_status' => ResponseStatus::ContactSubmitted,
|
||||
'metadata' => [
|
||||
'user_agent' => $request->userAgent(),
|
||||
'referer' => $request->header('referer'),
|
||||
],
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
}
|
||||
}
|
||||
195
app/Http/Controllers/Api/VehicleEnquiryController.php
Normal file
195
app/Http/Controllers/Api/VehicleEnquiryController.php
Normal file
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Enums\ResponseStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\VehicleEnquiryRequest;
|
||||
use App\Models\ApiRequest;
|
||||
use App\Models\VehicleDataSource;
|
||||
use App\Models\VehicleRecord;
|
||||
use App\Models\Website;
|
||||
use App\Services\DvlaService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class VehicleEnquiryController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DvlaService $dvlaService
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(VehicleEnquiryRequest $request): JsonResponse
|
||||
{
|
||||
$startTime = microtime(true);
|
||||
$website = $request->user();
|
||||
$registrationNumber = strtoupper(str_replace(' ', '', $request->validated('registration_number')));
|
||||
$contactData = $request->validated('contact_data');
|
||||
|
||||
$vehicleRecord = VehicleRecord::where('registration_number', $registrationNumber)->first();
|
||||
|
||||
if ($vehicleRecord) {
|
||||
$this->logRequest(
|
||||
$website,
|
||||
$registrationNumber,
|
||||
$request->ip(),
|
||||
$contactData,
|
||||
ResponseStatus::CacheHit,
|
||||
$this->buildMetadata($request, $startTime)
|
||||
);
|
||||
$this->incrementCacheHitRateLimit($request);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $this->filterByTier($vehicleRecord->data, $website),
|
||||
]);
|
||||
}
|
||||
|
||||
if (!$this->checkExternalApiRateLimit($website)) {
|
||||
return response()->json([
|
||||
'message' => 'External API rate limit exceeded',
|
||||
'limit' => $website->external_api_rate_limit,
|
||||
'reset_at' => now()->addHour()->startOfHour()->timestamp,
|
||||
], 429);
|
||||
}
|
||||
|
||||
try {
|
||||
$dvlaData = $this->dvlaService->getVehicleDetails($registrationNumber);
|
||||
|
||||
if (!$dvlaData) {
|
||||
$this->logRequest(
|
||||
$website,
|
||||
$registrationNumber,
|
||||
$request->ip(),
|
||||
$contactData,
|
||||
ResponseStatus::NotFound,
|
||||
$this->buildMetadata($request, $startTime)
|
||||
);
|
||||
$this->incrementExternalApiRateLimit($website);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Vehicle not found',
|
||||
], 404);
|
||||
}
|
||||
|
||||
$vehicleRecord = DB::transaction(function () use ($registrationNumber, $dvlaData) {
|
||||
$vehicle = VehicleRecord::create([
|
||||
'registration_number' => $registrationNumber,
|
||||
'data' => $dvlaData,
|
||||
]);
|
||||
|
||||
VehicleDataSource::create([
|
||||
'vehicle_record_id' => $vehicle->id,
|
||||
'source_name' => 'dvla',
|
||||
'source_url' => DvlaService::class.'::API_URL',
|
||||
'last_fetched_at' => now(),
|
||||
'cache_expires_at' => now()->addMonths(6),
|
||||
]);
|
||||
|
||||
return $vehicle;
|
||||
});
|
||||
|
||||
$this->logRequest(
|
||||
$website,
|
||||
$registrationNumber,
|
||||
$request->ip(),
|
||||
$contactData,
|
||||
ResponseStatus::ApiFetched,
|
||||
$this->buildMetadata($request, $startTime)
|
||||
);
|
||||
$this->incrementExternalApiRateLimit($website);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $this->filterByTier($vehicleRecord->data, $website),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
$this->logRequest(
|
||||
$website,
|
||||
$registrationNumber,
|
||||
$request->ip(),
|
||||
$contactData,
|
||||
ResponseStatus::Error,
|
||||
$this->buildMetadata($request, $startTime, $e->getMessage())
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Failed to fetch vehicle details',
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function logRequest(Website $website, string $registrationNumber, string $ipAddress, ?array $contactData, ResponseStatus $status, array $metadata = []): void
|
||||
{
|
||||
ApiRequest::create([
|
||||
'website_id' => $website->id,
|
||||
'registration_number' => $registrationNumber,
|
||||
'ip_address' => $ipAddress,
|
||||
'contact_data' => $contactData,
|
||||
'response_status' => $status,
|
||||
'metadata' => $metadata,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function buildMetadata($request, float $startTime, ?string $errorMessage = null): array
|
||||
{
|
||||
$responseTime = round((microtime(true) - $startTime) * 1000, 2);
|
||||
|
||||
$metadata = [
|
||||
'user_agent' => $request->userAgent(),
|
||||
'response_time_ms' => $responseTime,
|
||||
'referer' => $request->header('referer'),
|
||||
'accept' => $request->header('accept'),
|
||||
];
|
||||
|
||||
if ($errorMessage) {
|
||||
$metadata['error_message'] = $errorMessage;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
private function incrementCacheHitRateLimit($request): void
|
||||
{
|
||||
$cacheKey = $request->attributes->get('rate_limit_key');
|
||||
|
||||
if ($cacheKey) {
|
||||
$value = Cache::increment($cacheKey);
|
||||
Cache::put($cacheKey, $value, 3600);
|
||||
}
|
||||
}
|
||||
|
||||
private function checkExternalApiRateLimit(Website $website): bool
|
||||
{
|
||||
if (app()->environment('local') || $website->bypass_rate_limit) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$hour = now()->format('Y-m-d-H');
|
||||
$cacheKey = "rate_limit:website:{$website->id}:external_api:{$hour}";
|
||||
$attempts = Cache::get($cacheKey, 0);
|
||||
|
||||
return $attempts < $website->external_api_rate_limit;
|
||||
}
|
||||
|
||||
private function incrementExternalApiRateLimit(Website $website): void
|
||||
{
|
||||
if (app()->environment('local') || $website->bypass_rate_limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
$hour = now()->format('Y-m-d-H');
|
||||
$cacheKey = "rate_limit:website:{$website->id}:external_api:{$hour}";
|
||||
|
||||
$value = Cache::increment($cacheKey);
|
||||
Cache::put($cacheKey, $value, 3600);
|
||||
}
|
||||
|
||||
private function filterByTier(mixed $data, Website $website): array
|
||||
{
|
||||
return $website->tier->filterFields((array) $data);
|
||||
}
|
||||
}
|
||||
8
app/Http/Controllers/Controller.php
Normal file
8
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
69
app/Http/Middleware/RateLimitApiRequests.php
Normal file
69
app/Http/Middleware/RateLimitApiRequests.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\Website;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RateLimitApiRequests
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$website = $request->user();
|
||||
|
||||
if (!$website instanceof Website) {
|
||||
return response()->json(['message' => 'Unauthorized'], 401);
|
||||
}
|
||||
|
||||
if (!$website->is_active) {
|
||||
return response()->json(['message' => 'Account inactive'], 403);
|
||||
}
|
||||
|
||||
if (app()->environment('local') || $website->bypass_rate_limit) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (!$this->originMatchesDomain($request, $website)) {
|
||||
return response()->json(['message' => 'Forbidden'], 403);
|
||||
}
|
||||
|
||||
$hour = now()->format('Y-m-d-H');
|
||||
$cacheKey = "rate_limit:website:{$website->id}:cache_hits:{$hour}";
|
||||
$attempts = Cache::get($cacheKey, 0);
|
||||
|
||||
if ($attempts >= $website->cache_hit_rate_limit) {
|
||||
return response()->json([
|
||||
'message' => 'Rate limit exceeded',
|
||||
'limit' => $website->cache_hit_rate_limit,
|
||||
'reset_at' => now()->addHour()->startOfHour()->timestamp,
|
||||
], 429);
|
||||
}
|
||||
|
||||
$request->attributes->set('rate_limit_key', $cacheKey);
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
|
||||
$response->headers->set('X-RateLimit-Limit', $website->cache_hit_rate_limit);
|
||||
$response->headers->set('X-RateLimit-Remaining', max(0, $website->cache_hit_rate_limit - $attempts - 1));
|
||||
$response->headers->set('X-RateLimit-Reset', now()->addHour()->startOfHour()->timestamp);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function originMatchesDomain(Request $request, Website $website): bool
|
||||
{
|
||||
$origin = $request->header('Origin') ?? $request->header('Referer');
|
||||
|
||||
if (!$origin) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$host = parse_url($origin, PHP_URL_HOST);
|
||||
|
||||
return $host === $website->domain;
|
||||
}
|
||||
}
|
||||
40
app/Http/Requests/ContactEnquiryRequest.php
Normal file
40
app/Http/Requests/ContactEnquiryRequest.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ContactEnquiryRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'registration_number' => ['required', 'string', 'max:8', 'regex:/^(?=.*\d)[A-Za-z0-9 ]+$/'],
|
||||
'contact_data' => ['required', 'array'],
|
||||
'contact_data.name' => ['nullable', 'string', 'max:255'],
|
||||
'contact_data.email' => ['required_without:contact_data.phone', 'nullable', 'email', 'max:255'],
|
||||
'contact_data.phone' => ['required_without:contact_data.email', 'nullable', 'string', 'max:50'],
|
||||
'contact_data.address' => ['nullable', 'string', 'max:500'],
|
||||
'contact_data.message' => ['nullable', 'string', 'max:2000'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'registration_number.required' => 'Vehicle registration number is required',
|
||||
'registration_number.max' => 'Vehicle registration number must not exceed 8 characters',
|
||||
'registration_number.regex' => 'Invalid registration number format',
|
||||
'contact_data.required' => 'Contact data is required',
|
||||
'contact_data.array' => 'Contact data must be a valid object',
|
||||
'contact_data.email.required_without' => 'Please provide at least an email address or phone number',
|
||||
'contact_data.email.email' => 'Please provide a valid email address',
|
||||
'contact_data.phone.required_without' => 'Please provide at least a phone number or email address',
|
||||
];
|
||||
}
|
||||
}
|
||||
36
app/Http/Requests/VehicleEnquiryRequest.php
Normal file
36
app/Http/Requests/VehicleEnquiryRequest.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class VehicleEnquiryRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'registration_number' => ['required', 'string', 'max:8', 'regex:/^(?=.*\d)[A-Za-z0-9 ]+$/'],
|
||||
'contact_data' => ['nullable', 'array'],
|
||||
'contact_data.name' => ['nullable', 'string', 'max:255'],
|
||||
'contact_data.email' => ['nullable', 'email', 'max:255'],
|
||||
'contact_data.phone' => ['nullable', 'string', 'max:50'],
|
||||
'contact_data.address' => ['nullable', 'string', 'max:500'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'registration_number.required' => 'Vehicle registration number is required',
|
||||
'registration_number.max' => 'Vehicle registration number must not exceed 8 characters',
|
||||
'registration_number.regex' => 'Invalid registration number format',
|
||||
'contact_data.array' => 'Contact data must be a valid object',
|
||||
'contact_data.email.email' => 'Please provide a valid email address',
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user