Files
Achievement_Inputing/accounts/es_client.py
2025-11-10 09:31:54 +08:00

33 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import base64
import hashlib
from elastic.es_connect import get_user_by_username as es_get_user_by_username
def _salt_for_username(username: str) -> bytes:
return hashlib.sha256(username.encode('utf-8')).digest()
def _derive_password(password_plain: str, salt: bytes) -> bytes:
return hashlib.pbkdf2_hmac('sha256', password_plain.encode('utf-8'), salt, 100_000, dklen=32)
def get_user_by_username(username: str):
"""
从Elasticsearch获取用户数据
"""
# 首先尝试从ES获取用户数据
es_user = es_get_user_by_username(username)
salt = _salt_for_username(username)
derived = _derive_password(es_user.get('password', ''), salt)
if es_user:
# 如果ES中有用户数据使用ES中的密码
return {
'user_id': es_user.get('user_id', 0),
'username': es_user.get('username', ''),
'password': base64.b64encode(derived).decode('ascii'),
'premission': es_user.get('permission', 1),
'salt': base64.b64encode(salt).decode('ascii'),
}
return None