registration.py 19 KB

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