I'm working on a little project using nodeMCU and Lua but i'm pretty new to these sort of things and i can't find a solution to my problem.
The project is basically to do a first access on the server, receive a page of control where I have to press a button connected to my nodemcu and after clicking it and refreshing i can reach the index page i loaded on the device.
The problem that I'm encountering is that if someone already reached the index page, everyone that tries to connect to the server will also go directly to the index, surpassing completely the control page.
I tried some solutions but none of them have worked in the end, so I'm asking if there is any easy solution to this.
Here is my code, with what is working so far:
-- auth.lua
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(client,request)
local buf = "";
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
end
local _, _, auth = string.find(request, "%cAuthorization: Basic ([%w=\+\/]+)");--Authorization:
if (auth == nil or auth ~= "dXNlcjoxMjM0")then --user:1234
client:send("HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"ESP8266 Web Server\"\r\n\r\n<h1>Unauthorized Access</h1>");
client:close();
return;
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf=buf.."<html><body>"
buf = buf.."<h1> Control Web Server</h1>";
buf=buf.."<p> Press the button attached to the device and click below</p>"
buf=buf.."<p><button onclick=\"history.go(0)\">ADVANCE</button></p>"
buf = buf.."</form></body></html>"
local _on,_off = "",""
gpio.mode(1 ,gpio.INPUT,gpio.PULLUP)
function debounce (func)
local last = 0
local delay = 200000
return function (...)
local now = tmr.now()
if now - last < delay then return end
last = now
return func(...)
end
end
function onChange()
if gpio.read(1) == 0 then
assert(loadfile("serverpin.lua"))
tmr.delay(500000)
end
end
gpio.trig(1,"down", debounce(onChange))
client:send(buf);
client:close();
collectgarbage();
end)
end)
--serverpin.lua
srv:listen(80,function(conn)
conn:on("receive", function(client,payload)
print(payload)
tgtfile = string.sub(payload,string.find(payload,"GET /")
+5,string.find(payload,"HTTP/")-2)
if tgtfile == "" then tgtfile = "index.htm" end
local f = file.open(tgtfile,"r")
if f ~= nil then
client:send(file.read())
file.close()
else
client:send("<html>"..tgtfile.." not found - 404 error.<BR><a href='index.htm'>Home</a><BR>")
end
client:close();
collectgarbage();
f = nil
tgtfile = nil
end)
end)