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