Skip to content

Instantly share code, notes, and snippets.

@dannymcc
Created July 24, 2012 19:57
Show Gist options
  • Select an option

  • Save dannymcc/3172246 to your computer and use it in GitHub Desktop.

Select an option

Save dannymcc/3172246 to your computer and use it in GitHub Desktop.
Protect from all but whitelist
before_filter :protect
def protect
@ips = ['127.0.0.1', '192.168.1.0/24'] #And so on ...]
allowed = false
@ips.each do |ipstring|
ip, mask = ipstring.split '/'
mask = mask ? mask.to_i : 32
bip = 0
ip.split('.').each { |x| bip = (bip << 8) + x.to_i }
bmask = ((1 << mask) - 1) << (32 - mask)
if bip & bmask == request.remote_ip & bmask
allowed = true
break
end
end
if not allowed
render :template => "static/protect"
return
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment