UnisKB/apps/common/auth/common.py

63 lines
1.9 KiB
Python
Raw Normal View History

2025-06-06 14:28:21 +00:00
# coding=utf-8
"""
@project: MaxKB
@Author虎虎
@file common.py
@date2025/6/6 19:55
@desc:
"""
import json
from django.core import signing
from common.utils.rsa_util import encrypt, decrypt
class ChatAuthentication:
2025-06-09 08:57:04 +00:00
def __init__(self, auth_type: str | None):
2025-06-06 14:28:21 +00:00
self.auth_type = auth_type
def to_dict(self):
2025-06-09 08:57:04 +00:00
return {'auth_type': self.auth_type}
2025-06-06 14:28:21 +00:00
def to_string(self):
return encrypt(json.dumps(self.to_dict()))
@staticmethod
def new_instance(authentication: str):
auth = json.loads(decrypt(authentication))
2025-06-09 08:57:04 +00:00
return ChatAuthentication(auth.get('auth_type'))
2025-06-06 14:28:21 +00:00
class ChatUserToken:
2025-06-09 08:18:43 +00:00
def __init__(self, application_id, user_id, access_token, _type, chat_user_type, chat_user_id,
2025-06-06 14:28:21 +00:00
authentication: ChatAuthentication):
self.application_id = application_id
self.user_id = user_id,
self.access_token = access_token
self.type = _type
2025-06-09 08:18:43 +00:00
self.chat_user_type = chat_user_type
self.chat_user_id = chat_user_id
2025-06-06 14:28:21 +00:00
self.authentication = authentication
def to_dict(self):
return {
'application_id': str(self.application_id),
'user_id': str(self.user_id),
'access_token': self.access_token,
'type': str(self.type.value),
2025-06-09 08:18:43 +00:00
'chat_user_type': str(self.chat_user_type),
'chat_user_id': str(self.chat_user_id),
2025-06-06 14:28:21 +00:00
'authentication': self.authentication.to_string()
}
def to_token(self):
return signing.dumps(self.to_dict())
@staticmethod
def new_instance(token_dict):
return ChatUserToken(token_dict.get('application_id'), token_dict.get('user_id'),
2025-06-09 08:18:43 +00:00
token_dict.get('access_token'), token_dict.get('type'), token_dict.get('chat_user_type'),
token_dict.get('chat_user_id'),
2025-06-06 14:28:21 +00:00
ChatAuthentication.new_instance(token_dict.get('authentication')))