httpserver-basicauth.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. -- httpserver-basicauth.lua
  2. -- Part of nodemcu-httpserver, authenticates a user using http basic auth.
  3. -- Author: Sam Dieck
  4. basicAuth = {}
  5. -- Returns true if the user/password match one of the users/passwords in httpserver-conf.lua.
  6. -- Returns false otherwise.
  7. function loginIsValid(user, pwd, users)
  8. if user == nil then return false end
  9. if pwd == nil then return false end
  10. if users[user] == nil then return false end
  11. if users[user] ~= pwd then return false end
  12. return true
  13. end
  14. -- Parse basic auth http header.
  15. -- Returns the username if header contains valid credentials,
  16. -- nil otherwise.
  17. function basicAuth.authenticate(header)
  18. local conf = dofile("httpserver-conf.lc")
  19. local credentials_enc = header:match("Authorization: Basic ([A-Za-z0-9+/=]+)")
  20. if not credentials_enc then
  21. return nil
  22. end
  23. local credentials = dofile("httpserver-b64decode.lc")(credentials_enc)
  24. local user, pwd = credentials:match("^(.*):(.*)$")
  25. if loginIsValid(user, pwd, conf.auth.users) then
  26. print("httpserver-basicauth: User \"" .. user .. "\": Authenticated.")
  27. return user
  28. else
  29. print("httpserver-basicauth: User \"" .. user .. "\": Access denied.")
  30. return nil
  31. end
  32. end
  33. function basicAuth.authErrorHeader()
  34. local conf = dofile("httpserver-conf.lc")
  35. return "WWW-Authenticate: Basic realm=\"" .. conf.auth.realm .. "\""
  36. end
  37. return basicAuth