bunkerized-nginx/src/common/confs/api.conf
2023-09-29 18:11:48 +01:00

72 lines
2 KiB
Plaintext

server {
server_name {{ API_SERVER_NAME }};
# HTTP listen
listen {{ API_LISTEN_IP }}:{{ API_HTTP_PORT }};
{% if API_LISTEN_IP != "127.0.0.1" +%}
listen 127.0.0.1:{{ API_HTTP_PORT }};
{% endif %}
# maximum body size for API
client_max_body_size 1G;
# default mime type is JSON
default_type 'application/json';
# check IP and do the API call
access_by_lua_block {
-- Instantiate objects and import required modules
local logger = require "bunkerweb.logger":new("API")
local api = require "bunkerweb.api":new()
local helpers = require "bunkerweb.helpers"
-- Start API handler
logger:log(ngx.INFO, "API handler started")
-- Fill ctx
logger:log(ngx.INFO, "filling ngx.ctx ...")
local ok, ret, errors, ctx = helpers.fill_ctx()
if not ok then
logger:log(ngx.ERR, "fill_ctx() failed : " .. ret)
elseif errors then
for i, error in ipairs(errors) do
logger:log(ngx.ERR, "fill_ctx() error " .. tostring(i) .. " : " .. error)
end
end
logger:log(ngx.INFO, "ngx.ctx filled (ret = " .. ret .. ")")
-- Check host header
if not ctx.bw.http_host or ctx.bw.http_host ~= "{{ API_SERVER_NAME }}" then
logger:log(ngx.WARN, "wrong Host header from IP " .. ctx.bw.remote_addr)
return ngx.exit(ngx.HTTP_CLOSE)
end
-- Check IP
local ok, err = api:is_allowed_ip()
if not ok then
logger:log(ngx.WARN, "can't validate access from IP " .. ctx.bw.remote_addr .. " : " .. err)
return ngx.exit(ngx.HTTP_CLOSE)
end
logger:log(ngx.NOTICE, "validated access from IP " .. ctx.bw.remote_addr)
-- Do API call
local ok, err, status, resp = api:do_api_call()
if not ok then
logger:log(ngx.WARN, "call from " .. ctx.bw.remote_addr .. " on " .. ctx.bw.uri .. " failed : " .. err)
else
logger:log(ngx.NOTICE, "successful call from " .. ctx.bw.remote_addr .. " on " .. ctx.bw.uri .. " : " .. err)
end
-- Start API handler
logger:log(ngx.INFO, "API handler ended")
-- Save ctx
ngx.ctx = ctx
-- Send response
ngx.status = status
ngx.say(resp)
return ngx.exit(status)
}
}