httpserver-basicauth.lua 962 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. -- Parse basic auth http header.
  6. -- Returns the username if header contains valid credentials,
  7. -- nil otherwise.
  8. function basicAuth.authenticate(header)
  9. local credentials_enc = header:match("Authorization: Basic ([A-Za-z0-9+/=]+)")
  10. if not credentials_enc then
  11. return nil
  12. end
  13. local credentials = encoder.fromBase64(credentials_enc)
  14. local user, pwd = credentials:match("^(.*):(.*)$")
  15. if user ~= conf.auth.user or pwd ~= conf.auth.password then
  16. print("httpserver-basicauth: User \"" .. user .. "\": Access denied.")
  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=\"" .. conf.auth.realm .. "\""
  24. end
  25. return basicAuth