location = %ANTIBOT_URI% { default_type 'text/html'; if ($request_method = GET) { content_by_lua_block { local cookie = require "cookie" local recaptcha = require "recaptcha" if not cookie.is_set("uri") then ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (1) for " .. ngx.var.remote_addr) return ngx.exit(ngx.HTTP_FORBIDDEN) end local code = recaptcha.get_code("%ANTIBOT_URI%", "%ANTIBOT_RECAPTCHA_SITEKEY%") ngx.say(code) } } if ($request_method = POST) { access_by_lua_block { local cookie = require "cookie" local recaptcha = require "recaptcha" if not cookie.is_set("uri") then ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (2) for " .. ngx.var.remote_addr) return ngx.exit(ngx.HTTP_FORBIDDEN) end ngx.req.read_body() local args, err = ngx.req.get_post_args(1) if err == "truncated" or not args or not args["token"] then ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (3) for " .. ngx.var.remote_addr) return ngx.exit(ngx.HTTP_FORBIDDEN) end local token = args["token"] local check = recaptcha.check(token, "%ANTIBOT_RECAPTCHA_SECRET%") if check < %ANTIBOT_RECAPTCHA_SCORE% then ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (4) for " .. ngx.var.remote_addr .. " (score = " .. tostring(check) .. ")") return ngx.exit(ngx.HTTP_FORBIDDEN) end cookie.set({recaptcha = "ok"}) return ngx.redirect(cookie.get("uri")) } } }