linux
This commit is contained in:
1 parent
f6f1ae20c2
commit
efd4e1dcf4
43 files changed
+25641
No files matched your search
@@ -0,0 +1,136 @@
|
||||
"""Local multi-user authentication and isolated per-user data folders."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class AuthError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class UserStore:
|
||||
ITERATIONS = 420_000
|
||||
SESSION_SECONDS = 12 * 60 * 60
|
||||
USER_RE = re.compile(r"^[a-zA-Z0-9_.-]{3,32}$")
|
||||
|
||||
def __init__(self, root: Path):
|
||||
self.root = Path(root)
|
||||
self.db = self.root / "accounts.sqlite3"
|
||||
self.users_dir = self.root / "users"
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
self.users_dir.mkdir(parents=True, exist_ok=True)
|
||||
with self.connect() as con:
|
||||
con.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
salt BLOB NOT NULL,
|
||||
password_hash BLOB NOT NULL,
|
||||
created REAL NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash BLOB PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires REAL NOT NULL,
|
||||
created REAL NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS metadata (
|
||||
name TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires);
|
||||
""")
|
||||
|
||||
def connect(self):
|
||||
con = sqlite3.connect(self.db, timeout=15)
|
||||
con.execute("PRAGMA foreign_keys=ON")
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
return con
|
||||
|
||||
@classmethod
|
||||
def _password_hash(cls, password: str, salt: bytes) -> bytes:
|
||||
return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, cls.ITERATIONS)
|
||||
|
||||
def register(self, username: str, password: str) -> str:
|
||||
username, password = (username or "").strip(), password or ""
|
||||
if not self.USER_RE.fullmatch(username):
|
||||
raise AuthError("Логин: 3–32 символа, латинские буквы, цифры, точка, дефис или подчёркивание")
|
||||
if len(password) < 12 or len(password) > 256:
|
||||
raise AuthError("Пароль должен содержать от 12 до 256 символов")
|
||||
user_id, salt = uuid.uuid4().hex, secrets.token_bytes(16)
|
||||
try:
|
||||
with self.connect() as con:
|
||||
con.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)",
|
||||
(user_id, username, salt, self._password_hash(password, salt), time.time()))
|
||||
except sqlite3.IntegrityError:
|
||||
raise AuthError("Такой логин уже зарегистрирован") from None
|
||||
(self.users_dir / user_id).mkdir(parents=True, exist_ok=True)
|
||||
return user_id
|
||||
|
||||
def authenticate(self, username: str, password: str) -> str | None:
|
||||
with self.connect() as con:
|
||||
row = con.execute("SELECT id, salt, password_hash FROM users WHERE username=? COLLATE NOCASE",
|
||||
((username or "").strip(),)).fetchone()
|
||||
if row is None:
|
||||
# Keep the missing-user path close to the cost of a real password check.
|
||||
self._password_hash(password or "", b"\0" * 16)
|
||||
return None
|
||||
return row[0] if hmac.compare_digest(self._password_hash(password or "", row[1]), row[2]) else None
|
||||
|
||||
@staticmethod
|
||||
def _token_hash(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
def create_session(self, user_id: str) -> str:
|
||||
token = secrets.token_urlsafe(36)
|
||||
now = time.time()
|
||||
with self.connect() as con:
|
||||
con.execute("DELETE FROM sessions WHERE expires < ?", (now,))
|
||||
con.execute("INSERT INTO sessions VALUES (?, ?, ?, ?)",
|
||||
(self._token_hash(token), user_id, now + self.SESSION_SECONDS, now))
|
||||
return token
|
||||
|
||||
def user_for_session(self, token: str | None) -> str | None:
|
||||
if not token or len(token) > 128:
|
||||
return None
|
||||
with self.connect() as con:
|
||||
row = con.execute("SELECT user_id FROM sessions WHERE token_hash=? AND expires>=?",
|
||||
(self._token_hash(token), time.time())).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def delete_session(self, token: str | None) -> None:
|
||||
if token:
|
||||
with self.connect() as con:
|
||||
con.execute("DELETE FROM sessions WHERE token_hash=?", (self._token_hash(token),))
|
||||
|
||||
def user_ids(self) -> list[str]:
|
||||
with self.connect() as con:
|
||||
return [row[0] for row in con.execute("SELECT id FROM users ORDER BY created")]
|
||||
|
||||
def username(self, user_id: str) -> str:
|
||||
with self.connect() as con:
|
||||
row = con.execute("SELECT username FROM users WHERE id=?", (user_id,)).fetchone()
|
||||
return row[0] if row else ""
|
||||
|
||||
def mark_legacy_imported(self) -> bool:
|
||||
"""Atomically elect only the first registered account to receive the old single-user data."""
|
||||
with self.connect() as con:
|
||||
cur = con.execute("INSERT OR IGNORE INTO metadata VALUES ('legacy_imported', '1')")
|
||||
return cur.rowcount == 1
|
||||
|
||||
def data_dir(self, user_id: str) -> Path:
|
||||
if not re.fullmatch(r"[0-9a-f]{32}", user_id):
|
||||
raise AuthError("Некорректный идентификатор пользователя")
|
||||
path = self.users_dir / user_id / "data"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
Reference in new issue
Block a user