shaheerawan3's picture
Update app.py
8d3bd0a verified
# app.py
import streamlit as st
from utils.metrics import get_login_attempts_counter
from views import show_login_page, show_dashboard, show_add_account_page, show_heir_management_page, show_security_settings_page
from models import initialize_database
from creator import Creator
import sqlite3
import os
from prometheus_client import REGISTRY
import logging
from config import init_app
import re
from typing import Tuple # Add this import at the top
from utils.security import log_security_event
from views import (
show_login_page,
show_dashboard,
show_add_account_page,
show_heir_management_page,
show_security_settings_page
)
from models import initialize_database
from dashboard_components import apply_custom_css
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
CREATOR_INFO = {
"name": "MUHAMMAD SHAHEER",
"version": "1.0.0",
"description": "Advanced Digital Asset Management & Inheritance"
}
if 'login_attempts_counter' not in st.session_state:
st.session_state['login_attempts_counter'] = get_login_attempts_counter()
def initialize_app():
"""Initialize the application."""
# Clear any existing metrics from previous sessions
try:
REGISTRY.unregister(REGISTRY._names_to_collectors['login_attempts_total'])
except KeyError:
pass
def initialize_session_state():
"""Initialize all required session state variables"""
if 'initialized' not in st.session_state:
try:
# Clear any existing metrics first
if 'login_attempts_counter' in st.session_state:
del st.session_state['login_attempts_counter']
# Initialize basic session state variables
st.session_state.initialized = False
st.session_state.page = 'login'
st.session_state.user = None
st.session_state.login_attempts = {}
# Initialize database connection
if 'db' not in st.session_state:
st.session_state.db = sqlite3.connect('digital_heir.db', check_same_thread=False)
# Initialize metrics
from utils.metrics import get_login_attempts_counter
st.session_state.login_attempts_counter = get_login_attempts_counter()
# Initialize database tables
initialize_database()
st.session_state.initialized = True
return True
except Exception as e:
logger.error(f"Initialization error: {str(e)}")
st.error(f"Failed to initialize: {str(e)}")
return False
return True
def validate_inputs(data: dict) -> Tuple[bool, str]:
"""Validate user inputs"""
if not all(data.values()):
return False, "All fields are required"
if 'email' in data and not re.match(r"[^@]+@[^@]+\.[^@]+", data['email']):
return False, "Invalid email format"
if 'username' in data and len(data['username']) < 3:
return False, "Username must be at least 3 characters"
return True, "Validation successful"
def handle_database_error(e: Exception, operation: str):
"""Handle database errors"""
error_msg = f"Database error during {operation}: {str(e)}"
logging.error(error_msg)
st.error(error_msg)
return False
def main():
"""Main application entry point"""
# Initialize session state first
init_success = initialize_session_state()
if not init_success:
st.error("Failed to initialize application. Please try again.")
return
# Check if user is logged in
if 'user' not in st.session_state or st.session_state.user is None:
show_login_page()
else:
# Define available pages
pages = {
'dashboard': show_dashboard,
'add_account': show_add_account_page,
'manage_heirs': show_heir_management_page,
'security': show_security_settings_page
}
# Get current page from session state, default to dashboard
current_page = st.session_state.get('page', 'dashboard')
# Show the current page
pages.get(current_page, show_dashboard)()
if __name__ == "__main__":
st.set_page_config(
page_title="Digital Inheritance System",
page_icon="🔐",
layout="wide"
)
if 'db' not in st.session_state:
st.session_state.db = sqlite3.connect('digital_heir.db', check_same_thread=False)
main()