registration.py 55 KB

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