registration.py 18 KB

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