Skip to content

Instantly share code, notes, and snippets.

@ariankordi
Created January 20, 2019 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariankordi/10bf177302ca6936a118693a90c72393 to your computer and use it in GitHub Desktop.
Save ariankordi/10bf177302ca6936a118693a90c72393 to your computer and use it in GitHub Desktop.
# closedpizza-authorization.rb - mruby handler to check if all clients
# have accounts on closed.pizza, checked via ip address and result kept with lrucache
# there is also a redis class in h2o mruby but it probably isn't worth using
# to change returned status code/response for unauthorized users, see end of call method
# paths:
# /:
# mruby.handler-file: /path/to/closedpizza-authorization.rb
# lrucache class
require "/usr/share/h2o/mruby/lru_cache.rb"
class ClosedPizzaAuthorization
def initialize()
# make a new lrucache with size 64 to use through this class
@cache = LRUCache.new(64)
end
# handler before every request
def call(env)
# get value from cache with key of the ip address
# if the cache doesn't exist, do everything in this block
unless allowed = @cache.get(env["REMOTE_ADDR"])
# closed.pizza ip existence api thing
# this will check to see if the ip belongs to any user on closed.pizza
req = http_request("http://closed.pizza/Bf9Euj6Vy3s3wDWC/#{env["REMOTE_ADDR"]}")
# execute request and get status code
status = req.join[0]
# if status is 202 then the ip is ok, otherwise it isn't
# value of 1 if ok, value of 2 if not good
allowed = status == 202 ? 1 : 2
# put allowed, an int of one byte, into cache
@cache.set(env["REMOTE_ADDR"], allowed)
end
# ip address is allowed
if allowed == 1
# go to next handler (status 399) and return
return [399, {}, []]
end
# ip address isn't allowed, return status 444, empty response
# TODO: change this to 403? or somehow add ip address to fail2ban jail?
[444, {}, []]
end
end
# return new instance
ClosedPizzaAuthorization.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment