Browse Source

add captcha verification to captcha processor

olinox14 1 year ago
parent
commit
755783e57e
2 changed files with 27 additions and 3 deletions
  1. 15 3
      src/ApiResource/ContactRequest.php
  2. 12 0
      src/State/Processor/ContactRequestProcessor.php

+ 15 - 3
src/ApiResource/ContactRequest.php

@@ -23,7 +23,7 @@ class ContactRequest
     )]
     protected string $email;
 
-    protected string|null $name = null;
+    protected ?string $name = null;
 
     #[Assert\Length(
         min: 10,
@@ -31,6 +31,8 @@ class ContactRequest
     )]
     protected string $message;
 
+    protected string $altchaPayload;
+
     public function getEmail(): string
     {
         return $this->email;
@@ -41,12 +43,12 @@ class ContactRequest
         $this->email = $email;
     }
 
-    public function getName(): string
+    public function getName(): ?string
     {
         return $this->name;
     }
 
-    public function setName(string $name): void
+    public function setName(?string $name): void
     {
         $this->name = $name;
     }
@@ -60,4 +62,14 @@ class ContactRequest
     {
         $this->message = $message;
     }
+
+    public function getAltchaPayload(): string
+    {
+        return $this->altchaPayload;
+    }
+
+    public function setAltchaPayload(string $altchaPayload): void
+    {
+        $this->altchaPayload = $altchaPayload;
+    }
 }

+ 12 - 0
src/State/Processor/ContactRequestProcessor.php

@@ -3,6 +3,7 @@ declare(strict_types=1);
 
 namespace App\State\Processor;
 
+use AltchaOrg\Altcha\Altcha;
 use ApiPlatform\Metadata\Operation;
 use ApiPlatform\Metadata\Post;
 use ApiPlatform\State\ProcessorInterface;
@@ -18,6 +19,7 @@ class ContactRequestProcessor implements ProcessorInterface
         private readonly MailerInterface $symfonyMailer,
         private readonly string $fromEmail,
         private readonly string $contactEmail,
+        private readonly string $hmacKey
     )
     {}
 
@@ -33,6 +35,16 @@ class ContactRequestProcessor implements ProcessorInterface
         /** @var ContactRequest $contactRequest */
         $contactRequest = $data;
 
+        $valid = Altcha::verifySolution(
+            $contactRequest->getAltchaPayload(),
+            $this->hmacKey,
+            true
+        );
+
+        if (!$valid) {
+            throw new \RuntimeException('Invalid payload');
+        }
+
         $symfonyMail = (new Email())
             ->to($this->contactEmail)
             ->from($this->fromEmail)