Implement ALTCHA captcha service with challenge generation and solution verification
- Added AltchaService class for managing ALTCHA captcha challenges and solutions. - Created CaptchaController to handle API requests for generating challenges. - Introduced CaptchaGuard for validating captcha solutions on public endpoints. - Developed unit tests for AltchaService to ensure challenge creation and solution verification functionality. - Implemented integration tests for the Captcha API endpoint and captcha bypass behavior when disabled. - Added documentation for the Captcha API in the corresponding markdown file.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Captcha;
|
||||
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
* Drop-in captcha check for public endpoints.
|
||||
*
|
||||
* Call `assertValid($request)` at the top of any unauthenticated POST handler.
|
||||
* No-op when ALTCHA is disabled (dev/test), so protected handlers stay testable
|
||||
* without solving a proof-of-work.
|
||||
*/
|
||||
class CaptchaGuard
|
||||
{
|
||||
public function __construct(private readonly AltchaService $altcha) {}
|
||||
|
||||
public function assertValid(Request $request): void
|
||||
{
|
||||
if (!$this->altcha->enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true);
|
||||
$payload = is_array($data) ? (string) ($data['altcha'] ?? '') : '';
|
||||
|
||||
if (!$this->altcha->verifySolution($payload)) {
|
||||
throw new AppException(ErrorCodes::ERR_CAPTCHA_001, null, 422, 'altcha');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user