imap.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # RadicaleIMAP IMAP authentication plugin for Radicale.
  2. # Copyright © 2017, 2020 Unrud <unrud@outlook.com>
  3. # Copyright © 2025-2025 Peter Bieringer <pb@bieringer.de>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. import imaplib
  18. import ssl
  19. from radicale import auth
  20. from radicale.log import logger
  21. class Auth(auth.BaseAuth):
  22. """Authenticate user with IMAP."""
  23. def __init__(self, configuration) -> None:
  24. super().__init__(configuration)
  25. self._host, self._port = self.configuration.get("auth", "imap_host")
  26. logger.info("auth imap host: %r", self._host)
  27. self._security = self.configuration.get("auth", "imap_security")
  28. if self._security == "none":
  29. logger.info("auth imap security: %s (INSECURE, credentials are transmitted in clear text)", self._security)
  30. else:
  31. logger.info("auth imap security: %s", self._security)
  32. if self._security == "tls":
  33. if self._port is None:
  34. self._port = 993
  35. logger.info("auth imap port (autoselected): %d", self._port)
  36. else:
  37. logger.info("auth imap port: %d", self._port)
  38. else:
  39. if self._port is None:
  40. self._port = 143
  41. logger.info("auth imap port (autoselected): %d", self._port)
  42. else:
  43. logger.info("auth imap port: %d", self._port)
  44. def _login(self, login, password) -> str:
  45. try:
  46. if self._security == "tls":
  47. connection = imaplib.IMAP4_SSL(
  48. host=self._host, port=self._port,
  49. ssl_context=ssl.create_default_context())
  50. else:
  51. connection = imaplib.IMAP4(host=self._host, port=self._port)
  52. if self._security == "starttls":
  53. connection.starttls(ssl.create_default_context())
  54. try:
  55. connection.login(login, password)
  56. except imaplib.IMAP4.error as e:
  57. logger.warning("IMAP authentication failed for user %r: %s", login, e, exc_info=False)
  58. return ""
  59. connection.logout()
  60. return login
  61. except (OSError, imaplib.IMAP4.error) as e:
  62. logger.error("Failed to communicate with IMAP server %r: %s" % ("[%s]:%d" % (self._host, self._port), e))
  63. return ""