passwd-verify.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. function auth_password_verify(request, password)
  2. request.domain = request.auth_user:match("@(.+)") or nil
  3. if request.domain == nil then
  4. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user"
  5. end
  6. local json = require "cjson"
  7. local ltn12 = require "ltn12"
  8. local https = require "ssl.https"
  9. https.TIMEOUT = 30
  10. local req = {
  11. username = request.auth_user,
  12. password = password,
  13. real_rip = request.remote_ip,
  14. service = request.protocol
  15. }
  16. local req_json = json.encode(req)
  17. local res = {}
  18. local b, c = https.request {
  19. method = "POST",
  20. url = "https://nginx:9082",
  21. source = ltn12.source.string(req_json),
  22. headers = {
  23. ["content-type"] = "application/json",
  24. ["content-length"] = tostring(#req_json)
  25. },
  26. sink = ltn12.sink.table(res),
  27. insecure = true
  28. }
  29. -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry.
  30. -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry,
  31. -- even if the TTL has expired. Useful to avoid cache eviction during backend issues.
  32. if c ~= 200 and c ~= 401 then
  33. return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Upstream error"
  34. end
  35. local response_str = table.concat(res)
  36. local is_response_valid, response_json = pcall(json.decode, response_str)
  37. if not is_response_valid then
  38. dovecot.i_info("Invalid JSON received: " .. response_str)
  39. return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Invalid response format"
  40. end
  41. if response_json.success == true then
  42. return dovecot.auth.PASSDB_RESULT_OK, { msg = "" }
  43. end
  44. return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate"
  45. end
  46. function auth_passdb_lookup(req)
  47. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, ""
  48. end
  49. function auth_passdb_get_cache_key()
  50. return "%{protocol}:%{user | username}\t:%{password}"
  51. end