yahtzee-py/models/database.py

212 lines
9.5 KiB
Python

import sqlite3
import hashlib
import hmac
import json
import os
DB_FILE = "yahtzee_profiles.db"
# Ein kleines, hartcodiertes "Salz" für unsere Signatur
SECRET_PEPPER = b"yahtzee_tui_super_secret_pepper_2026"
class Database:
@staticmethod
def init_db():
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# Profile Table
c.execute('''CREATE TABLE IF NOT EXISTS profiles
(id INTEGER PRIMARY KEY, name TEXT UNIQUE, pass_hash TEXT, language TEXT)''')
# Stats Table
c.execute('''CREATE TABLE IF NOT EXISTS stats
(profile_id INTEGER PRIMARY KEY,
vs_real_wins INT, vs_real_loss INT, vs_real_avg REAL, vs_real_high INT,
vs_bot_wins INT, vs_bot_loss INT, vs_bot_avg REAL, vs_bot_high INT,
signature TEXT)''')
# Save Game Table
c.execute('''CREATE TABLE IF NOT EXISTS saved_game
(profile_id INTEGER PRIMARY KEY, game_data TEXT)''')
conn.commit()
@staticmethod
def login_local(name):
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# Wir suchen nur nach dem Namen und holen uns den gespeicherten Hash
c.execute("SELECT id, language, pass_hash FROM profiles WHERE name=?", (name,))
result = c.fetchone()
if result:
prof_id, lang, pass_hash = result
# Verifiziere Stats (Tamper-Check)
c.execute("SELECT * FROM stats WHERE profile_id=?", (prof_id,))
s = c.fetchone()
if s:
stats_dict = {'vr_w':s[1], 'vr_l':s[2], 'vr_avg':s[3], 'vr_h':s[4], 'vb_w':s[5], 'vb_l':s[6], 'vb_avg':s[7], 'vb_h':s[8]}
sig = Database._generate_signature(stats_dict, pass_hash)
if sig != s[9]:
return None, "CORRUPT"
return {'id': prof_id, 'name': name, 'lang': lang, 'pass_hash': pass_hash}, "OK"
return None, "INVALID"
@staticmethod
def get_all_profile_names():
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT name FROM profiles")
return [row[0] for row in c.fetchall()]
@staticmethod
def _hash_password(password):
return hashlib.sha256((password + "salt").encode()).hexdigest()
@staticmethod
def _generate_signature(stats_dict, pass_hash):
"""Generiert einen manipulationssicheren Hash aus den Stats + User Passwort"""
data_string = f"{stats_dict['vr_w']}{stats_dict['vr_l']}{stats_dict['vr_h']}{stats_dict['vb_w']}{stats_dict['vb_l']}{stats_dict['vb_h']}"
key = (pass_hash + SECRET_PEPPER.decode()).encode()
return hmac.new(key, data_string.encode(), hashlib.sha256).hexdigest()
@staticmethod
def create_profile(name, password, lang):
Database.init_db()
pass_hash = Database._hash_password(password)
try:
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("INSERT INTO profiles (name, pass_hash, language) VALUES (?, ?, ?)", (name, pass_hash, lang))
prof_id = c.lastrowid
# Initiale leere Stats
init_stats = {'vr_w':0, 'vr_l':0, 'vr_avg':0.0, 'vr_h':0, 'vb_w':0, 'vb_l':0, 'vb_avg':0.0, 'vb_h':0}
sig = Database._generate_signature(init_stats, pass_hash)
c.execute('''INSERT INTO stats VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(prof_id, 0, 0, 0.0, 0, 0, 0, 0.0, 0, sig))
conn.commit()
return True
except sqlite3.IntegrityError:
return False # Name existiert schon
@staticmethod
def login(name, password):
Database.init_db()
pass_hash = Database._hash_password(password)
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT id, language FROM profiles WHERE name=? AND pass_hash=?", (name, pass_hash))
result = c.fetchone()
if result:
# Verifiziere Stats (Tamper-Check)
c.execute("SELECT * FROM stats WHERE profile_id=?", (result[0],))
s = c.fetchone()
if s:
stats_dict = {'vr_w':s[1], 'vr_l':s[2], 'vr_avg':s[3], 'vr_h':s[4], 'vb_w':s[5], 'vb_l':s[6], 'vb_avg':s[7], 'vb_h':s[8]}
sig = Database._generate_signature(stats_dict, pass_hash)
if sig != s[9]:
return None, "CORRUPT" # Jemand hat die DB manuell bearbeitet!
return {'id': result[0], 'name': name, 'lang': result[1], 'pass_hash': pass_hash}, "OK"
return None, "INVALID"
@staticmethod
def get_stats(profile_id):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT * FROM stats WHERE profile_id=?", (profile_id,))
return c.fetchone()
@staticmethod
def record_game(profile, is_vs_bot, won, score):
s = Database.get_stats(profile['id'])
if not s: return
# s indices: 1:vr_w, 2:vr_l, 3:vr_avg, 4:vr_h, 5:vb_w, 6:vb_l, 7:vb_avg, 8:vb_h
vr_w, vr_l, vr_avg, vr_h = s[1], s[2], s[3], s[4]
vb_w, vb_l, vb_avg, vb_h = s[5], s[6], s[7], s[8]
if is_vs_bot:
total_games = vb_w + vb_l
vb_w += 1 if won else 0
vb_l += 0 if won else 1
vb_avg = ((vb_avg * total_games) + score) / (total_games + 1)
vb_h = max(vb_h, score)
else:
total_games = vr_w + vr_l
vr_w += 1 if won else 0
vr_l += 0 if won else 1
vr_avg = ((vr_avg * total_games) + score) / (total_games + 1)
vr_h = max(vr_h, score)
stats_dict = {'vr_w':vr_w, 'vr_l':vr_l, 'vr_avg':vr_avg, 'vr_h':vr_h, 'vb_w':vb_w, 'vb_l':vb_l, 'vb_avg':vb_avg, 'vb_h':vb_h}
sig = Database._generate_signature(stats_dict, profile['pass_hash'])
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute('''UPDATE stats SET
vs_real_wins=?, vs_real_loss=?, vs_real_avg=?, vs_real_high=?,
vs_bot_wins=?, vs_bot_loss=?, vs_bot_avg=?, vs_bot_high=?, signature=?
WHERE profile_id=?''',
(vr_w, vr_l, vr_avg, vr_h, vb_w, vb_l, vb_avg, vb_h, sig, profile['id']))
conn.commit()
# --- SAVE / RESUME GAME ---
@staticmethod
def save_game(profile_id, game_state_json):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("REPLACE INTO saved_game (profile_id, game_data) VALUES (?, ?)", (profile_id, game_state_json))
conn.commit()
@staticmethod
def load_game(profile_id):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT game_data FROM saved_game WHERE profile_id=?", (profile_id,))
res = c.fetchone()
return res[0] if res else None
@staticmethod
def delete_save(profile_id):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("DELETE FROM saved_game WHERE profile_id=?", (profile_id,))
conn.commit()
@staticmethod
def save_bot_names(profile_id, bot_names_dict):
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS bot_names (profile_id INTEGER, bot_index INTEGER, name TEXT, PRIMARY KEY(profile_id, bot_index))")
for idx, name in bot_names_dict.items():
c.execute("INSERT OR REPLACE INTO bot_names (profile_id, bot_index, name) VALUES (?, ?, ?)", (profile_id, idx, name))
conn.commit()
@staticmethod
def load_bot_names(profile_id):
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS bot_names (profile_id INTEGER, bot_index INTEGER, name TEXT, PRIMARY KEY(profile_id, bot_index))")
c.execute("SELECT bot_index, name FROM bot_names WHERE profile_id=?", (profile_id,))
return {row[0]: row[1] for row in c.fetchall()}
@staticmethod
def save_bot_configs(profile_id, bot_configs_dict):
# bot_configs_dict = {index: (name, level)}
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS bot_configs (profile_id INTEGER, bot_index INTEGER, name TEXT, level INTEGER, PRIMARY KEY(profile_id, bot_index))")
for idx, (name, level) in bot_configs_dict.items():
c.execute("INSERT OR REPLACE INTO bot_configs (profile_id, bot_index, name, level) VALUES (?, ?, ?, ?)", (profile_id, idx, name, level))
conn.commit()
@staticmethod
def load_bot_configs(profile_id):
Database.init_db()
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS bot_configs (profile_id INTEGER, bot_index INTEGER, name TEXT, level INTEGER)")
c.execute("SELECT bot_index, name, level FROM bot_configs WHERE profile_id=?", (profile_id,))
return {row[0]: (row[1], row[2]) for row in c.fetchall()}