]> BookStack Code Mirror - bookstack/blobdiff - app/Auth/Access/Mfa/BackupCodeService.php
Guest create page: name field autofocus
[bookstack] / app / Auth / Access / Mfa / BackupCodeService.php
index cc533bd317db8162a3caac7eb51cdefacc7ce723..d58d28ae12f4a115c7cf9d6a5bd92e50dcce66af 100644 (file)
@@ -12,10 +12,51 @@ class BackupCodeService
     public function generateNewSet(): array
     {
         $codes = [];
-        for ($i = 0; $i < 16; $i++) {
+        while (count($codes) < 16) {
             $code = Str::random(5) . '-' . Str::random(5);
-            $codes[] = strtolower($code);
+            if (!in_array($code, $codes)) {
+                $codes[] = strtolower($code);
+            }
         }
+
         return $codes;
     }
-}
\ No newline at end of file
+
+    /**
+     * Check if the given code matches one of the available options.
+     */
+    public function inputCodeExistsInSet(string $code, string $codeSet): bool
+    {
+        $cleanCode = $this->cleanInputCode($code);
+        $codes = json_decode($codeSet);
+
+        return in_array($cleanCode, $codes);
+    }
+
+    /**
+     * Remove the given input code from the given available options.
+     * Will return a JSON string containing the codes.
+     */
+    public function removeInputCodeFromSet(string $code, string $codeSet): string
+    {
+        $cleanCode = $this->cleanInputCode($code);
+        $codes = json_decode($codeSet);
+        $pos = array_search($cleanCode, $codes, true);
+        array_splice($codes, $pos, 1);
+
+        return json_encode($codes);
+    }
+
+    /**
+     * Count the number of codes in the given set.
+     */
+    public function countCodesInSet(string $codeSet): int
+    {
+        return count(json_decode($codeSet));
+    }
+
+    protected function cleanInputCode(string $code): string
+    {
+        return strtolower(str_replace(' ', '-', trim($code)));
+    }
+}