registration.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import re
  16. from six.moves import range
  17. from twisted.internet import defer
  18. from synapse.api.constants import UserTypes
  19. from synapse.api.errors import Codes, StoreError
  20. from synapse.storage import background_updates
  21. from synapse.storage._base import SQLBaseStore
  22. from synapse.types import UserID
  23. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  24. class RegistrationWorkerStore(SQLBaseStore):
  25. def __init__(self, db_conn, hs):
  26. super(RegistrationWorkerStore, self).__init__(db_conn, hs)
  27. self.config = hs.config
  28. @cached()
  29. def get_user_by_id(self, user_id):
  30. return self._simple_select_one(
  31. table="users",
  32. keyvalues={
  33. "name": user_id,
  34. },
  35. retcols=[
  36. "name", "password_hash", "is_guest",
  37. "consent_version", "consent_server_notice_sent",
  38. "appservice_id", "creation_ts",
  39. ],
  40. allow_none=True,
  41. desc="get_user_by_id",
  42. )
  43. @defer.inlineCallbacks
  44. def is_trial_user(self, user_id):
  45. """Checks if user is in the "trial" period, i.e. within the first
  46. N days of registration defined by `mau_trial_days` config
  47. Args:
  48. user_id (str)
  49. Returns:
  50. Deferred[bool]
  51. """
  52. info = yield self.get_user_by_id(user_id)
  53. if not info:
  54. defer.returnValue(False)
  55. now = self.clock.time_msec()
  56. trial_duration_ms = self.config.mau_trial_days * 24 * 60 * 60 * 1000
  57. is_trial = (now - info["creation_ts"] * 1000) < trial_duration_ms
  58. defer.returnValue(is_trial)
  59. @cached()
  60. def get_user_by_access_token(self, token):
  61. """Get a user from the given access token.
  62. Args:
  63. token (str): The access token of a user.
  64. Returns:
  65. defer.Deferred: None, if the token did not match, otherwise dict
  66. including the keys `name`, `is_guest`, `device_id`, `token_id`.
  67. """
  68. return self.runInteraction(
  69. "get_user_by_access_token",
  70. self._query_for_auth,
  71. token
  72. )
  73. @defer.inlineCallbacks
  74. def is_server_admin(self, user):
  75. res = yield self._simple_select_one_onecol(
  76. table="users",
  77. keyvalues={"name": user.to_string()},
  78. retcol="admin",
  79. allow_none=True,
  80. desc="is_server_admin",
  81. )
  82. defer.returnValue(res if res else False)
  83. def _query_for_auth(self, txn, token):
  84. sql = (
  85. "SELECT users.name, users.is_guest, access_tokens.id as token_id,"
  86. " access_tokens.device_id"
  87. " FROM users"
  88. " INNER JOIN access_tokens on users.name = access_tokens.user_id"
  89. " WHERE token = ?"
  90. )
  91. txn.execute(sql, (token,))
  92. rows = self.cursor_to_dict(txn)
  93. if rows:
  94. return rows[0]
  95. return None
  96. class RegistrationStore(RegistrationWorkerStore,
  97. background_updates.BackgroundUpdateStore):
  98. def __init__(self, db_conn, hs):
  99. super(RegistrationStore, self).__init__(db_conn, hs)
  100. self.clock = hs.get_clock()
  101. self.register_background_index_update(
  102. "access_tokens_device_index",
  103. index_name="access_tokens_device_id",
  104. table="access_tokens",
  105. columns=["user_id", "device_id"],
  106. )
  107. self.register_background_index_update(
  108. "users_creation_ts",
  109. index_name="users_creation_ts",
  110. table="users",
  111. columns=["creation_ts"],
  112. )
  113. # we no longer use refresh tokens, but it's possible that some people
  114. # might have a background update queued to build this index. Just
  115. # clear the background update.
  116. self.register_noop_background_update("refresh_tokens_device_index")
  117. @defer.inlineCallbacks
  118. def add_access_token_to_user(self, user_id, token, device_id=None):
  119. """Adds an access token for the given user.
  120. Args:
  121. user_id (str): The user ID.
  122. token (str): The new access token to add.
  123. device_id (str): ID of the device to associate with the access
  124. token
  125. Raises:
  126. StoreError if there was a problem adding this.
  127. """
  128. next_id = self._access_tokens_id_gen.get_next()
  129. yield self._simple_insert(
  130. "access_tokens",
  131. {
  132. "id": next_id,
  133. "user_id": user_id,
  134. "token": token,
  135. "device_id": device_id,
  136. },
  137. desc="add_access_token_to_user",
  138. )
  139. def register(self, user_id, token=None, password_hash=None,
  140. was_guest=False, make_guest=False, appservice_id=None,
  141. create_profile_with_displayname=None, admin=False, user_type=None):
  142. """Attempts to register an account.
  143. Args:
  144. user_id (str): The desired user ID to register.
  145. token (str): The desired access token to use for this user. If this
  146. is not None, the given access token is associated with the user
  147. id.
  148. password_hash (str): Optional. The password hash for this user.
  149. was_guest (bool): Optional. Whether this is a guest account being
  150. upgraded to a non-guest account.
  151. make_guest (boolean): True if the the new user should be guest,
  152. false to add a regular user account.
  153. appservice_id (str): The ID of the appservice registering the user.
  154. create_profile_with_displayname (unicode): Optionally create a profile for
  155. the user, setting their displayname to the given value
  156. admin (boolean): is an admin user?
  157. user_type (str|None): type of user. One of the values from
  158. api.constants.UserTypes, or None for a normal user.
  159. Raises:
  160. StoreError if the user_id could not be registered.
  161. """
  162. return self.runInteraction(
  163. "register",
  164. self._register,
  165. user_id,
  166. token,
  167. password_hash,
  168. was_guest,
  169. make_guest,
  170. appservice_id,
  171. create_profile_with_displayname,
  172. admin,
  173. user_type
  174. )
  175. def _register(
  176. self,
  177. txn,
  178. user_id,
  179. token,
  180. password_hash,
  181. was_guest,
  182. make_guest,
  183. appservice_id,
  184. create_profile_with_displayname,
  185. admin,
  186. user_type,
  187. ):
  188. user_id_obj = UserID.from_string(user_id)
  189. now = int(self.clock.time())
  190. next_id = self._access_tokens_id_gen.get_next()
  191. try:
  192. if was_guest:
  193. # Ensure that the guest user actually exists
  194. # ``allow_none=False`` makes this raise an exception
  195. # if the row isn't in the database.
  196. self._simple_select_one_txn(
  197. txn,
  198. "users",
  199. keyvalues={
  200. "name": user_id,
  201. "is_guest": 1,
  202. },
  203. retcols=("name",),
  204. allow_none=False,
  205. )
  206. self._simple_update_one_txn(
  207. txn,
  208. "users",
  209. keyvalues={
  210. "name": user_id,
  211. "is_guest": 1,
  212. },
  213. updatevalues={
  214. "password_hash": password_hash,
  215. "upgrade_ts": now,
  216. "is_guest": 1 if make_guest else 0,
  217. "appservice_id": appservice_id,
  218. "admin": 1 if admin else 0,
  219. "user_type": user_type,
  220. }
  221. )
  222. else:
  223. self._simple_insert_txn(
  224. txn,
  225. "users",
  226. values={
  227. "name": user_id,
  228. "password_hash": password_hash,
  229. "creation_ts": now,
  230. "is_guest": 1 if make_guest else 0,
  231. "appservice_id": appservice_id,
  232. "admin": 1 if admin else 0,
  233. "user_type": user_type,
  234. }
  235. )
  236. except self.database_engine.module.IntegrityError:
  237. raise StoreError(
  238. 400, "User ID already taken.", errcode=Codes.USER_IN_USE
  239. )
  240. if token:
  241. # it's possible for this to get a conflict, but only for a single user
  242. # since tokens are namespaced based on their user ID
  243. txn.execute(
  244. "INSERT INTO access_tokens(id, user_id, token)"
  245. " VALUES (?,?,?)",
  246. (next_id, user_id, token,)
  247. )
  248. if create_profile_with_displayname:
  249. # set a default displayname serverside to avoid ugly race
  250. # between auto-joins and clients trying to set displaynames
  251. #
  252. # *obviously* the 'profiles' table uses localpart for user_id
  253. # while everything else uses the full mxid.
  254. txn.execute(
  255. "INSERT INTO profiles(user_id, displayname) VALUES (?,?)",
  256. (user_id_obj.localpart, create_profile_with_displayname)
  257. )
  258. self._invalidate_cache_and_stream(
  259. txn, self.get_user_by_id, (user_id,)
  260. )
  261. txn.call_after(self.is_guest.invalidate, (user_id,))
  262. def get_users_by_id_case_insensitive(self, user_id):
  263. """Gets users that match user_id case insensitively.
  264. Returns a mapping of user_id -> password_hash.
  265. """
  266. def f(txn):
  267. sql = (
  268. "SELECT name, password_hash FROM users"
  269. " WHERE lower(name) = lower(?)"
  270. )
  271. txn.execute(sql, (user_id,))
  272. return dict(txn)
  273. return self.runInteraction("get_users_by_id_case_insensitive", f)
  274. def user_set_password_hash(self, user_id, password_hash):
  275. """
  276. NB. This does *not* evict any cache because the one use for this
  277. removes most of the entries subsequently anyway so it would be
  278. pointless. Use flush_user separately.
  279. """
  280. def user_set_password_hash_txn(txn):
  281. self._simple_update_one_txn(
  282. txn,
  283. 'users', {
  284. 'name': user_id
  285. },
  286. {
  287. 'password_hash': password_hash
  288. }
  289. )
  290. self._invalidate_cache_and_stream(
  291. txn, self.get_user_by_id, (user_id,)
  292. )
  293. return self.runInteraction(
  294. "user_set_password_hash", user_set_password_hash_txn
  295. )
  296. def user_set_consent_version(self, user_id, consent_version):
  297. """Updates the user table to record privacy policy consent
  298. Args:
  299. user_id (str): full mxid of the user to update
  300. consent_version (str): version of the policy the user has consented
  301. to
  302. Raises:
  303. StoreError(404) if user not found
  304. """
  305. def f(txn):
  306. self._simple_update_one_txn(
  307. txn,
  308. table='users',
  309. keyvalues={'name': user_id, },
  310. updatevalues={'consent_version': consent_version, },
  311. )
  312. self._invalidate_cache_and_stream(
  313. txn, self.get_user_by_id, (user_id,)
  314. )
  315. return self.runInteraction("user_set_consent_version", f)
  316. def user_set_consent_server_notice_sent(self, user_id, consent_version):
  317. """Updates the user table to record that we have sent the user a server
  318. notice about privacy policy consent
  319. Args:
  320. user_id (str): full mxid of the user to update
  321. consent_version (str): version of the policy we have notified the
  322. user about
  323. Raises:
  324. StoreError(404) if user not found
  325. """
  326. def f(txn):
  327. self._simple_update_one_txn(
  328. txn,
  329. table='users',
  330. keyvalues={'name': user_id, },
  331. updatevalues={'consent_server_notice_sent': consent_version, },
  332. )
  333. self._invalidate_cache_and_stream(
  334. txn, self.get_user_by_id, (user_id,)
  335. )
  336. return self.runInteraction("user_set_consent_server_notice_sent", f)
  337. def user_delete_access_tokens(self, user_id, except_token_id=None,
  338. device_id=None):
  339. """
  340. Invalidate access tokens belonging to a user
  341. Args:
  342. user_id (str): ID of user the tokens belong to
  343. except_token_id (str): list of access_tokens IDs which should
  344. *not* be deleted
  345. device_id (str|None): ID of device the tokens are associated with.
  346. If None, tokens associated with any device (or no device) will
  347. be deleted
  348. Returns:
  349. defer.Deferred[list[str, int, str|None, int]]: a list of
  350. (token, token id, device id) for each of the deleted tokens
  351. """
  352. def f(txn):
  353. keyvalues = {
  354. "user_id": user_id,
  355. }
  356. if device_id is not None:
  357. keyvalues["device_id"] = device_id
  358. items = keyvalues.items()
  359. where_clause = " AND ".join(k + " = ?" for k, _ in items)
  360. values = [v for _, v in items]
  361. if except_token_id:
  362. where_clause += " AND id != ?"
  363. values.append(except_token_id)
  364. txn.execute(
  365. "SELECT token, id, device_id FROM access_tokens WHERE %s" % where_clause,
  366. values
  367. )
  368. tokens_and_devices = [(r[0], r[1], r[2]) for r in txn]
  369. for token, _, _ in tokens_and_devices:
  370. self._invalidate_cache_and_stream(
  371. txn, self.get_user_by_access_token, (token,)
  372. )
  373. txn.execute(
  374. "DELETE FROM access_tokens WHERE %s" % where_clause,
  375. values
  376. )
  377. return tokens_and_devices
  378. return self.runInteraction(
  379. "user_delete_access_tokens", f,
  380. )
  381. def delete_access_token(self, access_token):
  382. def f(txn):
  383. self._simple_delete_one_txn(
  384. txn,
  385. table="access_tokens",
  386. keyvalues={
  387. "token": access_token
  388. },
  389. )
  390. self._invalidate_cache_and_stream(
  391. txn, self.get_user_by_access_token, (access_token,)
  392. )
  393. return self.runInteraction("delete_access_token", f)
  394. @cachedInlineCallbacks()
  395. def is_guest(self, user_id):
  396. res = yield self._simple_select_one_onecol(
  397. table="users",
  398. keyvalues={"name": user_id},
  399. retcol="is_guest",
  400. allow_none=True,
  401. desc="is_guest",
  402. )
  403. defer.returnValue(res if res else False)
  404. @cachedInlineCallbacks()
  405. def is_support_user(self, user_id):
  406. """Determines if the user is of type UserTypes.SUPPORT
  407. Args:
  408. user_id (str): user id to test
  409. Returns:
  410. Deferred[bool]: True if user is of type UserTypes.SUPPORT
  411. """
  412. res = yield self.runInteraction(
  413. "is_support_user", self.is_support_user_txn, user_id
  414. )
  415. defer.returnValue(res)
  416. def is_support_user_txn(self, txn, user_id):
  417. res = self._simple_select_one_onecol_txn(
  418. txn=txn,
  419. table="users",
  420. keyvalues={"name": user_id},
  421. retcol="user_type",
  422. allow_none=True,
  423. )
  424. return True if res == UserTypes.SUPPORT else False
  425. @defer.inlineCallbacks
  426. def user_add_threepid(self, user_id, medium, address, validated_at, added_at):
  427. yield self._simple_upsert("user_threepids", {
  428. "medium": medium,
  429. "address": address,
  430. }, {
  431. "user_id": user_id,
  432. "validated_at": validated_at,
  433. "added_at": added_at,
  434. })
  435. @defer.inlineCallbacks
  436. def user_get_threepids(self, user_id):
  437. ret = yield self._simple_select_list(
  438. "user_threepids", {
  439. "user_id": user_id
  440. },
  441. ['medium', 'address', 'validated_at', 'added_at'],
  442. 'user_get_threepids'
  443. )
  444. defer.returnValue(ret)
  445. @defer.inlineCallbacks
  446. def get_user_id_by_threepid(self, medium, address):
  447. """Returns user id from threepid
  448. Args:
  449. medium (str): threepid medium e.g. email
  450. address (str): threepid address e.g. me@example.com
  451. Returns:
  452. Deferred[str|None]: user id or None if no user id/threepid mapping exists
  453. """
  454. user_id = yield self.runInteraction(
  455. "get_user_id_by_threepid", self.get_user_id_by_threepid_txn,
  456. medium, address
  457. )
  458. defer.returnValue(user_id)
  459. def get_user_id_by_threepid_txn(self, txn, medium, address):
  460. """Returns user id from threepid
  461. Args:
  462. txn (cursor):
  463. medium (str): threepid medium e.g. email
  464. address (str): threepid address e.g. me@example.com
  465. Returns:
  466. str|None: user id or None if no user id/threepid mapping exists
  467. """
  468. ret = self._simple_select_one_txn(
  469. txn,
  470. "user_threepids",
  471. {
  472. "medium": medium,
  473. "address": address
  474. },
  475. ['user_id'], True
  476. )
  477. if ret:
  478. return ret['user_id']
  479. return None
  480. def user_delete_threepid(self, user_id, medium, address):
  481. return self._simple_delete(
  482. "user_threepids",
  483. keyvalues={
  484. "user_id": user_id,
  485. "medium": medium,
  486. "address": address,
  487. },
  488. desc="user_delete_threepids",
  489. )
  490. @defer.inlineCallbacks
  491. def count_all_users(self):
  492. """Counts all users registered on the homeserver."""
  493. def _count_users(txn):
  494. txn.execute("SELECT COUNT(*) AS users FROM users")
  495. rows = self.cursor_to_dict(txn)
  496. if rows:
  497. return rows[0]["users"]
  498. return 0
  499. ret = yield self.runInteraction("count_users", _count_users)
  500. defer.returnValue(ret)
  501. def count_daily_user_type(self):
  502. """
  503. Counts 1) native non guest users
  504. 2) native guests users
  505. 3) bridged users
  506. who registered on the homeserver in the past 24 hours
  507. """
  508. def _count_daily_user_type(txn):
  509. yesterday = int(self._clock.time()) - (60 * 60 * 24)
  510. sql = """
  511. SELECT user_type, COALESCE(count(*), 0) AS count FROM (
  512. SELECT
  513. CASE
  514. WHEN is_guest=0 AND appservice_id IS NULL THEN 'native'
  515. WHEN is_guest=1 AND appservice_id IS NULL THEN 'guest'
  516. WHEN is_guest=0 AND appservice_id IS NOT NULL THEN 'bridged'
  517. END AS user_type
  518. FROM users
  519. WHERE creation_ts > ?
  520. ) AS t GROUP BY user_type
  521. """
  522. results = {'native': 0, 'guest': 0, 'bridged': 0}
  523. txn.execute(sql, (yesterday,))
  524. for row in txn:
  525. results[row[0]] = row[1]
  526. return results
  527. return self.runInteraction("count_daily_user_type", _count_daily_user_type)
  528. @defer.inlineCallbacks
  529. def count_nonbridged_users(self):
  530. def _count_users(txn):
  531. txn.execute("""
  532. SELECT COALESCE(COUNT(*), 0) FROM users
  533. WHERE appservice_id IS NULL
  534. """)
  535. count, = txn.fetchone()
  536. return count
  537. ret = yield self.runInteraction("count_users", _count_users)
  538. defer.returnValue(ret)
  539. @defer.inlineCallbacks
  540. def find_next_generated_user_id_localpart(self):
  541. """
  542. Gets the localpart of the next generated user ID.
  543. Generated user IDs are integers, and we aim for them to be as small as
  544. we can. Unfortunately, it's possible some of them are already taken by
  545. existing users, and there may be gaps in the already taken range. This
  546. function returns the start of the first allocatable gap. This is to
  547. avoid the case of ID 10000000 being pre-allocated, so us wasting the
  548. first (and shortest) many generated user IDs.
  549. """
  550. def _find_next_generated_user_id(txn):
  551. txn.execute("SELECT name FROM users")
  552. regex = re.compile(r"^@(\d+):")
  553. found = set()
  554. for user_id, in txn:
  555. match = regex.search(user_id)
  556. if match:
  557. found.add(int(match.group(1)))
  558. for i in range(len(found) + 1):
  559. if i not in found:
  560. return i
  561. defer.returnValue((yield self.runInteraction(
  562. "find_next_generated_user_id",
  563. _find_next_generated_user_id
  564. )))
  565. @defer.inlineCallbacks
  566. def get_3pid_guest_access_token(self, medium, address):
  567. ret = yield self._simple_select_one(
  568. "threepid_guest_access_tokens",
  569. {
  570. "medium": medium,
  571. "address": address
  572. },
  573. ["guest_access_token"], True, 'get_3pid_guest_access_token'
  574. )
  575. if ret:
  576. defer.returnValue(ret["guest_access_token"])
  577. defer.returnValue(None)
  578. @defer.inlineCallbacks
  579. def save_or_get_3pid_guest_access_token(
  580. self, medium, address, access_token, inviter_user_id
  581. ):
  582. """
  583. Gets the 3pid's guest access token if exists, else saves access_token.
  584. Args:
  585. medium (str): Medium of the 3pid. Must be "email".
  586. address (str): 3pid address.
  587. access_token (str): The access token to persist if none is
  588. already persisted.
  589. inviter_user_id (str): User ID of the inviter.
  590. Returns:
  591. deferred str: Whichever access token is persisted at the end
  592. of this function call.
  593. """
  594. def insert(txn):
  595. txn.execute(
  596. "INSERT INTO threepid_guest_access_tokens "
  597. "(medium, address, guest_access_token, first_inviter) "
  598. "VALUES (?, ?, ?, ?)",
  599. (medium, address, access_token, inviter_user_id)
  600. )
  601. try:
  602. yield self.runInteraction("save_3pid_guest_access_token", insert)
  603. defer.returnValue(access_token)
  604. except self.database_engine.module.IntegrityError:
  605. ret = yield self.get_3pid_guest_access_token(medium, address)
  606. defer.returnValue(ret)
  607. def add_user_pending_deactivation(self, user_id):
  608. """
  609. Adds a user to the table of users who need to be parted from all the rooms they're
  610. in
  611. """
  612. return self._simple_insert(
  613. "users_pending_deactivation",
  614. values={
  615. "user_id": user_id,
  616. },
  617. desc="add_user_pending_deactivation",
  618. )
  619. def del_user_pending_deactivation(self, user_id):
  620. """
  621. Removes the given user to the table of users who need to be parted from all the
  622. rooms they're in, effectively marking that user as fully deactivated.
  623. """
  624. # XXX: This should be simple_delete_one but we failed to put a unique index on
  625. # the table, so somehow duplicate entries have ended up in it.
  626. return self._simple_delete(
  627. "users_pending_deactivation",
  628. keyvalues={
  629. "user_id": user_id,
  630. },
  631. desc="del_user_pending_deactivation",
  632. )
  633. def get_user_pending_deactivation(self):
  634. """
  635. Gets one user from the table of users waiting to be parted from all the rooms
  636. they're in.
  637. """
  638. return self._simple_select_one_onecol(
  639. "users_pending_deactivation",
  640. keyvalues={},
  641. retcol="user_id",
  642. allow_none=True,
  643. desc="get_users_pending_deactivation",
  644. )