70 lines
2.4 KiB
PHP
70 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Auth;
|
|
|
|
use App\Http\Controllers\Concerns\ProxiesBackend;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Services\BackendHttpClient;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
class AvailabilityController extends Controller
|
|
{
|
|
use ProxiesBackend;
|
|
|
|
public function __construct(private readonly BackendHttpClient $client)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* Check availability for username or email during registration via upstream API.
|
|
*/
|
|
public function __invoke(Request $request): JsonResponse
|
|
{
|
|
$field = $request->query('field');
|
|
$value = (string) $request->query('value', '');
|
|
|
|
if (!in_array($field, ['username', 'email'], true)) {
|
|
return response()->json([
|
|
'ok' => false,
|
|
'error' => 'Unsupported field',
|
|
], 422);
|
|
}
|
|
|
|
// Basic format checks to reduce unnecessary upstream calls
|
|
if ($field === 'username' && mb_strlen($value) < 3) {
|
|
return response()->json(['ok' => true, 'available' => false, 'reason' => 'too_short']);
|
|
}
|
|
if ($field === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
|
return response()->json(['ok' => true, 'available' => false, 'reason' => 'invalid_format']);
|
|
}
|
|
|
|
try {
|
|
$res = $this->client->get($request, '/api/auth/availability', [
|
|
'field' => $field,
|
|
'value' => $value,
|
|
], retry: true);
|
|
|
|
if ($res->successful()) {
|
|
$j = $res->json() ?: [];
|
|
// Normalize to { ok: true, available: bool, reason? }
|
|
$available = $j['available'] ?? $j['is_available'] ?? null;
|
|
if ($available !== null) {
|
|
$out = ['ok' => true, 'available' => (bool) $available];
|
|
if (isset($j['reason'])) {
|
|
$out['reason'] = $j['reason'];
|
|
}
|
|
return response()->json($out, 200);
|
|
}
|
|
// Fallback: pass-through
|
|
return response()->json($j, 200);
|
|
}
|
|
if ($res->clientError()) return $this->mapClientError($res);
|
|
if ($res->serverError()) return $this->mapServiceUnavailable($res);
|
|
return $this->mapBadGateway();
|
|
} catch (\Throwable $e) {
|
|
return $this->mapBadGateway('API server not reachable');
|
|
}
|
|
}
|
|
}
|