最后活跃于 10 months ago

這段程式碼使用 Streamlit 和 streamlit-authenticator 來 管理使用者登入,透過 YAML 設定檔 儲存使用者憑證與 Cookie 配置,並提供 登入、登出 和 使用者驗證 功能。

config.yaml 原始文件
1cookie:
2 expiry_days: 30
3 key: some_signature_key
4 name: my_auth_cookie
5credentials:
6 usernames:
7 jsmith:
8 email: jsmith@gmail.com
9 failed_login_attempts: 0 # Will be managed automatically
10 logged_in: False # Will be managed automatically
11 name: John Smith
12 password: abc # Will be hashed automatically
13 rbriggs:
14 email: rbriggs@gmail.com
15 failed_login_attempts: 0 # Will be managed automatically
16 logged_in: False # Will be managed automatically
17 name: Rebecca Briggs
18 password: def # Will be hashed automatically
19pre-authorized:
20 emails:
21 - admin@example.com
22 - manager@example.com
23
streamlit_authentication_with_yaml.py 原始文件
1import pretty_errors
2import streamlit as st
3import streamlit_authenticator as stauth
4import yaml
5from yaml.loader import SafeLoader
6
7pretty_errors.configure(
8 line_number_first=True,
9 lines_before=5,
10 lines_after=2,
11 line_color=pretty_errors.RED + "> " + pretty_errors.default_config.line_color,
12 display_locals=True,
13)
14
15# 從 config.yaml 檔案中讀取設定
16try:
17 with open("./config.yaml") as file:
18 config = yaml.load(file, Loader=SafeLoader)
19except Exception as e:
20 st.error(f"讀取 config.yaml 檔案時發生錯誤: {e}")
21
22# 確保配置文件讀取成功並包含必要的鍵
23if config and "credentials" in config and "cookie" in config:
24 # 檢查 credentials 結構
25 try:
26 credentials = config["credentials"]
27 if "usernames" in credentials:
28 for username, details in credentials["usernames"].items():
29 if not isinstance(details.get("password"), str):
30 raise TypeError(f"使用者 {username} 的密碼不是字串: {details.get('password')}")
31 except TypeError as e:
32 st.error(f"配置文件中的錯誤: {e}")
33 except Exception as e:
34 st.error(f"驗證配置文件時發生未知錯誤: {e}")
35else:
36 st.error("配置文件不完整或無法讀取")
37
38# User Authentication with Authenticator
39try:
40 authenticator = stauth.Authenticate(
41 config["credentials"],
42 config["cookie"]["name"],
43 config["cookie"]["key"],
44 config["cookie"]["expiry_days"],
45 config["pre-authorized"],
46 )
47except Exception as e:
48 st.error(f"初始化 Authenticator 時發生錯誤: {e}")
49
50# Attempt User Login with Authenticator
51try:
52 authenticator.login(
53 fields={
54 "Form name": "登入",
55 "Username": "使用者名稱",
56 "Password": "密碼",
57 "Login": "登入",
58 },
59 location="main",
60 )
61except Exception as e:
62 st.error(f"登入時發生錯誤: {e}")
63
64# 根據驗證的情況執行不同的操作
65if st.session_state.get("authentication_status"):
66 authenticator.logout("Logout", "main", key="unique_key")
67 user_info = {
68 "name": st.session_state.get("name"),
69 "username": st.session_state.get("username"),
70 }
71 st.write(user_info)
72elif st.session_state.get("authentication_status") is False:
73 st.error("使用者名稱/密碼不正確")
74elif st.session_state.get("authentication_status") is None:
75 st.warning("請輸入你的使用者名稱和密碼")
76
77with open("./config.yaml", "w") as file:
78 yaml.dump(config, file, default_flow_style=False)
79