import pretty_errors import streamlit as st import streamlit_authenticator as stauth import yaml from yaml.loader import SafeLoader pretty_errors.configure( line_number_first=True, lines_before=5, lines_after=2, line_color=pretty_errors.RED + "> " + pretty_errors.default_config.line_color, display_locals=True, ) # 從 config.yaml 檔案中讀取設定 try: with open("./config.yaml") as file: config = yaml.load(file, Loader=SafeLoader) except Exception as e: st.error(f"讀取 config.yaml 檔案時發生錯誤: {e}") # 確保配置文件讀取成功並包含必要的鍵 if config and "credentials" in config and "cookie" in config: # 檢查 credentials 結構 try: credentials = config["credentials"] if "usernames" in credentials: for username, details in credentials["usernames"].items(): if not isinstance(details.get("password"), str): raise TypeError(f"使用者 {username} 的密碼不是字串: {details.get('password')}") except TypeError as e: st.error(f"配置文件中的錯誤: {e}") except Exception as e: st.error(f"驗證配置文件時發生未知錯誤: {e}") else: st.error("配置文件不完整或無法讀取") # User Authentication with Authenticator try: authenticator = stauth.Authenticate( config["credentials"], config["cookie"]["name"], config["cookie"]["key"], config["cookie"]["expiry_days"], config["pre-authorized"], ) except Exception as e: st.error(f"初始化 Authenticator 時發生錯誤: {e}") # Attempt User Login with Authenticator try: authenticator.login( fields={ "Form name": "登入", "Username": "使用者名稱", "Password": "密碼", "Login": "登入", }, location="main", ) except Exception as e: st.error(f"登入時發生錯誤: {e}") # 根據驗證的情況執行不同的操作 if st.session_state.get("authentication_status"): authenticator.logout("Logout", "main", key="unique_key") user_info = { "name": st.session_state.get("name"), "username": st.session_state.get("username"), } st.write(user_info) elif st.session_state.get("authentication_status") is False: st.error("使用者名稱/密碼不正確") elif st.session_state.get("authentication_status") is None: st.warning("請輸入你的使用者名稱和密碼") with open("./config.yaml", "w") as file: yaml.dump(config, file, default_flow_style=False)