File size: 4,590 Bytes
e78b10d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# utils/user_auth.py
"""User authentication module"""

import streamlit as st
import hashlib
import json
import os
from datetime import datetime

# Simple authentication system for demo
# In production, use proper authentication libraries


def hash_password(password: str) -> str:
    """Hash password using SHA256"""
    return hashlib.sha256(password.encode()).hexdigest()


def load_users():
    """Load users from file"""
    users_file = "data/users.json"
    if os.path.exists(users_file):
        with open(users_file, "r") as f:
            return json.load(f)
    return {}


def save_users(users):
    """Save users to file"""
    os.makedirs("data", exist_ok=True)
    with open("data/users.json", "w") as f:
        json.dump(users, f, indent=2)


def init_authentication():
    """Initialize authentication in session state"""
    if "authenticated" not in st.session_state:
        st.session_state.authenticated = False
    if "username" not in st.session_state:
        st.session_state.username = None


def authenticate_user():
    """Show authentication UI and handle login/signup"""
    if st.session_state.authenticated:
        return True

    st.title("🎯 Welcome to TriviaVerse")
    st.markdown("### Please login or create an account to continue")

    tab1, tab2 = st.tabs(["Login", "Sign Up"])

    with tab1:
        with st.form("login_form"):
            username = st.text_input("Username")
            password = st.text_input("Password", type="password")
            submitted = st.form_submit_button("Login", type="primary")

            if submitted:
                users = load_users()

                if username in users:
                    if users[username]["password"] == hash_password(password):
                        st.session_state.authenticated = True
                        st.session_state.username = username
                        st.session_state.user_id = username

                        # Update last login
                        users[username]["last_login"] = datetime.now().isoformat()
                        save_users(users)

                        st.success("Login successful!")
                        st.rerun()
                    else:
                        st.error("Invalid password")
                else:
                    st.error("Username not found")

    with tab2:
        with st.form("signup_form"):
            new_username = st.text_input("Choose a username")
            new_password = st.text_input("Choose a password", type="password")
            confirm_password = st.text_input("Confirm password", type="password")
            email = st.text_input("Email (optional)")

            terms = st.checkbox("I agree to the terms and conditions")
            submitted = st.form_submit_button("Sign Up", type="primary")

            if submitted:
                if not new_username or not new_password:
                    st.error("Username and password are required")
                elif new_password != confirm_password:
                    st.error("Passwords do not match")
                elif not terms:
                    st.error("Please agree to the terms and conditions")
                else:
                    users = load_users()

                    if new_username in users:
                        st.error("Username already exists")
                    else:
                        # Create new user
                        users[new_username] = {
                            "password": hash_password(new_password),
                            "email": email,
                            "created": datetime.now().isoformat(),
                            "last_login": datetime.now().isoformat(),
                        }
                        save_users(users)

                        # Auto login
                        st.session_state.authenticated = True
                        st.session_state.username = new_username
                        st.session_state.user_id = new_username

                        st.success("Account created successfully!")
                        st.balloons()
                        st.rerun()

    # Guest mode option
    st.divider()
    if st.button("Continue as Guest", type="secondary"):
        st.session_state.authenticated = True
        st.session_state.username = "Guest"
        st.session_state.user_id = f"guest_{int(datetime.now().timestamp())}"
        st.rerun()

    return False