registration.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import re
  19. from six import iterkeys
  20. from twisted.internet import defer
  21. from twisted.internet.defer import Deferred
  22. from synapse.api.constants import UserTypes
  23. from synapse.api.errors import Codes, StoreError, SynapseError, ThreepidValidationError
  24. from synapse.metrics.background_process_metrics import run_as_background_process
  25. from synapse.storage._base import SQLBaseStore
  26. from synapse.storage.database import Database
  27. from synapse.types import UserID
  28. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  29. THIRTY_MINUTES_IN_MS = 30 * 60 * 1000
  30. logger = logging.getLogger(__name__)
  31. class RegistrationWorkerStore(SQLBaseStore):
  32. def __init__(self, database: Database, db_conn, hs):
  33. super(RegistrationWorkerStore, self).__init__(database, db_conn, hs)
  34. self.config = hs.config
  35. self.clock = hs.get_clock()
  36. @cached()
  37. def get_user_by_id(self, user_id):
  38. return self.db.simple_select_one(
  39. table="users",
  40. keyvalues={"name": user_id},
  41. retcols=[
  42. "name",
  43. "password_hash",
  44. "is_guest",
  45. "admin",
  46. "consent_version",
  47. "consent_server_notice_sent",
  48. "appservice_id",
  49. "creation_ts",
  50. "user_type",
  51. "deactivated",
  52. ],
  53. allow_none=True,
  54. desc="get_user_by_id",
  55. )
  56. @defer.inlineCallbacks
  57. def is_trial_user(self, user_id):
  58. """Checks if user is in the "trial" period, i.e. within the first
  59. N days of registration defined by `mau_trial_days` config
  60. Args:
  61. user_id (str)
  62. Returns:
  63. Deferred[bool]
  64. """
  65. info = yield self.get_user_by_id(user_id)
  66. if not info:
  67. return False
  68. now = self.clock.time_msec()
  69. trial_duration_ms = self.config.mau_trial_days * 24 * 60 * 60 * 1000
  70. is_trial = (now - info["creation_ts"] * 1000) < trial_duration_ms
  71. return is_trial
  72. @cached()
  73. def get_user_by_access_token(self, token):
  74. """Get a user from the given access token.
  75. Args:
  76. token (str): The access token of a user.
  77. Returns:
  78. defer.Deferred: None, if the token did not match, otherwise dict
  79. including the keys `name`, `is_guest`, `device_id`, `token_id`,
  80. `valid_until_ms`.
  81. """
  82. return self.db.runInteraction(
  83. "get_user_by_access_token", self._query_for_auth, token
  84. )
  85. @cachedInlineCallbacks()
  86. def get_expiration_ts_for_user(self, user_id):
  87. """Get the expiration timestamp for the account bearing a given user ID.
  88. Args:
  89. user_id (str): The ID of the user.
  90. Returns:
  91. defer.Deferred: None, if the account has no expiration timestamp,
  92. otherwise int representation of the timestamp (as a number of
  93. milliseconds since epoch).
  94. """
  95. res = yield self.db.simple_select_one_onecol(
  96. table="account_validity",
  97. keyvalues={"user_id": user_id},
  98. retcol="expiration_ts_ms",
  99. allow_none=True,
  100. desc="get_expiration_ts_for_user",
  101. )
  102. return res
  103. @defer.inlineCallbacks
  104. def set_account_validity_for_user(
  105. self, user_id, expiration_ts, email_sent, renewal_token=None
  106. ):
  107. """Updates the account validity properties of the given account, with the
  108. given values.
  109. Args:
  110. user_id (str): ID of the account to update properties for.
  111. expiration_ts (int): New expiration date, as a timestamp in milliseconds
  112. since epoch.
  113. email_sent (bool): True means a renewal email has been sent for this
  114. account and there's no need to send another one for the current validity
  115. period.
  116. renewal_token (str): Renewal token the user can use to extend the validity
  117. of their account. Defaults to no token.
  118. """
  119. def set_account_validity_for_user_txn(txn):
  120. self.db.simple_update_txn(
  121. txn=txn,
  122. table="account_validity",
  123. keyvalues={"user_id": user_id},
  124. updatevalues={
  125. "expiration_ts_ms": expiration_ts,
  126. "email_sent": email_sent,
  127. "renewal_token": renewal_token,
  128. },
  129. )
  130. self._invalidate_cache_and_stream(
  131. txn, self.get_expiration_ts_for_user, (user_id,)
  132. )
  133. yield self.db.runInteraction(
  134. "set_account_validity_for_user", set_account_validity_for_user_txn
  135. )
  136. @defer.inlineCallbacks
  137. def set_renewal_token_for_user(self, user_id, renewal_token):
  138. """Defines a renewal token for a given user.
  139. Args:
  140. user_id (str): ID of the user to set the renewal token for.
  141. renewal_token (str): Random unique string that will be used to renew the
  142. user's account.
  143. Raises:
  144. StoreError: The provided token is already set for another user.
  145. """
  146. yield self.db.simple_update_one(
  147. table="account_validity",
  148. keyvalues={"user_id": user_id},
  149. updatevalues={"renewal_token": renewal_token},
  150. desc="set_renewal_token_for_user",
  151. )
  152. @defer.inlineCallbacks
  153. def get_user_from_renewal_token(self, renewal_token):
  154. """Get a user ID from a renewal token.
  155. Args:
  156. renewal_token (str): The renewal token to perform the lookup with.
  157. Returns:
  158. defer.Deferred[str]: The ID of the user to which the token belongs.
  159. """
  160. res = yield self.db.simple_select_one_onecol(
  161. table="account_validity",
  162. keyvalues={"renewal_token": renewal_token},
  163. retcol="user_id",
  164. desc="get_user_from_renewal_token",
  165. )
  166. return res
  167. @defer.inlineCallbacks
  168. def get_renewal_token_for_user(self, user_id):
  169. """Get the renewal token associated with a given user ID.
  170. Args:
  171. user_id (str): The user ID to lookup a token for.
  172. Returns:
  173. defer.Deferred[str]: The renewal token associated with this user ID.
  174. """
  175. res = yield self.db.simple_select_one_onecol(
  176. table="account_validity",
  177. keyvalues={"user_id": user_id},
  178. retcol="renewal_token",
  179. desc="get_renewal_token_for_user",
  180. )
  181. return res
  182. @defer.inlineCallbacks
  183. def get_users_expiring_soon(self):
  184. """Selects users whose account will expire in the [now, now + renew_at] time
  185. window (see configuration for account_validity for information on what renew_at
  186. refers to).
  187. Returns:
  188. Deferred: Resolves to a list[dict[user_id (str), expiration_ts_ms (int)]]
  189. """
  190. def select_users_txn(txn, now_ms, renew_at):
  191. sql = (
  192. "SELECT user_id, expiration_ts_ms FROM account_validity"
  193. " WHERE email_sent = ? AND (expiration_ts_ms - ?) <= ?"
  194. )
  195. values = [False, now_ms, renew_at]
  196. txn.execute(sql, values)
  197. return self.db.cursor_to_dict(txn)
  198. res = yield self.db.runInteraction(
  199. "get_users_expiring_soon",
  200. select_users_txn,
  201. self.clock.time_msec(),
  202. self.config.account_validity.renew_at,
  203. )
  204. return res
  205. @defer.inlineCallbacks
  206. def set_renewal_mail_status(self, user_id, email_sent):
  207. """Sets or unsets the flag that indicates whether a renewal email has been sent
  208. to the user (and the user hasn't renewed their account yet).
  209. Args:
  210. user_id (str): ID of the user to set/unset the flag for.
  211. email_sent (bool): Flag which indicates whether a renewal email has been sent
  212. to this user.
  213. """
  214. yield self.db.simple_update_one(
  215. table="account_validity",
  216. keyvalues={"user_id": user_id},
  217. updatevalues={"email_sent": email_sent},
  218. desc="set_renewal_mail_status",
  219. )
  220. @defer.inlineCallbacks
  221. def delete_account_validity_for_user(self, user_id):
  222. """Deletes the entry for the given user in the account validity table, removing
  223. their expiration date and renewal token.
  224. Args:
  225. user_id (str): ID of the user to remove from the account validity table.
  226. """
  227. yield self.db.simple_delete_one(
  228. table="account_validity",
  229. keyvalues={"user_id": user_id},
  230. desc="delete_account_validity_for_user",
  231. )
  232. @defer.inlineCallbacks
  233. def is_server_admin(self, user):
  234. """Determines if a user is an admin of this homeserver.
  235. Args:
  236. user (UserID): user ID of the user to test
  237. Returns (bool):
  238. true iff the user is a server admin, false otherwise.
  239. """
  240. res = yield self.db.simple_select_one_onecol(
  241. table="users",
  242. keyvalues={"name": user.to_string()},
  243. retcol="admin",
  244. allow_none=True,
  245. desc="is_server_admin",
  246. )
  247. return bool(res) if res else False
  248. def set_server_admin(self, user, admin):
  249. """Sets whether a user is an admin of this homeserver.
  250. Args:
  251. user (UserID): user ID of the user to test
  252. admin (bool): true iff the user is to be a server admin,
  253. false otherwise.
  254. """
  255. return self.db.simple_update_one(
  256. table="users",
  257. keyvalues={"name": user.to_string()},
  258. updatevalues={"admin": 1 if admin else 0},
  259. desc="set_server_admin",
  260. )
  261. def _query_for_auth(self, txn, token):
  262. sql = (
  263. "SELECT users.name, users.is_guest, access_tokens.id as token_id,"
  264. " access_tokens.device_id, access_tokens.valid_until_ms"
  265. " FROM users"
  266. " INNER JOIN access_tokens on users.name = access_tokens.user_id"
  267. " WHERE token = ?"
  268. )
  269. txn.execute(sql, (token,))
  270. rows = self.db.cursor_to_dict(txn)
  271. if rows:
  272. return rows[0]
  273. return None
  274. @cachedInlineCallbacks()
  275. def is_real_user(self, user_id):
  276. """Determines if the user is a real user, ie does not have a 'user_type'.
  277. Args:
  278. user_id (str): user id to test
  279. Returns:
  280. Deferred[bool]: True if user 'user_type' is null or empty string
  281. """
  282. res = yield self.db.runInteraction(
  283. "is_real_user", self.is_real_user_txn, user_id
  284. )
  285. return res
  286. @cachedInlineCallbacks()
  287. def is_support_user(self, user_id):
  288. """Determines if the user is of type UserTypes.SUPPORT
  289. Args:
  290. user_id (str): user id to test
  291. Returns:
  292. Deferred[bool]: True if user is of type UserTypes.SUPPORT
  293. """
  294. res = yield self.db.runInteraction(
  295. "is_support_user", self.is_support_user_txn, user_id
  296. )
  297. return res
  298. def is_real_user_txn(self, txn, user_id):
  299. res = self.db.simple_select_one_onecol_txn(
  300. txn=txn,
  301. table="users",
  302. keyvalues={"name": user_id},
  303. retcol="user_type",
  304. allow_none=True,
  305. )
  306. return res is None
  307. def is_support_user_txn(self, txn, user_id):
  308. res = self.db.simple_select_one_onecol_txn(
  309. txn=txn,
  310. table="users",
  311. keyvalues={"name": user_id},
  312. retcol="user_type",
  313. allow_none=True,
  314. )
  315. return True if res == UserTypes.SUPPORT else False
  316. def get_users_by_id_case_insensitive(self, user_id):
  317. """Gets users that match user_id case insensitively.
  318. Returns a mapping of user_id -> password_hash.
  319. """
  320. def f(txn):
  321. sql = "SELECT name, password_hash FROM users WHERE lower(name) = lower(?)"
  322. txn.execute(sql, (user_id,))
  323. return dict(txn)
  324. return self.db.runInteraction("get_users_by_id_case_insensitive", f)
  325. async def get_user_by_external_id(
  326. self, auth_provider: str, external_id: str
  327. ) -> str:
  328. """Look up a user by their external auth id
  329. Args:
  330. auth_provider: identifier for the remote auth provider
  331. external_id: id on that system
  332. Returns:
  333. str|None: the mxid of the user, or None if they are not known
  334. """
  335. return await self.db.simple_select_one_onecol(
  336. table="user_external_ids",
  337. keyvalues={"auth_provider": auth_provider, "external_id": external_id},
  338. retcol="user_id",
  339. allow_none=True,
  340. desc="get_user_by_external_id",
  341. )
  342. @defer.inlineCallbacks
  343. def count_all_users(self):
  344. """Counts all users registered on the homeserver."""
  345. def _count_users(txn):
  346. txn.execute("SELECT COUNT(*) AS users FROM users")
  347. rows = self.db.cursor_to_dict(txn)
  348. if rows:
  349. return rows[0]["users"]
  350. return 0
  351. ret = yield self.db.runInteraction("count_users", _count_users)
  352. return ret
  353. def count_daily_user_type(self):
  354. """
  355. Counts 1) native non guest users
  356. 2) native guests users
  357. 3) bridged users
  358. who registered on the homeserver in the past 24 hours
  359. """
  360. def _count_daily_user_type(txn):
  361. yesterday = int(self._clock.time()) - (60 * 60 * 24)
  362. sql = """
  363. SELECT user_type, COALESCE(count(*), 0) AS count FROM (
  364. SELECT
  365. CASE
  366. WHEN is_guest=0 AND appservice_id IS NULL THEN 'native'
  367. WHEN is_guest=1 AND appservice_id IS NULL THEN 'guest'
  368. WHEN is_guest=0 AND appservice_id IS NOT NULL THEN 'bridged'
  369. END AS user_type
  370. FROM users
  371. WHERE creation_ts > ?
  372. ) AS t GROUP BY user_type
  373. """
  374. results = {"native": 0, "guest": 0, "bridged": 0}
  375. txn.execute(sql, (yesterday,))
  376. for row in txn:
  377. results[row[0]] = row[1]
  378. return results
  379. return self.db.runInteraction("count_daily_user_type", _count_daily_user_type)
  380. @defer.inlineCallbacks
  381. def count_nonbridged_users(self):
  382. def _count_users(txn):
  383. txn.execute(
  384. """
  385. SELECT COALESCE(COUNT(*), 0) FROM users
  386. WHERE appservice_id IS NULL
  387. """
  388. )
  389. (count,) = txn.fetchone()
  390. return count
  391. ret = yield self.db.runInteraction("count_users", _count_users)
  392. return ret
  393. @defer.inlineCallbacks
  394. def count_real_users(self):
  395. """Counts all users without a special user_type registered on the homeserver."""
  396. def _count_users(txn):
  397. txn.execute("SELECT COUNT(*) AS users FROM users where user_type is null")
  398. rows = self.db.cursor_to_dict(txn)
  399. if rows:
  400. return rows[0]["users"]
  401. return 0
  402. ret = yield self.db.runInteraction("count_real_users", _count_users)
  403. return ret
  404. @defer.inlineCallbacks
  405. def find_next_generated_user_id_localpart(self):
  406. """
  407. Gets the localpart of the next generated user ID.
  408. Generated user IDs are integers, so we find the largest integer user ID
  409. already taken and return that plus one.
  410. """
  411. def _find_next_generated_user_id(txn):
  412. # We bound between '@0' and '@a' to avoid pulling the entire table
  413. # out.
  414. txn.execute("SELECT name FROM users WHERE '@0' <= name AND name < '@a'")
  415. regex = re.compile(r"^@(\d+):")
  416. max_found = 0
  417. for (user_id,) in txn:
  418. match = regex.search(user_id)
  419. if match:
  420. max_found = max(int(match.group(1)), max_found)
  421. return max_found + 1
  422. return (
  423. (
  424. yield self.db.runInteraction(
  425. "find_next_generated_user_id", _find_next_generated_user_id
  426. )
  427. )
  428. )
  429. @defer.inlineCallbacks
  430. def get_user_id_by_threepid(self, medium, address):
  431. """Returns user id from threepid
  432. Args:
  433. medium (str): threepid medium e.g. email
  434. address (str): threepid address e.g. me@example.com
  435. Returns:
  436. Deferred[str|None]: user id or None if no user id/threepid mapping exists
  437. """
  438. user_id = yield self.db.runInteraction(
  439. "get_user_id_by_threepid", self.get_user_id_by_threepid_txn, medium, address
  440. )
  441. return user_id
  442. def get_user_id_by_threepid_txn(self, txn, medium, address):
  443. """Returns user id from threepid
  444. Args:
  445. txn (cursor):
  446. medium (str): threepid medium e.g. email
  447. address (str): threepid address e.g. me@example.com
  448. Returns:
  449. str|None: user id or None if no user id/threepid mapping exists
  450. """
  451. ret = self.db.simple_select_one_txn(
  452. txn,
  453. "user_threepids",
  454. {"medium": medium, "address": address},
  455. ["user_id"],
  456. True,
  457. )
  458. if ret:
  459. return ret["user_id"]
  460. return None
  461. @defer.inlineCallbacks
  462. def user_add_threepid(self, user_id, medium, address, validated_at, added_at):
  463. yield self.db.simple_upsert(
  464. "user_threepids",
  465. {"medium": medium, "address": address},
  466. {"user_id": user_id, "validated_at": validated_at, "added_at": added_at},
  467. )
  468. @defer.inlineCallbacks
  469. def user_get_threepids(self, user_id):
  470. ret = yield self.db.simple_select_list(
  471. "user_threepids",
  472. {"user_id": user_id},
  473. ["medium", "address", "validated_at", "added_at"],
  474. "user_get_threepids",
  475. )
  476. return ret
  477. def user_delete_threepid(self, user_id, medium, address):
  478. return self.db.simple_delete(
  479. "user_threepids",
  480. keyvalues={"user_id": user_id, "medium": medium, "address": address},
  481. desc="user_delete_threepid",
  482. )
  483. def user_delete_threepids(self, user_id: str):
  484. """Delete all threepid this user has bound
  485. Args:
  486. user_id: The user id to delete all threepids of
  487. """
  488. return self.db.simple_delete(
  489. "user_threepids",
  490. keyvalues={"user_id": user_id},
  491. desc="user_delete_threepids",
  492. )
  493. def add_user_bound_threepid(self, user_id, medium, address, id_server):
  494. """The server proxied a bind request to the given identity server on
  495. behalf of the given user. We need to remember this in case the user
  496. asks us to unbind the threepid.
  497. Args:
  498. user_id (str)
  499. medium (str)
  500. address (str)
  501. id_server (str)
  502. Returns:
  503. Deferred
  504. """
  505. # We need to use an upsert, in case they user had already bound the
  506. # threepid
  507. return self.db.simple_upsert(
  508. table="user_threepid_id_server",
  509. keyvalues={
  510. "user_id": user_id,
  511. "medium": medium,
  512. "address": address,
  513. "id_server": id_server,
  514. },
  515. values={},
  516. insertion_values={},
  517. desc="add_user_bound_threepid",
  518. )
  519. def user_get_bound_threepids(self, user_id):
  520. """Get the threepids that a user has bound to an identity server through the homeserver
  521. The homeserver remembers where binds to an identity server occurred. Using this
  522. method can retrieve those threepids.
  523. Args:
  524. user_id (str): The ID of the user to retrieve threepids for
  525. Returns:
  526. Deferred[list[dict]]: List of dictionaries containing the following:
  527. medium (str): The medium of the threepid (e.g "email")
  528. address (str): The address of the threepid (e.g "bob@example.com")
  529. """
  530. return self.db.simple_select_list(
  531. table="user_threepid_id_server",
  532. keyvalues={"user_id": user_id},
  533. retcols=["medium", "address"],
  534. desc="user_get_bound_threepids",
  535. )
  536. def remove_user_bound_threepid(self, user_id, medium, address, id_server):
  537. """The server proxied an unbind request to the given identity server on
  538. behalf of the given user, so we remove the mapping of threepid to
  539. identity server.
  540. Args:
  541. user_id (str)
  542. medium (str)
  543. address (str)
  544. id_server (str)
  545. Returns:
  546. Deferred
  547. """
  548. return self.db.simple_delete(
  549. table="user_threepid_id_server",
  550. keyvalues={
  551. "user_id": user_id,
  552. "medium": medium,
  553. "address": address,
  554. "id_server": id_server,
  555. },
  556. desc="remove_user_bound_threepid",
  557. )
  558. def get_id_servers_user_bound(self, user_id, medium, address):
  559. """Get the list of identity servers that the server proxied bind
  560. requests to for given user and threepid
  561. Args:
  562. user_id (str)
  563. medium (str)
  564. address (str)
  565. Returns:
  566. Deferred[list[str]]: Resolves to a list of identity servers
  567. """
  568. return self.db.simple_select_onecol(
  569. table="user_threepid_id_server",
  570. keyvalues={"user_id": user_id, "medium": medium, "address": address},
  571. retcol="id_server",
  572. desc="get_id_servers_user_bound",
  573. )
  574. @cachedInlineCallbacks()
  575. def get_user_deactivated_status(self, user_id):
  576. """Retrieve the value for the `deactivated` property for the provided user.
  577. Args:
  578. user_id (str): The ID of the user to retrieve the status for.
  579. Returns:
  580. defer.Deferred(bool): The requested value.
  581. """
  582. res = yield self.db.simple_select_one_onecol(
  583. table="users",
  584. keyvalues={"name": user_id},
  585. retcol="deactivated",
  586. desc="get_user_deactivated_status",
  587. )
  588. # Convert the integer into a boolean.
  589. return res == 1
  590. def get_threepid_validation_session(
  591. self, medium, client_secret, address=None, sid=None, validated=True
  592. ):
  593. """Gets a session_id and last_send_attempt (if available) for a
  594. combination of validation metadata
  595. Args:
  596. medium (str|None): The medium of the 3PID
  597. address (str|None): The address of the 3PID
  598. sid (str|None): The ID of the validation session
  599. client_secret (str): A unique string provided by the client to help identify this
  600. validation attempt
  601. validated (bool|None): Whether sessions should be filtered by
  602. whether they have been validated already or not. None to
  603. perform no filtering
  604. Returns:
  605. Deferred[dict|None]: A dict containing the following:
  606. * address - address of the 3pid
  607. * medium - medium of the 3pid
  608. * client_secret - a secret provided by the client for this validation session
  609. * session_id - ID of the validation session
  610. * send_attempt - a number serving to dedupe send attempts for this session
  611. * validated_at - timestamp of when this session was validated if so
  612. Otherwise None if a validation session is not found
  613. """
  614. if not client_secret:
  615. raise SynapseError(
  616. 400, "Missing parameter: client_secret", errcode=Codes.MISSING_PARAM
  617. )
  618. keyvalues = {"client_secret": client_secret}
  619. if medium:
  620. keyvalues["medium"] = medium
  621. if address:
  622. keyvalues["address"] = address
  623. if sid:
  624. keyvalues["session_id"] = sid
  625. assert address or sid
  626. def get_threepid_validation_session_txn(txn):
  627. sql = """
  628. SELECT address, session_id, medium, client_secret,
  629. last_send_attempt, validated_at
  630. FROM threepid_validation_session WHERE %s
  631. """ % (
  632. " AND ".join("%s = ?" % k for k in iterkeys(keyvalues)),
  633. )
  634. if validated is not None:
  635. sql += " AND validated_at IS " + ("NOT NULL" if validated else "NULL")
  636. sql += " LIMIT 1"
  637. txn.execute(sql, list(keyvalues.values()))
  638. rows = self.db.cursor_to_dict(txn)
  639. if not rows:
  640. return None
  641. return rows[0]
  642. return self.db.runInteraction(
  643. "get_threepid_validation_session", get_threepid_validation_session_txn
  644. )
  645. def delete_threepid_session(self, session_id):
  646. """Removes a threepid validation session from the database. This can
  647. be done after validation has been performed and whatever action was
  648. waiting on it has been carried out
  649. Args:
  650. session_id (str): The ID of the session to delete
  651. """
  652. def delete_threepid_session_txn(txn):
  653. self.db.simple_delete_txn(
  654. txn,
  655. table="threepid_validation_token",
  656. keyvalues={"session_id": session_id},
  657. )
  658. self.db.simple_delete_txn(
  659. txn,
  660. table="threepid_validation_session",
  661. keyvalues={"session_id": session_id},
  662. )
  663. return self.db.runInteraction(
  664. "delete_threepid_session", delete_threepid_session_txn
  665. )
  666. class RegistrationBackgroundUpdateStore(RegistrationWorkerStore):
  667. def __init__(self, database: Database, db_conn, hs):
  668. super(RegistrationBackgroundUpdateStore, self).__init__(database, db_conn, hs)
  669. self.clock = hs.get_clock()
  670. self.config = hs.config
  671. self.db.updates.register_background_index_update(
  672. "access_tokens_device_index",
  673. index_name="access_tokens_device_id",
  674. table="access_tokens",
  675. columns=["user_id", "device_id"],
  676. )
  677. self.db.updates.register_background_index_update(
  678. "users_creation_ts",
  679. index_name="users_creation_ts",
  680. table="users",
  681. columns=["creation_ts"],
  682. )
  683. # we no longer use refresh tokens, but it's possible that some people
  684. # might have a background update queued to build this index. Just
  685. # clear the background update.
  686. self.db.updates.register_noop_background_update("refresh_tokens_device_index")
  687. self.db.updates.register_background_update_handler(
  688. "user_threepids_grandfather", self._bg_user_threepids_grandfather
  689. )
  690. self.db.updates.register_background_update_handler(
  691. "users_set_deactivated_flag", self._background_update_set_deactivated_flag
  692. )
  693. @defer.inlineCallbacks
  694. def _background_update_set_deactivated_flag(self, progress, batch_size):
  695. """Retrieves a list of all deactivated users and sets the 'deactivated' flag to 1
  696. for each of them.
  697. """
  698. last_user = progress.get("user_id", "")
  699. def _background_update_set_deactivated_flag_txn(txn):
  700. txn.execute(
  701. """
  702. SELECT
  703. users.name,
  704. COUNT(access_tokens.token) AS count_tokens,
  705. COUNT(user_threepids.address) AS count_threepids
  706. FROM users
  707. LEFT JOIN access_tokens ON (access_tokens.user_id = users.name)
  708. LEFT JOIN user_threepids ON (user_threepids.user_id = users.name)
  709. WHERE (users.password_hash IS NULL OR users.password_hash = '')
  710. AND (users.appservice_id IS NULL OR users.appservice_id = '')
  711. AND users.is_guest = 0
  712. AND users.name > ?
  713. GROUP BY users.name
  714. ORDER BY users.name ASC
  715. LIMIT ?;
  716. """,
  717. (last_user, batch_size),
  718. )
  719. rows = self.db.cursor_to_dict(txn)
  720. if not rows:
  721. return True, 0
  722. rows_processed_nb = 0
  723. for user in rows:
  724. if not user["count_tokens"] and not user["count_threepids"]:
  725. self.set_user_deactivated_status_txn(txn, user["name"], True)
  726. rows_processed_nb += 1
  727. logger.info("Marked %d rows as deactivated", rows_processed_nb)
  728. self.db.updates._background_update_progress_txn(
  729. txn, "users_set_deactivated_flag", {"user_id": rows[-1]["name"]}
  730. )
  731. if batch_size > len(rows):
  732. return True, len(rows)
  733. else:
  734. return False, len(rows)
  735. end, nb_processed = yield self.db.runInteraction(
  736. "users_set_deactivated_flag", _background_update_set_deactivated_flag_txn
  737. )
  738. if end:
  739. yield self.db.updates._end_background_update("users_set_deactivated_flag")
  740. return nb_processed
  741. @defer.inlineCallbacks
  742. def _bg_user_threepids_grandfather(self, progress, batch_size):
  743. """We now track which identity servers a user binds their 3PID to, so
  744. we need to handle the case of existing bindings where we didn't track
  745. this.
  746. We do this by grandfathering in existing user threepids assuming that
  747. they used one of the server configured trusted identity servers.
  748. """
  749. id_servers = set(self.config.trusted_third_party_id_servers)
  750. def _bg_user_threepids_grandfather_txn(txn):
  751. sql = """
  752. INSERT INTO user_threepid_id_server
  753. (user_id, medium, address, id_server)
  754. SELECT user_id, medium, address, ?
  755. FROM user_threepids
  756. """
  757. txn.executemany(sql, [(id_server,) for id_server in id_servers])
  758. if id_servers:
  759. yield self.db.runInteraction(
  760. "_bg_user_threepids_grandfather", _bg_user_threepids_grandfather_txn
  761. )
  762. yield self.db.updates._end_background_update("user_threepids_grandfather")
  763. return 1
  764. class RegistrationStore(RegistrationBackgroundUpdateStore):
  765. def __init__(self, database: Database, db_conn, hs):
  766. super(RegistrationStore, self).__init__(database, db_conn, hs)
  767. self._account_validity = hs.config.account_validity
  768. if self._account_validity.enabled:
  769. self._clock.call_later(
  770. 0.0,
  771. run_as_background_process,
  772. "account_validity_set_expiration_dates",
  773. self._set_expiration_date_when_missing,
  774. )
  775. # Create a background job for culling expired 3PID validity tokens
  776. def start_cull():
  777. # run as a background process to make sure that the database transactions
  778. # have a logcontext to report to
  779. return run_as_background_process(
  780. "cull_expired_threepid_validation_tokens",
  781. self.cull_expired_threepid_validation_tokens,
  782. )
  783. hs.get_clock().looping_call(start_cull, THIRTY_MINUTES_IN_MS)
  784. @defer.inlineCallbacks
  785. def add_access_token_to_user(self, user_id, token, device_id, valid_until_ms):
  786. """Adds an access token for the given user.
  787. Args:
  788. user_id (str): The user ID.
  789. token (str): The new access token to add.
  790. device_id (str): ID of the device to associate with the access
  791. token
  792. valid_until_ms (int|None): when the token is valid until. None for
  793. no expiry.
  794. Raises:
  795. StoreError if there was a problem adding this.
  796. """
  797. next_id = self._access_tokens_id_gen.get_next()
  798. yield self.db.simple_insert(
  799. "access_tokens",
  800. {
  801. "id": next_id,
  802. "user_id": user_id,
  803. "token": token,
  804. "device_id": device_id,
  805. "valid_until_ms": valid_until_ms,
  806. },
  807. desc="add_access_token_to_user",
  808. )
  809. def register_user(
  810. self,
  811. user_id,
  812. password_hash=None,
  813. was_guest=False,
  814. make_guest=False,
  815. appservice_id=None,
  816. create_profile_with_displayname=None,
  817. admin=False,
  818. user_type=None,
  819. ):
  820. """Attempts to register an account.
  821. Args:
  822. user_id (str): The desired user ID to register.
  823. password_hash (str): Optional. The password hash for this user.
  824. was_guest (bool): Optional. Whether this is a guest account being
  825. upgraded to a non-guest account.
  826. make_guest (boolean): True if the the new user should be guest,
  827. false to add a regular user account.
  828. appservice_id (str): The ID of the appservice registering the user.
  829. create_profile_with_displayname (unicode): Optionally create a profile for
  830. the user, setting their displayname to the given value
  831. admin (boolean): is an admin user?
  832. user_type (str|None): type of user. One of the values from
  833. api.constants.UserTypes, or None for a normal user.
  834. Raises:
  835. StoreError if the user_id could not be registered.
  836. """
  837. return self.db.runInteraction(
  838. "register_user",
  839. self._register_user,
  840. user_id,
  841. password_hash,
  842. was_guest,
  843. make_guest,
  844. appservice_id,
  845. create_profile_with_displayname,
  846. admin,
  847. user_type,
  848. )
  849. def _register_user(
  850. self,
  851. txn,
  852. user_id,
  853. password_hash,
  854. was_guest,
  855. make_guest,
  856. appservice_id,
  857. create_profile_with_displayname,
  858. admin,
  859. user_type,
  860. ):
  861. user_id_obj = UserID.from_string(user_id)
  862. now = int(self.clock.time())
  863. try:
  864. if was_guest:
  865. # Ensure that the guest user actually exists
  866. # ``allow_none=False`` makes this raise an exception
  867. # if the row isn't in the database.
  868. self.db.simple_select_one_txn(
  869. txn,
  870. "users",
  871. keyvalues={"name": user_id, "is_guest": 1},
  872. retcols=("name",),
  873. allow_none=False,
  874. )
  875. self.db.simple_update_one_txn(
  876. txn,
  877. "users",
  878. keyvalues={"name": user_id, "is_guest": 1},
  879. updatevalues={
  880. "password_hash": password_hash,
  881. "upgrade_ts": now,
  882. "is_guest": 1 if make_guest else 0,
  883. "appservice_id": appservice_id,
  884. "admin": 1 if admin else 0,
  885. "user_type": user_type,
  886. },
  887. )
  888. else:
  889. self.db.simple_insert_txn(
  890. txn,
  891. "users",
  892. values={
  893. "name": user_id,
  894. "password_hash": password_hash,
  895. "creation_ts": now,
  896. "is_guest": 1 if make_guest else 0,
  897. "appservice_id": appservice_id,
  898. "admin": 1 if admin else 0,
  899. "user_type": user_type,
  900. },
  901. )
  902. except self.database_engine.module.IntegrityError:
  903. raise StoreError(400, "User ID already taken.", errcode=Codes.USER_IN_USE)
  904. if self._account_validity.enabled:
  905. self.set_expiration_date_for_user_txn(txn, user_id)
  906. if create_profile_with_displayname:
  907. # set a default displayname serverside to avoid ugly race
  908. # between auto-joins and clients trying to set displaynames
  909. #
  910. # *obviously* the 'profiles' table uses localpart for user_id
  911. # while everything else uses the full mxid.
  912. txn.execute(
  913. "INSERT INTO profiles(user_id, displayname) VALUES (?,?)",
  914. (user_id_obj.localpart, create_profile_with_displayname),
  915. )
  916. if self.hs.config.stats_enabled:
  917. # we create a new completed user statistics row
  918. # we don't strictly need current_token since this user really can't
  919. # have any state deltas before now (as it is a new user), but still,
  920. # we include it for completeness.
  921. current_token = self._get_max_stream_id_in_current_state_deltas_txn(txn)
  922. self._update_stats_delta_txn(
  923. txn, now, "user", user_id, {}, complete_with_stream_id=current_token
  924. )
  925. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  926. txn.call_after(self.is_guest.invalidate, (user_id,))
  927. def record_user_external_id(
  928. self, auth_provider: str, external_id: str, user_id: str
  929. ) -> Deferred:
  930. """Record a mapping from an external user id to a mxid
  931. Args:
  932. auth_provider: identifier for the remote auth provider
  933. external_id: id on that system
  934. user_id: complete mxid that it is mapped to
  935. """
  936. return self.db.simple_insert(
  937. table="user_external_ids",
  938. values={
  939. "auth_provider": auth_provider,
  940. "external_id": external_id,
  941. "user_id": user_id,
  942. },
  943. desc="record_user_external_id",
  944. )
  945. def user_set_password_hash(self, user_id, password_hash):
  946. """
  947. NB. This does *not* evict any cache because the one use for this
  948. removes most of the entries subsequently anyway so it would be
  949. pointless. Use flush_user separately.
  950. """
  951. def user_set_password_hash_txn(txn):
  952. self.db.simple_update_one_txn(
  953. txn, "users", {"name": user_id}, {"password_hash": password_hash}
  954. )
  955. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  956. return self.db.runInteraction(
  957. "user_set_password_hash", user_set_password_hash_txn
  958. )
  959. def user_set_consent_version(self, user_id, consent_version):
  960. """Updates the user table to record privacy policy consent
  961. Args:
  962. user_id (str): full mxid of the user to update
  963. consent_version (str): version of the policy the user has consented
  964. to
  965. Raises:
  966. StoreError(404) if user not found
  967. """
  968. def f(txn):
  969. self.db.simple_update_one_txn(
  970. txn,
  971. table="users",
  972. keyvalues={"name": user_id},
  973. updatevalues={"consent_version": consent_version},
  974. )
  975. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  976. return self.db.runInteraction("user_set_consent_version", f)
  977. def user_set_consent_server_notice_sent(self, user_id, consent_version):
  978. """Updates the user table to record that we have sent the user a server
  979. notice about privacy policy consent
  980. Args:
  981. user_id (str): full mxid of the user to update
  982. consent_version (str): version of the policy we have notified the
  983. user about
  984. Raises:
  985. StoreError(404) if user not found
  986. """
  987. def f(txn):
  988. self.db.simple_update_one_txn(
  989. txn,
  990. table="users",
  991. keyvalues={"name": user_id},
  992. updatevalues={"consent_server_notice_sent": consent_version},
  993. )
  994. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  995. return self.db.runInteraction("user_set_consent_server_notice_sent", f)
  996. def user_delete_access_tokens(self, user_id, except_token_id=None, device_id=None):
  997. """
  998. Invalidate access tokens belonging to a user
  999. Args:
  1000. user_id (str): ID of user the tokens belong to
  1001. except_token_id (str): list of access_tokens IDs which should
  1002. *not* be deleted
  1003. device_id (str|None): ID of device the tokens are associated with.
  1004. If None, tokens associated with any device (or no device) will
  1005. be deleted
  1006. Returns:
  1007. defer.Deferred[list[str, int, str|None, int]]: a list of
  1008. (token, token id, device id) for each of the deleted tokens
  1009. """
  1010. def f(txn):
  1011. keyvalues = {"user_id": user_id}
  1012. if device_id is not None:
  1013. keyvalues["device_id"] = device_id
  1014. items = keyvalues.items()
  1015. where_clause = " AND ".join(k + " = ?" for k, _ in items)
  1016. values = [v for _, v in items]
  1017. if except_token_id:
  1018. where_clause += " AND id != ?"
  1019. values.append(except_token_id)
  1020. txn.execute(
  1021. "SELECT token, id, device_id FROM access_tokens WHERE %s"
  1022. % where_clause,
  1023. values,
  1024. )
  1025. tokens_and_devices = [(r[0], r[1], r[2]) for r in txn]
  1026. for token, _, _ in tokens_and_devices:
  1027. self._invalidate_cache_and_stream(
  1028. txn, self.get_user_by_access_token, (token,)
  1029. )
  1030. txn.execute("DELETE FROM access_tokens WHERE %s" % where_clause, values)
  1031. return tokens_and_devices
  1032. return self.db.runInteraction("user_delete_access_tokens", f)
  1033. def delete_access_token(self, access_token):
  1034. def f(txn):
  1035. self.db.simple_delete_one_txn(
  1036. txn, table="access_tokens", keyvalues={"token": access_token}
  1037. )
  1038. self._invalidate_cache_and_stream(
  1039. txn, self.get_user_by_access_token, (access_token,)
  1040. )
  1041. return self.db.runInteraction("delete_access_token", f)
  1042. @cachedInlineCallbacks()
  1043. def is_guest(self, user_id):
  1044. res = yield self.db.simple_select_one_onecol(
  1045. table="users",
  1046. keyvalues={"name": user_id},
  1047. retcol="is_guest",
  1048. allow_none=True,
  1049. desc="is_guest",
  1050. )
  1051. return res if res else False
  1052. def add_user_pending_deactivation(self, user_id):
  1053. """
  1054. Adds a user to the table of users who need to be parted from all the rooms they're
  1055. in
  1056. """
  1057. return self.db.simple_insert(
  1058. "users_pending_deactivation",
  1059. values={"user_id": user_id},
  1060. desc="add_user_pending_deactivation",
  1061. )
  1062. def del_user_pending_deactivation(self, user_id):
  1063. """
  1064. Removes the given user to the table of users who need to be parted from all the
  1065. rooms they're in, effectively marking that user as fully deactivated.
  1066. """
  1067. # XXX: This should be simple_delete_one but we failed to put a unique index on
  1068. # the table, so somehow duplicate entries have ended up in it.
  1069. return self.db.simple_delete(
  1070. "users_pending_deactivation",
  1071. keyvalues={"user_id": user_id},
  1072. desc="del_user_pending_deactivation",
  1073. )
  1074. def get_user_pending_deactivation(self):
  1075. """
  1076. Gets one user from the table of users waiting to be parted from all the rooms
  1077. they're in.
  1078. """
  1079. return self.db.simple_select_one_onecol(
  1080. "users_pending_deactivation",
  1081. keyvalues={},
  1082. retcol="user_id",
  1083. allow_none=True,
  1084. desc="get_users_pending_deactivation",
  1085. )
  1086. def validate_threepid_session(self, session_id, client_secret, token, current_ts):
  1087. """Attempt to validate a threepid session using a token
  1088. Args:
  1089. session_id (str): The id of a validation session
  1090. client_secret (str): A unique string provided by the client to
  1091. help identify this validation attempt
  1092. token (str): A validation token
  1093. current_ts (int): The current unix time in milliseconds. Used for
  1094. checking token expiry status
  1095. Raises:
  1096. ThreepidValidationError: if a matching validation token was not found or has
  1097. expired
  1098. Returns:
  1099. deferred str|None: A str representing a link to redirect the user
  1100. to if there is one.
  1101. """
  1102. # Insert everything into a transaction in order to run atomically
  1103. def validate_threepid_session_txn(txn):
  1104. row = self.db.simple_select_one_txn(
  1105. txn,
  1106. table="threepid_validation_session",
  1107. keyvalues={"session_id": session_id},
  1108. retcols=["client_secret", "validated_at"],
  1109. allow_none=True,
  1110. )
  1111. if not row:
  1112. raise ThreepidValidationError(400, "Unknown session_id")
  1113. retrieved_client_secret = row["client_secret"]
  1114. validated_at = row["validated_at"]
  1115. if retrieved_client_secret != client_secret:
  1116. raise ThreepidValidationError(
  1117. 400, "This client_secret does not match the provided session_id"
  1118. )
  1119. row = self.db.simple_select_one_txn(
  1120. txn,
  1121. table="threepid_validation_token",
  1122. keyvalues={"session_id": session_id, "token": token},
  1123. retcols=["expires", "next_link"],
  1124. allow_none=True,
  1125. )
  1126. if not row:
  1127. raise ThreepidValidationError(
  1128. 400, "Validation token not found or has expired"
  1129. )
  1130. expires = row["expires"]
  1131. next_link = row["next_link"]
  1132. # If the session is already validated, no need to revalidate
  1133. if validated_at:
  1134. return next_link
  1135. if expires <= current_ts:
  1136. raise ThreepidValidationError(
  1137. 400, "This token has expired. Please request a new one"
  1138. )
  1139. # Looks good. Validate the session
  1140. self.db.simple_update_txn(
  1141. txn,
  1142. table="threepid_validation_session",
  1143. keyvalues={"session_id": session_id},
  1144. updatevalues={"validated_at": self.clock.time_msec()},
  1145. )
  1146. return next_link
  1147. # Return next_link if it exists
  1148. return self.db.runInteraction(
  1149. "validate_threepid_session_txn", validate_threepid_session_txn
  1150. )
  1151. def upsert_threepid_validation_session(
  1152. self,
  1153. medium,
  1154. address,
  1155. client_secret,
  1156. send_attempt,
  1157. session_id,
  1158. validated_at=None,
  1159. ):
  1160. """Upsert a threepid validation session
  1161. Args:
  1162. medium (str): The medium of the 3PID
  1163. address (str): The address of the 3PID
  1164. client_secret (str): A unique string provided by the client to
  1165. help identify this validation attempt
  1166. send_attempt (int): The latest send_attempt on this session
  1167. session_id (str): The id of this validation session
  1168. validated_at (int|None): The unix timestamp in milliseconds of
  1169. when the session was marked as valid
  1170. """
  1171. insertion_values = {
  1172. "medium": medium,
  1173. "address": address,
  1174. "client_secret": client_secret,
  1175. }
  1176. if validated_at:
  1177. insertion_values["validated_at"] = validated_at
  1178. return self.db.simple_upsert(
  1179. table="threepid_validation_session",
  1180. keyvalues={"session_id": session_id},
  1181. values={"last_send_attempt": send_attempt},
  1182. insertion_values=insertion_values,
  1183. desc="upsert_threepid_validation_session",
  1184. )
  1185. def start_or_continue_validation_session(
  1186. self,
  1187. medium,
  1188. address,
  1189. session_id,
  1190. client_secret,
  1191. send_attempt,
  1192. next_link,
  1193. token,
  1194. token_expires,
  1195. ):
  1196. """Creates a new threepid validation session if it does not already
  1197. exist and associates a new validation token with it
  1198. Args:
  1199. medium (str): The medium of the 3PID
  1200. address (str): The address of the 3PID
  1201. session_id (str): The id of this validation session
  1202. client_secret (str): A unique string provided by the client to
  1203. help identify this validation attempt
  1204. send_attempt (int): The latest send_attempt on this session
  1205. next_link (str|None): The link to redirect the user to upon
  1206. successful validation
  1207. token (str): The validation token
  1208. token_expires (int): The timestamp for which after the token
  1209. will no longer be valid
  1210. """
  1211. def start_or_continue_validation_session_txn(txn):
  1212. # Create or update a validation session
  1213. self.db.simple_upsert_txn(
  1214. txn,
  1215. table="threepid_validation_session",
  1216. keyvalues={"session_id": session_id},
  1217. values={"last_send_attempt": send_attempt},
  1218. insertion_values={
  1219. "medium": medium,
  1220. "address": address,
  1221. "client_secret": client_secret,
  1222. },
  1223. )
  1224. # Create a new validation token with this session ID
  1225. self.db.simple_insert_txn(
  1226. txn,
  1227. table="threepid_validation_token",
  1228. values={
  1229. "session_id": session_id,
  1230. "token": token,
  1231. "next_link": next_link,
  1232. "expires": token_expires,
  1233. },
  1234. )
  1235. return self.db.runInteraction(
  1236. "start_or_continue_validation_session",
  1237. start_or_continue_validation_session_txn,
  1238. )
  1239. def cull_expired_threepid_validation_tokens(self):
  1240. """Remove threepid validation tokens with expiry dates that have passed"""
  1241. def cull_expired_threepid_validation_tokens_txn(txn, ts):
  1242. sql = """
  1243. DELETE FROM threepid_validation_token WHERE
  1244. expires < ?
  1245. """
  1246. return txn.execute(sql, (ts,))
  1247. return self.db.runInteraction(
  1248. "cull_expired_threepid_validation_tokens",
  1249. cull_expired_threepid_validation_tokens_txn,
  1250. self.clock.time_msec(),
  1251. )
  1252. @defer.inlineCallbacks
  1253. def set_user_deactivated_status(self, user_id, deactivated):
  1254. """Set the `deactivated` property for the provided user to the provided value.
  1255. Args:
  1256. user_id (str): The ID of the user to set the status for.
  1257. deactivated (bool): The value to set for `deactivated`.
  1258. """
  1259. yield self.db.runInteraction(
  1260. "set_user_deactivated_status",
  1261. self.set_user_deactivated_status_txn,
  1262. user_id,
  1263. deactivated,
  1264. )
  1265. def set_user_deactivated_status_txn(self, txn, user_id, deactivated):
  1266. self.db.simple_update_one_txn(
  1267. txn=txn,
  1268. table="users",
  1269. keyvalues={"name": user_id},
  1270. updatevalues={"deactivated": 1 if deactivated else 0},
  1271. )
  1272. self._invalidate_cache_and_stream(
  1273. txn, self.get_user_deactivated_status, (user_id,)
  1274. )
  1275. @defer.inlineCallbacks
  1276. def _set_expiration_date_when_missing(self):
  1277. """
  1278. Retrieves the list of registered users that don't have an expiration date, and
  1279. adds an expiration date for each of them.
  1280. """
  1281. def select_users_with_no_expiration_date_txn(txn):
  1282. """Retrieves the list of registered users with no expiration date from the
  1283. database, filtering out deactivated users.
  1284. """
  1285. sql = (
  1286. "SELECT users.name FROM users"
  1287. " LEFT JOIN account_validity ON (users.name = account_validity.user_id)"
  1288. " WHERE account_validity.user_id is NULL AND users.deactivated = 0;"
  1289. )
  1290. txn.execute(sql, [])
  1291. res = self.db.cursor_to_dict(txn)
  1292. if res:
  1293. for user in res:
  1294. self.set_expiration_date_for_user_txn(
  1295. txn, user["name"], use_delta=True
  1296. )
  1297. yield self.db.runInteraction(
  1298. "get_users_with_no_expiration_date",
  1299. select_users_with_no_expiration_date_txn,
  1300. )
  1301. def set_expiration_date_for_user_txn(self, txn, user_id, use_delta=False):
  1302. """Sets an expiration date to the account with the given user ID.
  1303. Args:
  1304. user_id (str): User ID to set an expiration date for.
  1305. use_delta (bool): If set to False, the expiration date for the user will be
  1306. now + validity period. If set to True, this expiration date will be a
  1307. random value in the [now + period - d ; now + period] range, d being a
  1308. delta equal to 10% of the validity period.
  1309. """
  1310. now_ms = self._clock.time_msec()
  1311. expiration_ts = now_ms + self._account_validity.period
  1312. if use_delta:
  1313. expiration_ts = self.rand.randrange(
  1314. expiration_ts - self._account_validity.startup_job_max_delta,
  1315. expiration_ts,
  1316. )
  1317. self.db.simple_upsert_txn(
  1318. txn,
  1319. "account_validity",
  1320. keyvalues={"user_id": user_id},
  1321. values={"expiration_ts_ms": expiration_ts, "email_sent": False},
  1322. )