venesis / auth.py
JohnGFX's picture
Venegard AI Hub - production release
ca812a1
"""
Authentication and configuration module using Streamlit Authenticator.
"""
import streamlit as st # type: ignore
from pathlib import Path
import yaml # type: ignore
import os
import streamlit_authenticator as stauth # type: ignore
from yaml.loader import SafeLoader # type: ignore
# Cesta ke konfiguraci (použijeme hlavní config.yaml v rootu projektu)
CONFIG_PATH = Path("config.yaml")
# Základní šablona, pokud soubor neexistuje
DEFAULT_CONFIG = """
credentials:
usernames:
demo_user:
email: demo@saleshub.cz
name: Demo User
password: demo123
admin:
email: honza@saleshub.cz
name: Jan Novák
password: $2b$12$KIXs6vCDAxNS6qVHbPG8z.TwVDKL3r0gJP8L5dMKNBFyh0k1S0Y5i
cookie:
expiry_days: 30
key: sales_hub_secret_key
name: sales_hub_auth
preauthorized:
emails:
- demo@saleshub.cz
"""
def load_auth_config():
"""Načte nebo vytvoří konfigurační soubor."""
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
if not CONFIG_PATH.exists():
with open(CONFIG_PATH, "w") as f:
f.write(DEFAULT_CONFIG)
with open(CONFIG_PATH) as file:
config = yaml.load(file, Loader=SafeLoader)
return config
def init_auth_config():
"""
Hlavní funkce pro inicializaci přihlašování.
Vrací objekt 'authenticator', který pak v app.py vykreslí login.
"""
config = load_auth_config()
# Normalize usernames to lower-case for case-insensitive login
creds = config.get("credentials", {})
usernames = creds.get("usernames", {})
normalized_usernames = {}
for username, data in usernames.items():
normalized_usernames[username.lower()] = data
creds["usernames"] = normalized_usernames
config["credentials"] = creds
authenticator = stauth.Authenticate(
config["credentials"],
config["cookie"]["name"],
config["cookie"]["key"],
config["cookie"]["expiry_days"],
)
return authenticator, config
def is_authenticated() -> bool:
"""Vrátí True, pokud je uživatel úspěšně přihlášen."""
return st.session_state.get("authentication_status") is True
def get_current_user():
"""Vrátí info o aktuálním uživateli (jméno, username)."""
if is_authenticated():
return {
"username": st.session_state.get("username"),
"name": st.session_state.get("name"),
"logout": st.session_state.get("logout")
}
return None