fipamo/app/Http/Middleware/ValidateAPIKey.php
ro 4337a20fb8
API Improvements #116
API Security has been reworked to check if request is secure, verifies
the API token created on site setup given to every member, and then
confirms the system is accepting API requests by way of the API enabled
toggle in settings

API usage is now only meant for backend use, so this needs to be noted
in the docs
2024-07-17 16:41:11 -06:00

67 lines
2.2 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Interfaces\MemberRepositoryInterface;
use App\Services\Data\SettingsService;
use function _\find;
class ValidateAPIKey
{
protected $member;
protected $settings;
public function __construct(
MemberRepositoryInterface $memberRepo,
SettingsService $settingsService,
) {
$this->member = $memberRepo;
$this->settings = $settingsService;
}
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$response = [];
//checks to see if request is secure
if (isHttps()) {
$key = $request->header('fipamo-api-key');
$folks = $this->member->getAll();
//looks to see if API key exists
if (find($folks, ['key' => $key])) {
//final check to see if API requests are being accepted
$global = $this->settings->getGlobal();
if (isset($global['externalAPI']) && $global['externalAPI'] == "true") {
return $next($request);
} else {
$response = [
'message' => "API Auth Fail: Not Accepting Requests",
'type' => 'postError',
];
return response()->json($response)->header('Content-Type', 'application/json');
}
} else {
$response = [
'message' => "API Auth Fail: API Key Invalid",
'type' => 'postError',
];
return response()->json($response)->header('Content-Type', 'application/json');
}
} else {
$response = [
'message' => "API Auth Fail: Request must be secure (HTTPS)",
'type' => 'postError',
];
return response()->json($response)->header('Content-Type', 'application/json');
}
}
}