Skip to content

Commit 0199c31

Browse files
committed
perf: Parsing Tokens
1 parent d53b4dc commit 0199c31

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

apps/common/auth/common.py

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,52 @@
66
@date:2025/6/6 19:55
77
@desc:
88
"""
9+
import hashlib
910
import json
11+
import threading
1012

11-
from django.core import signing
13+
from django.core import signing, cache
1214

15+
from common.constants.cache_version import Cache_Version
1316
from common.utils.rsa_util import encrypt, decrypt
1417

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+
1534

1635
class ChatAuthentication:
17-
def __init__(self, auth_type: str | None):
36+
def __init__(self, auth_type: str | None, **kwargs):
1837
self.auth_type = auth_type
38+
for k, v in kwargs.items():
39+
self.__setattr__(k, v)
1940

2041
def to_dict(self):
21-
return {'auth_type': self.auth_type}
42+
return self.__dict__
2243

2344
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
2550

2651
@staticmethod
2752
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)
3055

3156

3257
class ChatUserToken:

0 commit comments

Comments
 (0)