user_oauth.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import datetime
  2. from typing import Optional
  3. import os
  4. import sys
  5. sys.path.append(os.path.dirname(os.path.dirname(__file__)))
  6. from db.engine import engine
  7. from sqlmodel import Field, SQLModel,create_engine,Session,select,func,Column,Relationship
  8. from config import DB_URL,logger
  9. # from db.common import engine
  10. from sqlalchemy import UniqueConstraint, Index, asc
  11. from sqlalchemy.dialects.postgresql import insert
  12. from db.base import DouyinBaseRepository
  13. from db.model import *
  14. # Database manager class
  15. class UserOAuthRepository(DouyinBaseRepository):
  16. def __init__(self, engine=engine):
  17. super().__init__(UserOAuthToken, engine)
  18. self.model:UserOAuthToken
  19. def dict_to_model(self, data: dict):
  20. access_token_expires_in = datetime.datetime.now() + datetime.timedelta(seconds=data.get("expires_in"))
  21. refresh_token_expires_in = datetime.datetime.now() + datetime.timedelta(seconds=data.get("refresh_expires_in"))
  22. model:UserOAuthToken = super().dict_to_model(data,self.model)
  23. model.expires_at = access_token_expires_in
  24. model.refresh_expires_at = refresh_token_expires_in
  25. return model
  26. # field = UserOAuthToken.expires_at | UserOAuthToken.refresh_expires_at
  27. def select_nearest_expire(self, field: Column) -> UserOAuthToken:
  28. with Session(bind=self.engine) as session:
  29. statement = select(self.model).where(field > datetime.datetime.now()).order_by(asc(field)).limit(1)
  30. res = session.exec(statement)
  31. return res.first()
  32. def update_refresh_token(self, open_id:str, refresh_token:str, refresh_expires_in:int):
  33. refresh_token_expires_at = datetime.datetime.now() + datetime.timedelta(seconds=refresh_expires_in)
  34. model = UserOAuthToken(open_id=open_id, refresh_expires_in=refresh_expires_in, refresh_token=refresh_token,refresh_expires_at=refresh_token_expires_at)
  35. return self.add_or_update(model)
  36. def update_access_token(self, open_id:str, access_token:str, expires_in:int):
  37. access_token_expires_at = datetime.datetime.now() + datetime.timedelta(seconds=expires_in)
  38. model = UserOAuthToken(open_id=open_id, access_token=access_token, expires_in=expires_in,expires_at=access_token_expires_at)
  39. return self.add_or_update(model)
  40. async def delete_token(self, token_id: int):
  41. async with self.session_factory() as session:
  42. statement = select(UserOAuthToken).where(UserOAuthToken.id == token_id)
  43. token = await session.execute(statement).scalars().first()
  44. if token:
  45. await session.delete(token)
  46. await session.commit()
  47. print(f"Record deleted: ID - {token_id}")
  48. else:
  49. print(f"Record with ID {token_id} not found")
  50. def test_add(open_id=None):
  51. SQLModel.metadata.create_all(engine)
  52. user_oauth = {'access_token': 'act.3.m3kiZmfxxIH95i1bHZ7Bq3Wkv_Xm5TtD3kpLGjtCr3G96WIINBKEvzlsaObrGcH4GaxTQeLZA13jkzoZhpAwPwMRqFxlVuIcxpge_-BpdFib1xHqkcFa4B-LX4zpd2YK3kDFTFfMcJXN_fZ2eByg6oqqa1OieUWcvlaVgw==', 'captcha': '', 'desc_url': '', 'description': '', 'error_code': 0, 'expires_in': 1296000, 'log_id': '202402171353461C33F969CEFB511B216F', 'open_id': '_000LiV_o0FGKMwaZgqGMCvcVSf-UAnNU_kk', 'refresh_expires_in': 2592000, 'refresh_token': 'rft.e4b3da8bd3ef01d880d827b11e826391OEGHiRrTLcp5zsGYP1dh6F9Bo7fg', 'scope': 'user_info,trial.whitelist'}
  53. user_oauth2 = {'access_token': 'act', 'expires_in': 19290, 'open_id': '55test2', 'refresh_expires_in': 1950, 'refresh_token': 'rft', 'scope': 'user_info,trial.whitelist'}
  54. user_info = {
  55. "avatar": "https://p26.douyinpic.com/aweme/100x100/aweme-avatar/tos-cn-i-0813_66c4e34ae8834399bbf967c3d3c919db.jpeg?from=4010531038",
  56. "avatar_larger": "https://p3.douyinpic.com/aweme/1080x1080/aweme-avatar/tos-cn-i-0813_66c4e34ae8834399bbf967c3d3c919db.jpeg?from=4010531038",
  57. "captcha": "",
  58. "city": "",
  59. "client_key": "55",
  60. "country": "",
  61. "desc_url": "",
  62. "description": "",
  63. "district": "",
  64. "e_account_role": "",
  65. "error_code": 0,
  66. "gender": 0,
  67. "log_id": "202401261424326FE877A6CAB03910C553",
  68. "nickname": "程序员马工",
  69. "open_id": "_000QadFMhmU1jNCI3JdPnyVDL6XavC70dFy",
  70. "province": "",
  71. "union_id": "123-01ae-59bd-978a-1de8566186a8"
  72. }
  73. if open_id:
  74. user_oauth["open_id"] = open_id
  75. user_info["open_id"] = open_id
  76. user_info["nickname"] = "user" + open_id[:5]
  77. else:
  78. open_id = user_oauth["open_id"]
  79. db_manager = UserOAuthRepository()
  80. res = db_manager.save_login_data(user_oauth2)
  81. res = db_manager.select_nearest_expire(UserOAuthToken.expires_at)
  82. logger.debug(res)
  83. # db_user_info = UserInfoRepository()
  84. # res = db_user_info.add_or_update(user_info)
  85. # logger.debug(db_manager.get_by_open_id(open_id))
  86. return user_oauth["open_id"]
  87. if __name__ == "__main__":
  88. test_add()