location = {{ ANTIBOT_URI }} {

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