Files
grecia/app/lib/restrict_admin_ips.rb
CoslaJohn 424cedc0c8 Restrict access to admin functions by IP
There are many possible ways to implement this feature:

* Adding a custom middleware
* Using rack-attack with a blocklist
* Using routes constraints

We're choosing to use a controller concern with a redirect because it's
what we do to handle unauthorized cancancan exceptions.
2024-10-30 15:59:50 +01:00

38 lines
784 B
Ruby

class RestrictAdminIps
attr_reader :ip
def initialize(ip)
@ip = ip
end
def allowed?
unrestricted_access? || allowed_ip?
end
private
def unrestricted_access?
allowed_ips.blank?
end
def allowed_ips
Array(Tenant.current_secrets.dig(:security, :allowed_admin_ips))
end
def allowed_ip?
normalized_allowed_ips.any? { |allowed_ip| allowed_ip.include?(ip) }
rescue IPAddr::Error
false
end
def normalized_allowed_ips
allowed_ips.map do |allowed_ip|
IPAddr.new(allowed_ip)
rescue IPAddr::Error
Rails.logger.warn "Your allowed_admin_ips configuration includes the " \
"address \"#{allowed_ip}\", which is not valid"
nil
end.compact
end
end