httpserver-basicauth.lua 1.0 KB

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