add initialization callback for filters

This commit is contained in:
Luna 2022-12-06 14:52:09 -03:00
parent eefdecb1e9
commit a747fe8182
2 changed files with 21 additions and 19 deletions

View file

@ -18,8 +18,10 @@ local WANTED_SCRIPTS = {
local compiled_chain = {} local compiled_chain = {}
for module_name, module_config in pairs(WANTED_SCRIPTS) do for module_name, module_config in pairs(WANTED_SCRIPTS) do
module = require(module_name) local module = require(module_name)
table.insert(compiled_chain, {module, module_config}) local module_state = module.init(module_config)
-- TODO is it possible to make module_config readonly?
table.insert(compiled_chain, {module, module_config, module_state})
end end
local function onRequest() local function onRequest()
@ -28,12 +30,12 @@ local function onRequest()
-- find out which modules to call based on their regexes -- find out which modules to call based on their regexes
local callbacks_to_call = {} local callbacks_to_call = {}
for _, filter in ipairs(compiled_chain) do for _, filter in ipairs(compiled_chain) do
local module, module_config = filter[1], filter[2] local module, module_config, state = unpack(filter)
for callback_regex, callback_function in pairs(module.callbacks) do for callback_regex, callback_function in pairs(module.callbacks) do
local match, error = ngx.re.match(request_uri, callback_regex) local match, error = ngx.re.match(request_uri, callback_regex)
if match then if match then
table.insert(callbacks_to_call, {callback_function, module_config}) table.insert(callbacks_to_call, {callback_function, module_config, state})
end end
end end
end end

View file

@ -1,25 +1,24 @@
function webfingerCallback(cfg) function webfingerInit(cfg)
local accounts_set = {}
for _, account in ipairs(cfg.accounts) do
accounts_set["acct:" .. account] = true
end
return accounts_set
end
function webfingerCallback(cfg, accounts_set)
local args, err = ngx.req.get_uri_args() local args, err = ngx.req.get_uri_args()
if err == "truncated" then if err == "truncated" then
return false, 'uri args too long' return 400, 'uri args too long'
end end
local resource = args['resource'] local resource = args['resource']
if resource ~= nil then if accounts_set[resource] then
-- TODO this is O(n) but we can make it O(1) by doing a funny and making return nil
-- cfg.accounts be transformed into keys in a table else
-- return 404, "Couldn't find user"
-- this would require us to do some setup() callback as well as
-- the request() callback
for _, account in ipairs(cfg.accounts) do
if resource == account then
return true
end end
end end
end
return false
end
return { return {
name='WebfingerAllowlist', name='WebfingerAllowlist',
@ -32,6 +31,7 @@ return {
Useful for small instances. Useful for small instances.
]], ]],
apiVersion=1, apiVersion=1,
init=webfingerInit,
callbacks = { callbacks = {
['/.well-known/webfinger'] = webfingerCallback ['/.well-known/webfinger'] = webfingerCallback
}, },