mirror of
https://github.com/bunkerity/bunkerized-nginx
synced 2023-12-13 21:30:18 +01:00
71 lines
2 KiB
Text
71 lines
2 KiB
Text
server {
|
|
server_name {{ API_SERVER_NAME }};
|
|
|
|
# HTTP listen
|
|
listen {{ API_LISTEN_IP }}:{{ API_HTTP_PORT }} reuseport;
|
|
{% if API_LISTEN_IP != "127.0.0.1" +%}
|
|
listen 127.0.0.1:{{ API_HTTP_PORT }} reuseport;
|
|
{% 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)
|
|
}
|
|
}
|