create login page in streamlit and use sqlite as db
To upload files, please first save the app
import streamlit as st
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import Session, DeclarativeBase
from passlib.hash import pbkdf2_sha256
# Database setup
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False)
password = Column(String(256), nullable=False)
# Create engine and tables
engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)
def create_user(username, password):
with Session(engine) as session:
# Check if user already exists
if session.query(User).filter(User.username == username).first():
return False
# Hash password and create new user
hashed_password = pbkdf2_sha256.hash(password)
new_user = User(username=username, password=hashed_password)
session.add(new_user)
session.commit()
return True
def verify_user(username, password):
with Session(engine) as session:
user = session.query(User).filter(User.username == username).first()
if user and pbkdf2_sha256.verify(password, user.password):
return True
return False
# Initialize session state
if 'logged_in' not in st.session_state:
st.session_state.logged_in = False
def login():
st.session_state.logged_in = True
def logout():
st.session_state.logged_in = False
st.title('Login System')
if not st.session_state.logged_in:
tab1, tab2 = st.tabs(['Login', 'Register'])
with tab1:
st.subheader('Login')
login_username = st.text_input('Username', key='login_username')
login_password = st.text_input('Password', type='password', key='login_password')
if st.button('Login'):
if verify_user(login_username, login_password):
login()
st.success('Logged in successfully!')
st.rerun()
else:
st.error('Invalid username or password')
with tab2:
st.subheader('Register')
reg_username = st.text_input('Username', key='reg_username')
reg_password = st.text_input('Password', type='password', key='reg_password')
reg_password_confirm = st.text_input('Confirm Password', type='password')
if st.button('Register'):
if not reg_username or not reg_password:
st.error('Please fill in all fields')
elif reg_password != reg_password_confirm:
st.error('Passwords do not match')
else:
if create_user(reg_username, reg_password):
st.success('Registration successful! You can now login.')
else:
st.error('Username already exists')
else:
st.write(f'Welcome! You are logged in.')
if st.button('Logout'):
logout()
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?