bisheng.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import httpx
  2. from app.config.config import settings
  3. from app.utils.rsa_crypto import BishengCrypto
  4. class BishengService:
  5. def __init__(self, base_url: str):
  6. self.base_url = base_url
  7. async def register(self, username: str, password: str):
  8. public_key = await self.get_public_key_api()
  9. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  10. async with httpx.AsyncClient() as client:
  11. response = await client.post(
  12. f"{self.base_url}/api/v1/user/regist",
  13. json={"user_name": username, "password": password},
  14. headers={'Content-Type': 'application/json'}
  15. )
  16. if response.status_code != 200 and response.status_code != 201:
  17. raise Exception(f"Bisheng registration failed: {response.text}")
  18. async def login(self, username: str, password: str) -> str:
  19. public_key = await self.get_public_key_api()
  20. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  21. async with httpx.AsyncClient() as client:
  22. response = await client.post(
  23. f"{self.base_url}/api/v1/user/login",
  24. json={"user_name": username, "password": password},
  25. headers={'Content-Type': 'application/json'}
  26. )
  27. if response.status_code != 200 and response.status_code != 201:
  28. raise Exception(f"Bisheng login failed: {response.text}")
  29. return response.json().get('data', {}).get('access_token')
  30. async def get_public_key_api(self) -> dict:
  31. async with httpx.AsyncClient() as client:
  32. response = await client.get(
  33. f"{self.base_url}/api/v1/user/public_key",
  34. headers={'Content-Type': 'application/json'}
  35. )
  36. if response.status_code != 200:
  37. raise Exception(f"Failed to get public key: {response.text}")
  38. return response.json().get('data', {}).get('public_key')