saddie / app.py
URIQ0023's picture
Update app.py
84a23b7 verified
import streamlit as st
import pymongo
import bcrypt
import os
import json
from dotenv import load_dotenv
import streamlit_authenticator as stauth
# Load environment variables
load_dotenv()
if os.path.exists("secrets.json"):
with open("secrets.json") as f:
secrets = json.load(f)
os.environ.update(secrets)
MONGO_URI = os.getenv("MONGO_URI")
SECRET_KEY = os.getenv("SECRET_KEY")
if not MONGO_URI or not SECRET_KEY:
st.error("Missing environment variables! Please check your Hugging Face Secrets.")
st.stop()
# Connect to MongoDB
client = pymongo.MongoClient(MONGO_URI)
db = client["user_database"]
users_collection = db["users"]
# Function to hash passwords
def hash_password(password):
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
# Function to verify passwords
def verify_password(password, hashed):
return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
# UI Customization
st.set_page_config(page_title="Secure Login App", page_icon="🔒", layout="centered")
# Light/Dark Mode Toggle
theme_mode = st.toggle("🌞 Light / 🌙 Dark Mode", value=True)
if theme_mode:
st.markdown(
"""
<style>
body { background-color: #f0f2f6; color: black; }
.stTextInput>div>div>input, .stButton>button { background-color: white; }
</style>
""",
unsafe_allow_html=True
)
else:
st.markdown(
"""
<style>
body { background-color: #1e1e1e; color: white; }
.stTextInput>div>div>input, .stButton>button { background-color: #333; color: white; }
</style>
""",
unsafe_allow_html=True
)
# Login and Signup Flow
if "signup_mode" not in st.session_state:
st.session_state.signup_mode = False
if not st.session_state.signup_mode:
st.subheader("🔑 Login to Your Account")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
user = users_collection.find_one({"username": username})
if user and verify_password(password, user["password"]):
st.success(f"Welcome {username}!")
else:
st.error("Invalid credentials. Please try again.")
# Hyperlink to switch to signup
if st.button("Sign up instead"):
st.session_state.signup_mode = True
st.rerun()
else:
st.subheader("📝 Create a New Account")
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")
if st.button("Sign Up"):
if new_password != confirm_password:
st.error("Passwords do not match.")
elif users_collection.find_one({"username": new_username}):
st.error("Username already exists.")
else:
hashed_password = hash_password(new_password)
users_collection.insert_one({"username": new_username, "password": hashed_password})
st.success("Account created successfully! You can now log in.")
# Hyperlink to switch back to login
if st.button("Back to Login"):
st.session_state.signup_mode = False
st.rerun()