passwd-verify.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function auth_password_verify(request, password)
  2. if request.domain == nil then
  3. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user"
  4. end
  5. local json = require "cjson"
  6. local ltn12 = require "ltn12"
  7. local https = require "ssl.https"
  8. https.TIMEOUT = 30
  9. local req = {
  10. username = request.user,
  11. password = password,
  12. real_rip = request.real_rip,
  13. service = request.service
  14. }
  15. local req_json = json.encode(req)
  16. local res = {}
  17. local b, c = https.request {
  18. method = "POST",
  19. url = "https://nginx:9082",
  20. source = ltn12.source.string(req_json),
  21. headers = {
  22. ["content-type"] = "application/json",
  23. ["content-length"] = tostring(#req_json)
  24. },
  25. sink = ltn12.sink.table(res),
  26. insecure = true
  27. }
  28. -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry.
  29. -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry,
  30. -- even if the TTL has expired. Useful to avoid cache eviction during backend issues.
  31. if c ~= 200 and c ~= 401 then
  32. dovecot.i_info("HTTP request failed with " .. c .. " for user " .. request.user)
  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, ""
  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