]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Mfa/MfaValue.php
8f07c6657433d9543ea83e42e4228b759bcead2d
[bookstack] / app / Auth / Access / Mfa / MfaValue.php
1 <?php
2
3 namespace BookStack\Auth\Access\Mfa;
4
5 use BookStack\Auth\User;
6 use Carbon\Carbon;
7 use Illuminate\Database\Eloquent\Model;
8
9 /**
10  * @property int    $id
11  * @property int    $user_id
12  * @property string $method
13  * @property string $value
14  * @property Carbon $created_at
15  * @property Carbon $updated_at
16  */
17 class MfaValue extends Model
18 {
19     protected static $unguarded = true;
20
21     const METHOD_TOTP = 'totp';
22     const METHOD_BACKUP_CODES = 'backup_codes';
23
24     /**
25      * Get all the MFA methods available.
26      */
27     public static function allMethods(): array
28     {
29         return [self::METHOD_TOTP, self::METHOD_BACKUP_CODES];
30     }
31
32     /**
33      * Upsert a new MFA value for the given user and method
34      * using the provided value.
35      */
36     public static function upsertWithValue(User $user, string $method, string $value): void
37     {
38         /** @var MfaValue $mfaVal */
39         $mfaVal = static::query()->firstOrNew([
40             'user_id' => $user->id,
41             'method'  => $method,
42         ]);
43         $mfaVal->setValue($value);
44         $mfaVal->save();
45     }
46
47     /**
48      * Easily get the decrypted MFA value for the given user and method.
49      */
50     public static function getValueForUser(User $user, string $method): ?string
51     {
52         /** @var MfaValue $mfaVal */
53         $mfaVal = static::query()
54             ->where('user_id', '=', $user->id)
55             ->where('method', '=', $method)
56             ->first();
57
58         return $mfaVal ? $mfaVal->getValue() : null;
59     }
60
61     /**
62      * Decrypt the value attribute upon access.
63      */
64     protected function getValue(): string
65     {
66         return decrypt($this->value);
67     }
68
69     /**
70      * Encrypt the value attribute upon access.
71      */
72     protected function setValue($value): void
73     {
74         $this->value = encrypt($value);
75     }
76 }