From 79e345d964fb2b26f053254d02859c7934c427b6 Mon Sep 17 00:00:00 2001 From: Marcos Kirsch Date: Wed, 28 Dec 2016 14:16:58 -0600 Subject: [PATCH] Allow multiple users for basic HTTP authentication. --- httpserver-basicauth.lua | 17 ++++++++++++++--- httpserver-conf.lua | 6 +++--- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/httpserver-basicauth.lua b/httpserver-basicauth.lua index 09d4f78..42109ec 100644 --- a/httpserver-basicauth.lua +++ b/httpserver-basicauth.lua @@ -4,6 +4,16 @@ 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. @@ -15,12 +25,13 @@ function basicAuth.authenticate(header) end local credentials = dofile("httpserver-b64decode.lc")(credentials_enc) local user, pwd = credentials:match("^(.*):(.*)$") - if user ~= conf.auth.user or pwd ~= conf.auth.password then + 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 - print("httpserver-basicauth: User \"" .. user .. "\": Authenticated.") - return user end function basicAuth.authErrorHeader() diff --git a/httpserver-conf.lua b/httpserver-conf.lua index 854e557..54ef5fd 100644 --- a/httpserver-conf.lua +++ b/httpserver-conf.lua @@ -6,10 +6,10 @@ local conf = {} -- Basic Authentication Conf local auth = {} -auth.enabled = false +auth.enabled = true auth.realm = "nodemcu-httpserver" -- displayed in the login dialog users get -auth.user = "user" -auth.password = "password" -- PLEASE change this +-- Add users and passwords to this table. Do not leave this unchanged if you enable authentication! +auth.users = {user1 = "password1", user2 = "password2", user3 = "password3"} conf.auth = auth return conf