Browse Source

add captcha challenge verification route

olinox14 1 year ago
parent
commit
495890ba40

+ 32 - 2
src/ApiResource/Challenge.php

@@ -5,17 +5,47 @@ namespace App\ApiResource;
 
 use ApiPlatform\Metadata\ApiResource;
 use ApiPlatform\Metadata\Get;
-use App\State\Provider\ChallengeRequestProvider;
+use ApiPlatform\Metadata\Post;
+use App\State\Processor\ChallengeProcessor;
+use App\State\Provider\ChallengeProvider;
 
 #[ApiResource(
     operations: [
         new Get(
             uriTemplate: '/challenge',
-            provider: ChallengeRequestProvider::class
+            provider: ChallengeProvider::class
+        ),
+        new Post(
+            uriTemplate: '/challenge',
+            processor: ChallengeProcessor::class
         ),
     ],
 
 )]
 class Challenge
 {
+    private string | null $payload = null;
+    private ?bool $verified = null;
+
+    public function getPayload(): ?string
+    {
+        return $this->payload;
+    }
+
+    public function setPayload(?string $payload): self
+    {
+        $this->payload = $payload;
+        return $this;
+    }
+
+    public function isVerified(): bool
+    {
+        return $this->verified;
+    }
+
+    public function setVerified(bool $verified): self
+    {
+        $this->verified = $verified;
+        return $this;
+    }
 }

+ 38 - 0
src/State/Processor/ChallengeProcessor.php

@@ -0,0 +1,38 @@
+<?php
+declare(strict_types=1);
+
+namespace App\State\Processor;
+
+use AltchaOrg\Altcha\Altcha;
+use ApiPlatform\Metadata\Operation;
+use ApiPlatform\Metadata\Post;
+use ApiPlatform\State\ProcessorInterface;
+use App\ApiResource\Challenge;
+use Symfony\Component\HttpFoundation\Response;
+
+class ChallengeProcessor implements ProcessorInterface
+{
+    public function __construct(
+        private readonly string $hmacKey
+    ) {}
+
+    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): Challenge
+    {
+        if (!$operation instanceof Post) {
+            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
+        }
+
+        /** @var Challenge $challenge */
+        $challenge = $data;
+
+        $valid = Altcha::verifySolution(
+            $challenge->getPayload(),
+            $this->hmacKey,
+            true
+        );
+
+        $challenge->setVerified($valid);
+
+        return $challenge;
+    }
+}

+ 2 - 1
src/State/Provider/ChallengeRequestProvider.php → src/State/Provider/ChallengeProvider.php

@@ -11,11 +11,12 @@ use ApiPlatform\State\ProviderInterface;
 use ApiPlatform\Metadata\Operation;
 use Symfony\Component\HttpFoundation\Response;
 
-class ChallengeRequestProvider implements ProviderInterface
+class ChallengeProvider implements ProviderInterface
 {
     public function __construct(
         private readonly string $hmacKey
     ) {}
+
     /**
      * @param mixed[] $uriVariables
      * @param mixed[] $context