location = {{ ANTIBOT_URI }} {

	default_type 'text/html';
	
	if ($request_method = GET) {
		content_by_lua_block {
			local cookie		= require "cookie"
			local javascript	= require "javascript"
			local logger		= require "logger"
			if not cookie.is_set("challenge") then
				logger.log(ngx.WARN, "ANTIBOT", "javascript fail (1) for " .. ngx.var.remote_addr)
				return ngx.exit(ngx.HTTP_FORBIDDEN)
			end
			local challenge	= cookie.get("challenge")
			local code	= javascript.get_code(challenge, "{{ ANTIBOT_URI }}", cookie.get("uri"))
			ngx.say(code)
		}
	}
	
	if ($request_method = POST) {
		content_by_lua_block {
			local cookie		= require "cookie"
			local javascript	= require "javascript"
			local logger		= require "logger"
			if not cookie.is_set("challenge") then
				logger.log(ngx.WARN, "ANTIBOT", "javascript 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["challenge"] then
				logger.log(ngx.WARN, "ANTIBOT", "javascript fail (3) for " .. ngx.var.remote_addr)
				return ngx.exit(ngx.HTTP_FORBIDDEN)
			end
			local challenge		= args["challenge"]
			local check		= javascript.check(cookie.get("challenge"), challenge)
			if not check then
				logger.log(ngx.WARN, "ANTIBOT", "javascript fail (4) for " .. ngx.var.remote_addr)
				return ngx.exit(ngx.HTTP_FORBIDDEN)
			end
			cookie.set({javascript = "ok"})
			return ngx.exit(ngx.OK)
		}
	}
}
