3 namespace BookStack\Auth\Access\Mfa;
5 use Illuminate\Support\Str;
7 class BackupCodeService
10 * Generate a new set of 16 backup codes.
12 public function generateNewSet(): array
15 while (count($codes) < 16) {
16 $code = Str::random(5) . '-' . Str::random(5);
17 if (!in_array($code, $codes)) {
18 $codes[] = strtolower($code);
26 * Check if the given code matches one of the available options.
28 public function inputCodeExistsInSet(string $code, string $codeSet): bool
30 $cleanCode = $this->cleanInputCode($code);
31 $codes = json_decode($codeSet);
33 return in_array($cleanCode, $codes);
37 * Remove the given input code from the given available options.
38 * Will return a JSON string containing the codes.
40 public function removeInputCodeFromSet(string $code, string $codeSet): string
42 $cleanCode = $this->cleanInputCode($code);
43 $codes = json_decode($codeSet);
44 $pos = array_search($cleanCode, $codes, true);
45 array_splice($codes, $pos, 1);
47 return json_encode($codes);
51 * Count the number of codes in the given set.
53 public function countCodesInSet(string $codeSet): int
55 return count(json_decode($codeSet));
58 protected function cleanInputCode(string $code): string
60 return strtolower(str_replace(' ', '-', trim($code)));