BigW Consortium Gitlab

unique_ips_limiter.rb 1.21 KB
Newer Older
1 2 3
module Gitlab
  module Auth
    class UniqueIpsLimiter
4
      USER_UNIQUE_IPS_PREFIX = 'user_unique_ips'.freeze
5 6 7 8 9

      class << self
        def limit_user_id!(user_id)
          if config.unique_ips_limit_enabled
            ip = RequestContext.client_ip
10
            unique_ips = update_and_return_ips_count(user_id, ip)
11

12 13 14 15 16
            raise TooManyIps.new(user_id, ip, unique_ips) if unique_ips > config.unique_ips_limit_per_user
          end
        end

        def limit_user!(user = nil)
17
          user ||= yield if block_given?
18 19 20 21 22 23 24 25
          limit_user_id!(user.id) unless user.nil?
          user
        end

        def config
          Gitlab::CurrentSettings.current_application_settings
        end

26 27
        def update_and_return_ips_count(user_id, ip)
          time = Time.now.utc.to_i
28 29
          key = "#{USER_UNIQUE_IPS_PREFIX}:#{user_id}"

30
          Gitlab::Redis::SharedState.with do |redis|
31 32 33 34 35 36 37 38 39 40 41 42 43
            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