PERF: Avoid loading ActiveRecord objects when checking for second factor.

approved

#1

PERF: Avoid loading ActiveRecord objects when checking for second factor.

  • Eliminate DB query for sites without local logins and sites that has SSO enabled.
diff --git a/app/models/concerns/second_factor_manager.rb b/app/models/concerns/second_factor_manager.rb
index 1761d64..67e160d 100644
--- a/app/models/concerns/second_factor_manager.rb
+++ b/app/models/concerns/second_factor_manager.rb
@@ -34,15 +34,15 @@ module SecondFactorManager
   end
 
   def totp_enabled?
-    !!(self&.user_second_factors&.totp&.enabled?) &&
-      !SiteSetting.enable_sso &&
-      SiteSetting.enable_local_logins
+    !SiteSetting.enable_sso &&
+      SiteSetting.enable_local_logins &&
+      self&.user_second_factors.totps.exists?
   end
 
   def backup_codes_enabled?
-    !!(self&.user_second_factors&.backup_codes&.present?) &&
-      !SiteSetting.enable_sso &&
-      SiteSetting.enable_local_logins
+    !SiteSetting.enable_sso &&
+      SiteSetting.enable_local_logins &&
+      self&.user_second_factors.backup_codes.exists?
   end
 
   def remaining_backup_codes
diff --git a/app/models/user_second_factor.rb b/app/models/user_second_factor.rb
index dc7f169..6c39e8c 100644
--- a/app/models/user_second_factor.rb
+++ b/app/models/user_second_factor.rb
@@ -5,6 +5,10 @@ class UserSecondFactor < ActiveRecord::Base
     where(method: UserSecondFactor.methods[:backup_codes], enabled: true)
   end
 
+  scope :totps, -> do
+    where(method: UserSecondFactor.methods[:totp], enabled: true)
+  end
+
   def self.methods
     @methods ||= Enum.new(
       totp: 1,

GitHub sha: 6327f36b


Approved #2