summaryrefslogtreecommitdiffstats
path: root/msb-core/openresty-ext/src/assembly/resources/openresty/nginx/luaext/make_authed.lua
blob: c4c2d788675576209337f35f3938fd9ba20c4014 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function ipValidator(ip)
	local chunks = {ip:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")}
	if #chunks == 4 then
		for _,v in pairs(chunks) do
			if tonumber(v) > 255 then return R.STRING end
		end
		return true
	end
	local chunks = {ip:match(("([a-fA-F0-9]*):"):rep(8):gsub(":$","$"))}
	if #chunks == 8 then
		for _,v in pairs(chunks) do
			if #v > 0 and tonumber(v, 16) > 65535 then return R.STRING end
		end
		return true
	end
	return false
end	

if ngx.req.get_method() == "POST" then
	ngx.req.read_body()
	local body = ngx.req.get_body_data()	
	local json = require('cjson')
	local tab = json.decode(body)
	local ip = tab["passIp"]
	if not ip then
		ngx.log(ngx.WARN, "ip is nil.")
		ngx.exit(500)
	end
	if ipValidator(ip) then
		local cache = ngx.shared.ceryx
		local succ, err, forcible = cache:set(ip, "place_holder", 3600)
		if not succ then
			ngx.log(ngx.WARN, err)
			ngx.exit(500)
		end
	else
		ngx.log(ngx.WARN, "not a valid ip.")
		ngx.exit(500)
	end		
	ngx.exit(201)
else
	ngx.log(ngx.WARN, "not a POST request.")
	ngx.exit(500)
end