2018-10-11 16:12:21 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-02-06 07:48:46 -05:00
|
|
|
module Gitlab
|
|
|
|
module Auth
|
|
|
|
class UniqueIpsLimiter
|
2019-08-31 15:25:25 -04:00
|
|
|
USER_UNIQUE_IPS_PREFIX = 'user_unique_ips'
|
2017-02-06 07:48:46 -05:00
|
|
|
|
|
|
|
class << self
|
|
|
|
def limit_user_id!(user_id)
|
|
|
|
if config.unique_ips_limit_enabled
|
2020-01-13 10:07:53 -05:00
|
|
|
ip = RequestContext.instance.client_ip
|
2017-02-20 09:09:05 -05:00
|
|
|
unique_ips = update_and_return_ips_count(user_id, ip)
|
2017-03-03 12:10:22 -05:00
|
|
|
|
2017-02-06 07:48:46 -05:00
|
|
|
raise TooManyIps.new(user_id, ip, unique_ips) if unique_ips > config.unique_ips_limit_per_user
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def limit_user!(user = nil)
|
2017-03-03 12:10:22 -05:00
|
|
|
user ||= yield if block_given?
|
2017-02-06 07:48:46 -05:00
|
|
|
limit_user_id!(user.id) unless user.nil?
|
|
|
|
user
|
|
|
|
end
|
|
|
|
|
|
|
|
def config
|
|
|
|
Gitlab::CurrentSettings.current_application_settings
|
|
|
|
end
|
|
|
|
|
2017-02-20 09:09:05 -05:00
|
|
|
def update_and_return_ips_count(user_id, ip)
|
|
|
|
time = Time.now.utc.to_i
|
2017-02-06 07:48:46 -05:00
|
|
|
key = "#{USER_UNIQUE_IPS_PREFIX}:#{user_id}"
|
|
|
|
|
2017-07-10 23:35:47 -04:00
|
|
|
Gitlab::Redis::SharedState.with do |redis|
|
2017-02-06 07:48:46 -05:00
|
|
|
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
|