php-commerce/Middleware/CommerceApiAuth.php
Snider a774f4e285 refactor: migrate namespace from Core\Commerce to Core\Mod\Commerce
Align commerce module with the monorepo module structure by updating
all namespaces to use the Core\Mod\Commerce convention. This change
supports the recent monorepo separation and ensures consistency with
other modules.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 16:23:12 +00:00

55 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Core\Mod\Commerce\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Authenticate Commerce Provisioning API requests using Bearer token.
*
* The token is compared against the configured Commerce API secret.
* Used for internal service provisioning and entitlement management endpoints.
*/
class CommerceApiAuth
{
public function handle(Request $request, Closure $next): Response
{
$token = $request->bearerToken();
if (! $token) {
return $this->unauthorized('API token required. Use Authorization: Bearer <token>');
}
$expectedToken = config('services.commerce.api_secret');
if (! $expectedToken) {
return response()->json([
'error' => 'configuration_error',
'message' => 'Commerce API not configured',
], 500);
}
if (! hash_equals($expectedToken, $token)) {
return $this->unauthorized('Invalid API token');
}
$request->attributes->set('auth_type', 'commerce_api');
return $next($request);
}
/**
* Return 401 Unauthorized response.
*/
protected function unauthorized(string $message): Response
{
return response()->json([
'error' => 'unauthorized',
'message' => $message,
], 401);
}
}