Skip to content

Instantly share code, notes, and snippets.

@vdel26
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save vdel26/cc12c36234ecee5f92a6 to your computer and use it in GitHub Desktop.

Select an option

Save vdel26/cc12c36234ecee5f92a6 to your computer and use it in GitHub Desktop.
Send Application plan as a header named X-3scale-Plan
...
location / {
set $provider_key null;
set $cached_key null;
set $credentials null;
set $usage null;
set $service_id YOURSERVICEID;
set $proxy_pass null;
set $secret_token null;
set $plan_header null; # ADD THIS LINE
proxy_ignore_client_abort on;
## CHANGE THE PATH TO POINT TO THE RIGHT FILE ON YOUR FILESYSTEM
access_by_lua_file /opt/openresty/nginx/conf/nginx.lua;
proxy_pass $proxy_pass ;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host api-sentiment.3scale.net;
proxy_set_header X-3scale-proxy-secret-token $secret_token;
proxy_set_header X-3scale-plan $plan_header; # ADD THIS LINE
post_action /out_of_band_authrep_action;
}
...
-- new helper function to add
function parse_cached_value(val)
local is_known, plan
if val == nil then
is_known = false
plan = nil
else
local idx = val:find(":")
if idx then
is_known = val:sub(1, idx-1)
plan = val:sub(idx+1)
else
is_known = val
plan = nil
end
end
return is_known, plan
end
-- replace authrep function by this one
function authrep(params, service)
ngx.var.cached_key = ngx.var.cached_key .. ":" .. ngx.var.usage
local api_keys = ngx.shared.api_keys
local val = api_keys:get(ngx.var.cached_key)
local is_known, cached_plan = parse_cached_value(val)
-- set X-3scale-Plan header if it was in the cache before
-- otherwise will be nil and will be overwritten below
ngx.var.plan_header = cached_plan
-- key is not in cache, check synchronously with 3scale backend
if is_known ~= "200" then
local res = ngx.location.capture("/threescale_authrep", { share_all_vars = true })
-- get Application plan
local m, err = ngx.re.match(res.body, [[<plan>(\w+)<\/plan>]])
local plan
if m then plan = m[1] end
if res.status ~= 200 then
-- not authorized, make sure we delete the key from cache
api_keys:delete(ngx.var.cached_key)
-- unset X-3scale-Plan
ngx.var.plan_header = nil
ngx.status = res.status
ngx.header.content_type = "application/json"
error_authorization_failed(service)
else
-- authorized, cache key to check asynchronously on next request
local cached_value = "200:" .. plan
-- keep Application plan in the local cache for next requests
api_keys:set(ngx.var.cached_key, cached_value)
-- set header X-3scale-Plan
ngx.var.plan_header = plan
end
ngx.var.cached_key = nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment