57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
"""进程内只保留当前管理员的用户名和密码密文。
|
|
|
|
不缓存明文密码,也不缓存 e 学用户、登录凭证或检查结果。
|
|
启动时从设置表加载,修改用户名或密码后同步。重启会重新加载。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hmac
|
|
import threading
|
|
from contextlib import contextmanager
|
|
|
|
from admin.passwords import is_hashed, verify_password
|
|
from euniv.crypto import decrypt_secret
|
|
|
|
|
|
class AdminIdentity:
|
|
def __init__(self) -> None:
|
|
self._username = ""
|
|
self._password_cipher = ""
|
|
self._lock = threading.RLock()
|
|
|
|
@contextmanager
|
|
def exclusive(self):
|
|
with self._lock:
|
|
yield
|
|
|
|
def replace(self, username: str, password_cipher: str) -> None:
|
|
with self._lock:
|
|
self._username = username
|
|
self._password_cipher = password_cipher
|
|
|
|
def matches(self, account: str) -> bool:
|
|
with self._lock:
|
|
username = self._username
|
|
return bool(username) and account == username
|
|
|
|
def password_ok(self, password: str) -> bool:
|
|
with self._lock:
|
|
cipher = self._password_cipher
|
|
if not cipher:
|
|
return False
|
|
if is_hashed(cipher):
|
|
return verify_password(cipher, password)
|
|
try:
|
|
stored = decrypt_secret(cipher).encode("utf-8")
|
|
except Exception:
|
|
return False
|
|
return hmac.compare_digest(stored, password.encode("utf-8"))
|
|
|
|
def username(self) -> str:
|
|
with self._lock:
|
|
return self._username
|
|
|
|
|
|
identity = AdminIdentity()
|