Commit 8fd9da65 by Ivan Lan

Support appid

parent 17c7f7cd
......@@ -2,4 +2,10 @@ IpWhitelist.redis = Redic.new
rails g ip_whitelist:migrations
include IpWhitelist::Interceptor
\ No newline at end of file
class ApplicatonController < ActiveController::Base
include IpWhitelist::Interceptor
end
class TestsController < ApplicationController
ip_interceptor :your_appid, only: :your_action
end
\ No newline at end of file
......@@ -3,6 +3,7 @@ class CreateIpWhitelistList < ActiveRecord::Migration[5.1]
create_table :ip_whitelist_lists do |t|
t.string :descr
t.string :ips
t.string :appid
end
end
end
......@@ -3,15 +3,26 @@ module IpWhitelist
extend ActiveSupport::Concern
included do
before_action :ip_intercept
rescue_from IpWhitelist::Error do |e|
render json: { code: e.code, message: e.message }, status: e.status
end
end
class_methods do
def ip_interceptor appid, only: nil
@@appid = appid
only ?
before_action(:ip_intercept, only: only) :
before_action(:ip_intercept)
def ip_intercept
unless IpWhitelist::List.ips.include?(request.ip)
raise IpWhitelist::Error.new(status: 403, message: 'Invaild Request')
class_eval do
private
def ip_intercept
p @@appid
IpWhitelist::List.auth!(@@appid, request.ip)
end
end
end
end
......
......@@ -2,19 +2,40 @@ module IpWhitelist
class List < ActiveRecord::Base
self.table_name = 'ip_whitelist_lists'
REDIS_KEY = 'ip-whitelist-redis'
REDIS_KEY = '`ip-whitelist-redis`'
validates_presence_of :ips
validates_presence_of :ips, :appid
after_save :load
after_destroy :load
def redis_key
self.class.redis_key(appid)
end
private
def load
self.class.load
end
class << self
def ips
IpWhitelist.redis.get(REDIS_KEY)&.split(',') || load
def redis_key appid
"#{REDIS_KEY}-#{appid}"
end
def auth! appid, ip
unless IpWhitelist.redis.hget(redis_key(appid), ip)
raise IpWhitelist::Error.new(status: 403, message: 'Invaild Request')
end
end
def load
ips_ary = all.pluck(:ips).map { |ips_str| ips_str.split(',') }.reduce(:+) || []
IpWhitelist.redis.set(REDIS_KEY, ips_ary.join(','))
ips_ary
redis = IpWhitelist.redis
redis.keys(redis_key('*')).each { |key| redis.del(key) }
IpWhitelist::List.all.each do |list|
list.ips.split(',').each { |ip| redis.hset(list.redis_key, ip, true) }
end
end
end
end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment