|
6 | 6 | @date:2025/6/6 19:55 |
7 | 7 | @desc: |
8 | 8 | """ |
| 9 | +import hashlib |
9 | 10 | import json |
| 11 | +import threading |
10 | 12 |
|
11 | | -from django.core import signing |
| 13 | +from django.core import signing, cache |
12 | 14 |
|
| 15 | +from common.constants.cache_version import Cache_Version |
13 | 16 | from common.utils.rsa_util import encrypt, decrypt |
14 | 17 |
|
| 18 | +authentication_cache = cache.cache |
| 19 | +lock = threading.Lock() |
| 20 | + |
| 21 | + |
| 22 | +def _decrypt(authentication: str): |
| 23 | + cache_key = hashlib.sha256(authentication.encode()).hexdigest() |
| 24 | + result = authentication_cache.get(key=cache_key, version=Cache_Version.CHAT.value) |
| 25 | + if result is None: |
| 26 | + with lock: |
| 27 | + result = authentication_cache.get(cache_key, version=Cache_Version.CHAT.value) |
| 28 | + if result is None: |
| 29 | + result = decrypt(authentication) |
| 30 | + authentication_cache.set(cache_key, result, version=Cache_Version.CHAT.value, timeout=60 * 60 * 2) |
| 31 | + |
| 32 | + return result |
| 33 | + |
15 | 34 |
|
16 | 35 | class ChatAuthentication: |
17 | | - def __init__(self, auth_type: str | None): |
| 36 | + def __init__(self, auth_type: str | None, **kwargs): |
18 | 37 | self.auth_type = auth_type |
| 38 | + for k, v in kwargs.items(): |
| 39 | + self.__setattr__(k, v) |
19 | 40 |
|
20 | 41 | def to_dict(self): |
21 | | - return {'auth_type': self.auth_type} |
| 42 | + return self.__dict__ |
22 | 43 |
|
23 | 44 | def to_string(self): |
24 | | - return encrypt(json.dumps(self.to_dict())) |
| 45 | + value = json.dumps(self.to_dict()) |
| 46 | + authentication = encrypt(value) |
| 47 | + cache_key = hashlib.sha256(authentication.encode()).hexdigest() |
| 48 | + authentication_cache.set(cache_key, value, version=Cache_Version.CHAT.value, timeout=60 * 60 * 2) |
| 49 | + return authentication |
25 | 50 |
|
26 | 51 | @staticmethod |
27 | 52 | def new_instance(authentication: str): |
28 | | - auth = json.loads(decrypt(authentication)) |
29 | | - return ChatAuthentication(auth.get('auth_type')) |
| 53 | + auth = json.loads(_decrypt(authentication)) |
| 54 | + return ChatAuthentication(**auth) |
30 | 55 |
|
31 | 56 |
|
32 | 57 | class ChatUserToken: |
|
0 commit comments