]> BookStack Code Mirror - bookstack/blobdiff - app/Auth/Access/Mfa/MfaValue.php
Skip intermediate login page with single provider
[bookstack] / app / Auth / Access / Mfa / MfaValue.php
index cba90dcac2b14dcab9769bfbdbbfbd5077f129eb..8f07c6657433d9543ea83e42e4228b759bcead2d 100644 (file)
@@ -7,8 +7,8 @@ use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Model;
 
 /**
- * @property int $id
- * @property int $user_id
+ * @property int    $id
+ * @property int    $user_id
  * @property string $method
  * @property string $value
  * @property Carbon $created_at
@@ -21,6 +21,14 @@ class MfaValue extends Model
     const METHOD_TOTP = 'totp';
     const METHOD_BACKUP_CODES = 'backup_codes';
 
+    /**
+     * Get all the MFA methods available.
+     */
+    public static function allMethods(): array
+    {
+        return [self::METHOD_TOTP, self::METHOD_BACKUP_CODES];
+    }
+
     /**
      * Upsert a new MFA value for the given user and method
      * using the provided value.
@@ -30,16 +38,30 @@ class MfaValue extends Model
         /** @var MfaValue $mfaVal */
         $mfaVal = static::query()->firstOrNew([
             'user_id' => $user->id,
-            'method' => $method
+            'method'  => $method,
         ]);
         $mfaVal->setValue($value);
         $mfaVal->save();
     }
 
+    /**
+     * Easily get the decrypted MFA value for the given user and method.
+     */
+    public static function getValueForUser(User $user, string $method): ?string
+    {
+        /** @var MfaValue $mfaVal */
+        $mfaVal = static::query()
+            ->where('user_id', '=', $user->id)
+            ->where('method', '=', $method)
+            ->first();
+
+        return $mfaVal ? $mfaVal->getValue() : null;
+    }
+
     /**
      * Decrypt the value attribute upon access.
      */
-    public function getValue(): string
+    protected function getValue(): string
     {
         return decrypt($this->value);
     }
@@ -47,7 +69,7 @@ class MfaValue extends Model
     /**
      * Encrypt the value attribute upon access.
      */
-    public function setValue($value): void
+    protected function setValue($value): void
     {
         $this->value = encrypt($value);
     }