registration.py 18 KB

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