diff --git a/app/libs/limit_forbid_control/base.rb b/app/libs/limit_forbid_control/base.rb new file mode 100644 index 0000000..6f11ae5 --- /dev/null +++ b/app/libs/limit_forbid_control/base.rb @@ -0,0 +1,66 @@ +class LimitForbidControl::Base + def initialize + end + + def cache_key + raise 'Please overwrite method :cache_Key' + end + + def forbid_cache_key + "#{cache_key}:forbid" + end + + def allow_times + 5 + end + + def cumulative_expires + 1.days + end + + def forbid_expires + 1.hours + end + + def forbid? + Rails.cache.read(forbid_cache_key) + end + + def increment! + value = Rails.cache.read(cache_key) + value = value.to_i + 1 + + # 锁定 + if value >= allow_times.to_i + Rails.logger.info("[LimitForbidControl] Lock #{cache_key}") + Rails.cache.write(forbid_cache_key, true, expires_in: forbid_expires) + Rails.cache.delete(cache_key) + else + Rails.cache.write(cache_key, value, expires_in: cumulative_expires) + end + end + + def error_times + Rails.cache.read(cache_key).to_i + end + + def remain_times + allow_times.to_i - error_times + end + + def clear + Rails.logger.info("[LimitForbidControl] Clear #{cache_key}") + Rails.cache.delete(forbid_cache_key) + Rails.cache.delete(cache_key) + end + + private + + def redis_cache? + Rails.cache.is_a?(ActiveSupport::Cache::RedisStore) + end + + def day + Time.current.strftime('%Y%m%d') + end +end \ No newline at end of file diff --git a/app/libs/limit_forbid_control/send_email_code.rb b/app/libs/limit_forbid_control/send_email_code.rb new file mode 100644 index 0000000..729446e --- /dev/null +++ b/app/libs/limit_forbid_control/send_email_code.rb @@ -0,0 +1,25 @@ +class LimitForbidControl::SendEmailCode < LimitForbidControl::Base + attr_reader :email + + def initialize(email) + super() + @email = email + end + + def allow_times + EduSetting.get('daily_send_email_code_times').presence || 5 + end + + def forbid_expires + num = EduSetting.get('daily_send_email_code_forbid_time').presence.to_i + num.zero? ? 10.minutes : num.to_i.hours + end + + def cumulative_expires + 1.hours + end + + def cache_key + @_cache_key ||= "limit_forbid_control:#{day}:send_email_code:#{email}" + end +end \ No newline at end of file diff --git a/app/libs/limit_forbid_control/user_login.rb b/app/libs/limit_forbid_control/user_login.rb new file mode 100644 index 0000000..5588e94 --- /dev/null +++ b/app/libs/limit_forbid_control/user_login.rb @@ -0,0 +1,25 @@ +class LimitForbidControl::UserLogin < LimitForbidControl::Base + attr_reader :user + + def initialize(user) + super() + @user = user + end + + def allow_times + EduSetting.get('daily_error_password_times').presence || 5 + end + + def forbid_expires + num = EduSetting.get('daily_error_password_forbid_time').presence.to_i + num.zero? ? 1.hours : num.to_i.minutes + end + + def cumulative_expires + 1.days + end + + def cache_key + @_cache_key ||= "limit_forbid_control:#{day}:user_login:#{user.id}" + end +end \ No newline at end of file