Files
fotospiel-app/app/Http/Middleware/ApiTokenAuth.php
Codex Agent 79b209de9a Limit-Status im Upload-Flow anzeigen (Warnbanner + Sperrzustände).
Upload-Fehlercodes auswerten und freundliche Dialoge zeigen.
2025-11-01 19:50:17 +01:00

47 lines
1.3 KiB
PHP

<?php
namespace App\Http\Middleware;
use App\Models\User;
use App\Support\ApiError;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
class ApiTokenAuth
{
public function handle(Request $request, Closure $next)
{
$header = $request->header('Authorization', '');
if (! str_starts_with($header, 'Bearer ')) {
return $this->unauthorizedResponse('missing_bearer');
}
$token = substr($header, 7);
$userId = Cache::get('api_token:'.$token);
if (! $userId) {
return $this->unauthorizedResponse('token_unknown');
}
$user = User::find($userId);
if (! $user) {
return $this->unauthorizedResponse('user_missing');
}
Auth::login($user); // for policies if needed
return $next($request);
}
private function unauthorizedResponse(string $reason): JsonResponse
{
return ApiError::response(
'unauthorized',
'Unauthorized',
'Authentication is required to access this resource.',
Response::HTTP_UNAUTHORIZED,
['reason' => $reason]
);
}
}