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);
32 return in_array($cleanCode, $codes);
36 * Remove the given input code from the given available options.
37 * Will return a JSON string containing the codes.
39 public function removeInputCodeFromSet(string $code, string $codeSet): string
41 $cleanCode = $this->cleanInputCode($code);
42 $codes = json_decode($codeSet);
43 $pos = array_search($cleanCode, $codes, true);
44 array_splice($codes, $pos, 1);
45 return json_encode($codes);
49 * Count the number of codes in the given set.
51 public function countCodesInSet(string $codeSet): int
53 return count(json_decode($codeSet));
56 protected function cleanInputCode(string $code): string
58 return strtolower(str_replace(' ', '-', trim($code)));