debian-mirror-gitlab/lib/gitlab/auth/unique_ips_limiter.rb

46 lines
1.2 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
module Gitlab
module Auth
class UniqueIpsLimiter
2019-12-04 20:38:33 +05:30
USER_UNIQUE_IPS_PREFIX = 'user_unique_ips'
2017-08-17 22:00:37 +05:30
class << self
def limit_user_id!(user_id)
if config.unique_ips_limit_enabled
ip = RequestContext.client_ip
unique_ips = update_and_return_ips_count(user_id, ip)
raise TooManyIps.new(user_id, ip, unique_ips) if unique_ips > config.unique_ips_limit_per_user
end
end
def limit_user!(user = nil)
user ||= yield if block_given?
limit_user_id!(user.id) unless user.nil?
user
end
def config
Gitlab::CurrentSettings.current_application_settings
end
def update_and_return_ips_count(user_id, ip)
time = Time.now.utc.to_i
key = "#{USER_UNIQUE_IPS_PREFIX}:#{user_id}"
2017-09-10 17:25:29 +05:30
Gitlab::Redis::SharedState.with do |redis|
2017-08-17 22:00:37 +05:30
unique_ips_count = nil
redis.multi do |r|
r.zadd(key, time, ip)
r.zremrangebyscore(key, 0, time - config.unique_ips_limit_time_window)
unique_ips_count = r.zcard(key)
end
unique_ips_count.value
end
end
end
end
end
end