account_validity.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import email.mime.multipart
  16. import email.utils
  17. import logging
  18. from email.mime.multipart import MIMEMultipart
  19. from email.mime.text import MIMEText
  20. from twisted.internet import defer
  21. from synapse.api.errors import StoreError
  22. from synapse.logging.context import make_deferred_yieldable
  23. from synapse.metrics.background_process_metrics import run_as_background_process
  24. from synapse.types import UserID
  25. from synapse.util import stringutils
  26. try:
  27. from synapse.push.mailer import load_jinja2_templates
  28. except ImportError:
  29. load_jinja2_templates = None
  30. logger = logging.getLogger(__name__)
  31. class AccountValidityHandler(object):
  32. def __init__(self, hs):
  33. self.hs = hs
  34. self.store = self.hs.get_datastore()
  35. self.sendmail = self.hs.get_sendmail()
  36. self.clock = self.hs.get_clock()
  37. self._account_validity = self.hs.config.account_validity
  38. if self._account_validity.renew_by_email_enabled and load_jinja2_templates:
  39. # Don't do email-specific configuration if renewal by email is disabled.
  40. try:
  41. app_name = self.hs.config.email_app_name
  42. self._subject = self._account_validity.renew_email_subject % {
  43. "app": app_name
  44. }
  45. self._from_string = self.hs.config.email_notif_from % {"app": app_name}
  46. except Exception:
  47. # If substitution failed, fall back to the bare strings.
  48. self._subject = self._account_validity.renew_email_subject
  49. self._from_string = self.hs.config.email_notif_from
  50. self._raw_from = email.utils.parseaddr(self._from_string)[1]
  51. self._template_html, self._template_text = load_jinja2_templates(
  52. config=self.hs.config,
  53. template_html_name=self.hs.config.email_expiry_template_html,
  54. template_text_name=self.hs.config.email_expiry_template_text,
  55. )
  56. # Check the renewal emails to send and send them every 30min.
  57. def send_emails():
  58. # run as a background process to make sure that the database transactions
  59. # have a logcontext to report to
  60. return run_as_background_process(
  61. "send_renewals", self.send_renewal_emails
  62. )
  63. self.clock.looping_call(send_emails, 30 * 60 * 1000)
  64. @defer.inlineCallbacks
  65. def send_renewal_emails(self):
  66. """Gets the list of users whose account is expiring in the amount of time
  67. configured in the ``renew_at`` parameter from the ``account_validity``
  68. configuration, and sends renewal emails to all of these users as long as they
  69. have an email 3PID attached to their account.
  70. """
  71. expiring_users = yield self.store.get_users_expiring_soon()
  72. if expiring_users:
  73. for user in expiring_users:
  74. yield self._send_renewal_email(
  75. user_id=user["user_id"], expiration_ts=user["expiration_ts_ms"]
  76. )
  77. @defer.inlineCallbacks
  78. def send_renewal_email_to_user(self, user_id):
  79. expiration_ts = yield self.store.get_expiration_ts_for_user(user_id)
  80. yield self._send_renewal_email(user_id, expiration_ts)
  81. @defer.inlineCallbacks
  82. def _send_renewal_email(self, user_id, expiration_ts):
  83. """Sends out a renewal email to every email address attached to the given user
  84. with a unique link allowing them to renew their account.
  85. Args:
  86. user_id (str): ID of the user to send email(s) to.
  87. expiration_ts (int): Timestamp in milliseconds for the expiration date of
  88. this user's account (used in the email templates).
  89. """
  90. addresses = yield self._get_email_addresses_for_user(user_id)
  91. # Stop right here if the user doesn't have at least one email address.
  92. # In this case, they will have to ask their server admin to renew their
  93. # account manually.
  94. # We don't need to do a specific check to make sure the account isn't
  95. # deactivated, as a deactivated account isn't supposed to have any
  96. # email address attached to it.
  97. if not addresses:
  98. return
  99. try:
  100. user_display_name = yield self.store.get_profile_displayname(
  101. UserID.from_string(user_id).localpart
  102. )
  103. if user_display_name is None:
  104. user_display_name = user_id
  105. except StoreError:
  106. user_display_name = user_id
  107. renewal_token = yield self._get_renewal_token(user_id)
  108. url = "%s_matrix/client/unstable/account_validity/renew?token=%s" % (
  109. self.hs.config.public_baseurl,
  110. renewal_token,
  111. )
  112. template_vars = {
  113. "display_name": user_display_name,
  114. "expiration_ts": expiration_ts,
  115. "url": url,
  116. }
  117. html_text = self._template_html.render(**template_vars)
  118. html_part = MIMEText(html_text, "html", "utf8")
  119. plain_text = self._template_text.render(**template_vars)
  120. text_part = MIMEText(plain_text, "plain", "utf8")
  121. for address in addresses:
  122. raw_to = email.utils.parseaddr(address)[1]
  123. multipart_msg = MIMEMultipart("alternative")
  124. multipart_msg["Subject"] = self._subject
  125. multipart_msg["From"] = self._from_string
  126. multipart_msg["To"] = address
  127. multipart_msg["Date"] = email.utils.formatdate()
  128. multipart_msg["Message-ID"] = email.utils.make_msgid()
  129. multipart_msg.attach(text_part)
  130. multipart_msg.attach(html_part)
  131. logger.info("Sending renewal email to %s", address)
  132. yield make_deferred_yieldable(
  133. self.sendmail(
  134. self.hs.config.email_smtp_host,
  135. self._raw_from,
  136. raw_to,
  137. multipart_msg.as_string().encode("utf8"),
  138. reactor=self.hs.get_reactor(),
  139. port=self.hs.config.email_smtp_port,
  140. requireAuthentication=self.hs.config.email_smtp_user is not None,
  141. username=self.hs.config.email_smtp_user,
  142. password=self.hs.config.email_smtp_pass,
  143. requireTransportSecurity=self.hs.config.require_transport_security,
  144. )
  145. )
  146. yield self.store.set_renewal_mail_status(user_id=user_id, email_sent=True)
  147. @defer.inlineCallbacks
  148. def _get_email_addresses_for_user(self, user_id):
  149. """Retrieve the list of email addresses attached to a user's account.
  150. Args:
  151. user_id (str): ID of the user to lookup email addresses for.
  152. Returns:
  153. defer.Deferred[list[str]]: Email addresses for this account.
  154. """
  155. threepids = yield self.store.user_get_threepids(user_id)
  156. addresses = []
  157. for threepid in threepids:
  158. if threepid["medium"] == "email":
  159. addresses.append(threepid["address"])
  160. return addresses
  161. @defer.inlineCallbacks
  162. def _get_renewal_token(self, user_id):
  163. """Generates a 32-byte long random string that will be inserted into the
  164. user's renewal email's unique link, then saves it into the database.
  165. Args:
  166. user_id (str): ID of the user to generate a string for.
  167. Returns:
  168. defer.Deferred[str]: The generated string.
  169. Raises:
  170. StoreError(500): Couldn't generate a unique string after 5 attempts.
  171. """
  172. attempts = 0
  173. while attempts < 5:
  174. try:
  175. renewal_token = stringutils.random_string(32)
  176. yield self.store.set_renewal_token_for_user(user_id, renewal_token)
  177. return renewal_token
  178. except StoreError:
  179. attempts += 1
  180. raise StoreError(500, "Couldn't generate a unique string as refresh string.")
  181. @defer.inlineCallbacks
  182. def renew_account(self, renewal_token):
  183. """Renews the account attached to a given renewal token by pushing back the
  184. expiration date by the current validity period in the server's configuration.
  185. Args:
  186. renewal_token (str): Token sent with the renewal request.
  187. """
  188. user_id = yield self.store.get_user_from_renewal_token(renewal_token)
  189. logger.debug("Renewing an account for user %s", user_id)
  190. yield self.renew_account_for_user(user_id)
  191. @defer.inlineCallbacks
  192. def renew_account_for_user(self, user_id, expiration_ts=None, email_sent=False):
  193. """Renews the account attached to a given user by pushing back the
  194. expiration date by the current validity period in the server's
  195. configuration.
  196. Args:
  197. renewal_token (str): Token sent with the renewal request.
  198. expiration_ts (int): New expiration date. Defaults to now + validity period.
  199. email_sent (bool): Whether an email has been sent for this validity period.
  200. Defaults to False.
  201. Returns:
  202. defer.Deferred[int]: New expiration date for this account, as a timestamp
  203. in milliseconds since epoch.
  204. """
  205. if expiration_ts is None:
  206. expiration_ts = self.clock.time_msec() + self._account_validity.period
  207. yield self.store.set_account_validity_for_user(
  208. user_id=user_id, expiration_ts=expiration_ts, email_sent=email_sent
  209. )
  210. return expiration_ts