openid.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Optional
  15. from synapse.storage._base import SQLBaseStore
  16. from synapse.storage.database import LoggingTransaction
  17. class OpenIdStore(SQLBaseStore):
  18. async def insert_open_id_token(
  19. self, token: str, ts_valid_until_ms: int, user_id: str
  20. ) -> None:
  21. await self.db_pool.simple_insert(
  22. table="open_id_tokens",
  23. values={
  24. "token": token,
  25. "ts_valid_until_ms": ts_valid_until_ms,
  26. "user_id": user_id,
  27. },
  28. desc="insert_open_id_token",
  29. )
  30. async def get_user_id_for_open_id_token(
  31. self, token: str, ts_now_ms: int
  32. ) -> Optional[str]:
  33. def get_user_id_for_token_txn(txn: LoggingTransaction) -> Optional[str]:
  34. sql = (
  35. "SELECT user_id FROM open_id_tokens"
  36. " WHERE token = ? AND ? <= ts_valid_until_ms"
  37. )
  38. txn.execute(sql, (token, ts_now_ms))
  39. rows = txn.fetchall()
  40. if not rows:
  41. return None
  42. else:
  43. return rows[0][0]
  44. return await self.db_pool.runInteraction(
  45. "get_user_id_for_token", get_user_id_for_token_txn
  46. )