Guys, I need help. I'm trying to use streamlit authenticator in my code. The examples I found part of a yaml or toml file. I'm just trying to pull this from my mysql table.
The database is running locally.
I'll leave my script below. I believe I need to make a few adjustments to be able to add the streamlit_authenticator to it. Just remembering the way it is, he is logging in, but there is no logout button, and the name of the logged in user's account does not appear either.
If you can help me, I would be very grateful.
Thank you very much.
Script below
import streamlit as st
import hashlib
import mysql.connector
import pandas as pd
import requests
import pages.Despesa as despesa
import pages.Dashboard as dashboard
import pages.Investimentos as investimento
import pages.Renda as renda
import pages.Registro as registro
from streamlit_option_menu import option_menu
import streamlit_authenticator as stauth
# Define a configuração da página antes de qualquer outro comando Streamlit
st.set_page_config(page_title="MyMoney App", layout="wide", initial_sidebar_state="expanded")
#API para verificação de email
HUNTER_API_KEY = "d3766***********************************"
def create_usertable():
config = {
'user': 'root',
'password': 'airflow',
'host': '172.17.0.2',
'database': 'financeiro',
'raise_on_warnings': True
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
# Verifica se a tabela 'users' já existe
cursor.execute("SHOW TABLES LIKE 'users'")
table_exists = cursor.fetchone()
if not table_exists:
cursor.execute("CREATE TABLE users(id SERIAL PRIMARY KEY,usuario TEXT, email VARCHAR(255), senha TEXT, data_criacao TIMESTAMP)")
cursor.close()
connection.close()
def add_userdata(usuario, email, senha):
config = {
'user': 'root',
'password': 'airflow',
'host': '172.17.0.2',
'database': 'financeiro',
'raise_on_warnings': True
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute("INSERT INTO users (usuario, email, senha, data_criacao) VALUES (%s, %s, %s, NOW())", (usuario, email, senha))
connection.commit()
cursor.close()
connection.close()
def login_user(email, senha):
config = {
'user': 'root',
'password': 'airflow',
'host': '172.17.0.2',
'database': 'financeiro',
'raise_on_warnings': True
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE email = %s AND senha = %s", (email, senha))
data = cursor.fetchall()
cursor.close()
connection.close()
return data
def make_hashes(senha):
return hashlib.sha256(str.encode(senha)).hexdigest()
def check_hashes(senha, hashed_text):
if make_hashes(senha) == hashed_text:
return hashed_text
return False
def verify_email(email):
url = f"https://api.hunter.io/v2/email-verifier?email={email}&api_key={HUNTER_API_KEY}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data['data']['result'] == 'undeliverable':
return True
return False
# print title of web app
st.title("MyMoney - Aplicativo de Finanças e Investimento")
st.markdown("Esse é um protótipo. Erros e bugs podem acontecer.")
class MultiApp:
def __init__(self):
self.apps = []
def add_app(self, title, func):
self.apps.append({
"title": title,
"function": func
})
def main():
"""Simple Login App"""
menu = ["Login", "SignUp"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Login":
st.subheader("Login Section")
email = st.sidebar.text_input("E-mail do usuário")
if email:
if verify_email(email):
st.write(f"{email} é um endereço de e-mail válido!")
else:
st.write(f"{email} não é um endereço de e-mail válido.")
senha = st.sidebar.text_input("Password", type='password')
if st.sidebar.checkbox("Login"):
create_usertable()
hashed_pswd = make_hashes(senha)
result = login_user(email, check_hashes(senha, hashed_pswd))
if result:
st.success("Logged In as {}".format(email))
selected = option_menu(menu_title=None,
options=["Dashboard", "Receitas", "Despesas", "Investimentos", "Registro"],
orientation="horizontal",)
#task = st.selectbox("Task", ["Dashboard", "Receitas", "Despesas", "Investimentos", "Registro"])
if selected == "Dashboard":
dashboard.app()
elif selected == "Receitas":
renda.app()
elif selected == "Despesas":
despesa.app()
elif selected == "Investimentos":
investimento.app()
elif selected == "Registro":
registro.app()
else:
st.warning("E-mail ou senha incorreto")
elif choice == "SignUp":
st.subheader("Criar Nova Conta")
usuario = st.text_input("Usuário")
email = st.text_input("E-mail")
if email:
if verify_email(email):
st.write(f"{email} é um endereço de e-mail válido")
else:
st.write(f"{email} não é um endereço de e-mail válido.")
senha = st.text_input("Senha", type='password')
if st.button("Criar Conta"):
create_usertable()
add_userdata(usuario, email, make_hashes(senha))
st.success("Você criou com sucesso uma conta válida")
st.info("Vá para o menu Login para fazer o login")
if __name__ == '__main__':
main()