registration.py 22 KB

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