Commit 8fd9da65 by Ivan Lan

Support appid

parent 17c7f7cd
...@@ -2,4 +2,10 @@ IpWhitelist.redis = Redic.new ...@@ -2,4 +2,10 @@ IpWhitelist.redis = Redic.new
rails g ip_whitelist:migrations rails g ip_whitelist:migrations
include IpWhitelist::Interceptor class ApplicatonController < ActiveController::Base
\ No newline at end of file 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] ...@@ -3,6 +3,7 @@ class CreateIpWhitelistList < ActiveRecord::Migration[5.1]
create_table :ip_whitelist_lists do |t| create_table :ip_whitelist_lists do |t|
t.string :descr t.string :descr
t.string :ips t.string :ips
t.string :appid
end end
end end
end end
...@@ -3,15 +3,26 @@ module IpWhitelist ...@@ -3,15 +3,26 @@ module IpWhitelist
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
before_action :ip_intercept
rescue_from IpWhitelist::Error do |e| rescue_from IpWhitelist::Error do |e|
render json: { code: e.code, message: e.message }, status: e.status render json: { code: e.code, message: e.message }, status: e.status
end end
end
class_methods do
def ip_interceptor appid, only: nil
@@appid = appid
only ?
before_action(:ip_intercept, only: only) :
before_action(:ip_intercept)
class_eval do
private
def ip_intercept def ip_intercept
unless IpWhitelist::List.ips.include?(request.ip) p @@appid
raise IpWhitelist::Error.new(status: 403, message: 'Invaild Request') IpWhitelist::List.auth!(@@appid, request.ip)
end
end end
end end
end end
......
...@@ -2,19 +2,40 @@ module IpWhitelist ...@@ -2,19 +2,40 @@ module IpWhitelist
class List < ActiveRecord::Base class List < ActiveRecord::Base
self.table_name = 'ip_whitelist_lists' 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 class << self
def ips def redis_key appid
IpWhitelist.redis.get(REDIS_KEY)&.split(',') || load "#{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 end
def load def load
ips_ary = all.pluck(:ips).map { |ips_str| ips_str.split(',') }.reduce(:+) || [] redis = IpWhitelist.redis
IpWhitelist.redis.set(REDIS_KEY, ips_ary.join(',')) redis.keys(redis_key('*')).each { |key| redis.del(key) }
ips_ary IpWhitelist::List.all.each do |list|
list.ips.split(',').each { |ip| redis.hset(list.redis_key, ip, true) }
end
end end
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