* Fixed global assignment that should be local Made result variable be local, see Issue #113 * Made global variable local Made ASCII variable be local, see Issue #113 * Made more variables local Related to Issue #113. questionMarkPos, and b,c,d,e,f all are global in scope, and are not cleared from memory, so leak. Frankly, b, c, d, e, and f are not used either, but will now get GC'd later, if they ever were assigned, so not problematic line 114 also has _ and i to make local too, so were put on their own line. i on line 24 also was unnecessarily global, and undetected in issue #113 * Made module more local Made the basicAuth table local in scope. Since it is returned when dofile is called in httpserver.lua, that already has a correctly scoped table, 'auth'. This is related to issue #113, and should reduce memory loss to globals * Made bufferedConnection local bufferedConnection was global and didn't have to be. Part of issue #113. Now no longer remains in _G (globals table) after a connection has closed.
43 lines
1.4 KiB
Lua
43 lines
1.4 KiB
Lua
-- httpserver-basicauth.lua
|
|
-- Part of nodemcu-httpserver, authenticates a user using http basic auth.
|
|
-- Author: Sam Dieck
|
|
|
|
local basicAuth = {}
|
|
|
|
-- Returns true if the user/password match one of the users/passwords in httpserver-conf.lua.
|
|
-- Returns false otherwise.
|
|
function loginIsValid(user, pwd, users)
|
|
if user == nil then return false end
|
|
if pwd == nil then return false end
|
|
if users[user] == nil then return false end
|
|
if users[user] ~= pwd then return false end
|
|
return true
|
|
end
|
|
|
|
-- Parse basic auth http header.
|
|
-- Returns the username if header contains valid credentials,
|
|
-- nil otherwise.
|
|
function basicAuth.authenticate(header)
|
|
local conf = dofile("httpserver-conf.lc")
|
|
local credentials_enc = header:match("Authorization: Basic ([A-Za-z0-9+/=]+)")
|
|
if not credentials_enc then
|
|
return nil
|
|
end
|
|
local credentials = dofile("httpserver-b64decode.lc")(credentials_enc)
|
|
local user, pwd = credentials:match("^(.*):(.*)$")
|
|
if loginIsValid(user, pwd, conf.auth.users) then
|
|
print("httpserver-basicauth: User \"" .. user .. "\": Authenticated.")
|
|
return user
|
|
else
|
|
print("httpserver-basicauth: User \"" .. user .. "\": Access denied.")
|
|
return nil
|
|
end
|
|
end
|
|
|
|
function basicAuth.authErrorHeader()
|
|
local conf = dofile("httpserver-conf.lc")
|
|
return "WWW-Authenticate: Basic realm=\"" .. conf.auth.realm .. "\""
|
|
end
|
|
|
|
return basicAuth
|