httpserver-basicauth.lua 928 B

1234567891011121314151617181920212223242526272829
  1. -- httpserver-basicauth.lua
  2. -- Part of nodemcu-httpserver, authenticates a user using http basic auth.
  3. -- Author: Sam Dieck
  4. basicAuth = {}
  5. function basicAuth.authenticate(header)
  6. conf = dofile("httpserver-conf.lc")
  7. -- Parse basic auth http header.
  8. -- Returns the username if header contains valid credentials,
  9. -- nil otherwise.
  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("b64.lc").decode(credentials_enc)
  15. local user, pwd = credentials:match("^(.*):(.*)$")
  16. if user ~= conf.auth.user or pwd ~= conf.auth.password then
  17. return nil
  18. end
  19. print("httpserver-basicauth: User " .. user .. " authenticated.")
  20. return user
  21. end
  22. function basicAuth.authErrorHeader()
  23. return "WWW-Authenticate: Basic realm=\"nodemcu-httpserver\""
  24. end
  25. return basicAuth