Dernière activité 10 months ago

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

timmy a révisé ce gist 10 months ago. Aller à la révision

Aucun changement

timmy a révisé ce gist 10 months ago. Aller à la révision

Aucun changement

timmy a révisé ce gist 2 years ago. Aller à la révision

1 file changed, 11 insertions, 17 deletions

config.yaml

@@ -4,24 +4,18 @@ cookie:
4 4 name: my_auth_cookie
5 5 credentials:
6 6 usernames:
7 - timmy:
8 - email: timmy.lo@automodules.com
9 - failed_login_attempts: 0
10 - logged_in: true
11 - name: Timmy
12 - password: abc # Will be hashed automatically
13 - user1:
14 - email: user1@example.com
15 - failed_login_attempts: 0
16 - logged_in: false
17 - name: User One
18 - password: abc # Will be hashed automatically
19 - user2:
20 - email: user2@example.com
21 - failed_login_attempts: 0
22 - logged_in: false
23 - name: User Two
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
24 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
25 19 pre-authorized:
26 20 emails:
27 21 - admin@example.com

timmy a révisé ce gist 2 years ago. Aller à la révision

2 files changed, 91 insertions, 39 deletions

config.yaml

@@ -1,18 +1,28 @@
1 + cookie:
2 + expiry_days: 30
3 + key: some_signature_key
4 + name: my_auth_cookie
1 5 credentials:
2 6 usernames:
7 + timmy:
8 + email: timmy.lo@automodules.com
9 + failed_login_attempts: 0
10 + logged_in: true
11 + name: Timmy
12 + password: abc # Will be hashed automatically
3 13 user1:
4 14 email: user1@example.com
15 + failed_login_attempts: 0
16 + logged_in: false
5 17 name: User One
6 - password: $2b$12$RVn2UdS.KJiM24xT3Vb9fOIEv4S3hvP6Pjw2xzaP5d/fDq1U2pX2e
18 + password: abc # Will be hashed automatically
7 19 user2:
8 20 email: user2@example.com
21 + failed_login_attempts: 0
22 + logged_in: false
9 23 name: User Two
10 - password: $2b$12$C4E7p9kXQKoM3W8Jp5s1zOtk0D2q7T2zJtOjVg22uW/1sLp7B4sGW
11 - cookie:
12 - expiry_days: 30
13 - key: some_signature_key
14 - name: my_auth_cookie
15 - preauthorized:
24 + password: abc # Will be hashed automatically
25 + pre-authorized:
16 26 emails:
17 - - admin@example.com
18 - - manager@example.com
27 + - admin@example.com
28 + - manager@example.com

streamlit_authentication_with_yaml.py

@@ -1,36 +1,78 @@
1 - import streamlit as st # 匯入 streamlit 模組
2 - import streamlit_authenticator as stauth # 匯入 streamlit_authenticator 模組
3 - import yaml # 匯入 yaml 模組
4 - from yaml.loader import SafeLoader # 從 yaml.loader 匯入 SafeLoader
1 + import pretty_errors
2 + import streamlit as st
3 + import streamlit_authenticator as stauth
4 + import yaml
5 + from yaml.loader import SafeLoader
5 6
6 - with open("./config.yaml") as file: # 開啟名為 config.yaml 的檔案
7 - config = yaml.load(file, Loader=SafeLoader) # 使用 SafeLoader 從檔案讀取配置資訊並存入 config 變數中
8 -
9 - authenticator = stauth.Authenticate( # 建立一個 stauth.Authenticate 的實例 authenticator
10 - config["credentials"], # 使用配置中的 credentials 屬性
11 - config["cookie"]["name"], # 使用配置中的 cookie 的 name 屬性
12 - config["cookie"]["key"], # 使用配置中的 cookie 的 key 屬性
13 - config["cookie"]["expiry_days"], # 使用配置中的 cookie 的 expiry_days 屬性
14 - config["preauthorized"], # 使用配置中的 preauthorized 屬性
7 + pretty_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,
15 13 )
16 14
17 - authenticator.login("Login", "main") # 進行登入驗證,並顯示 "Login" 按鈕,連接到 "main"
18 -
19 - if st.session_state["authentication_status"]: # 如果驗證狀態為真
20 - authenticator.logout("Logout", "main", key="unique_key") # 顯示 "Logout" 按鈕,連接到 "main",並使用特定的 key
21 - st.write(f'Welcome *{st.session_state["name"]}*') # 顯示歡迎訊息,使用 st.session_state 中的 name 屬性
22 - st.title("Some content") # 顯示標題為 "Some content"
23 - elif st.session_state["authentication_status"] is False: # 如果驗證狀態為假
24 - st.error("Username/password is incorrect") # 顯示錯誤訊息,提示使用者帳號或密碼不正確
25 - elif st.session_state["authentication_status"] is None: # 如果驗證狀態為空
26 - st.warning("Please enter your username and password") # 顯示警告訊息,提示使用者輸入帳號和密碼
15 + # 從 config.yaml 檔案中讀取設定
16 + try:
17 + with open("./config.yaml") as file:
18 + config = yaml.load(file, Loader=SafeLoader)
19 + except Exception as e:
20 + st.error(f"讀取 config.yaml 檔案時發生錯誤: {e}")
27 21
28 - if st.session_state["authentication_status"]: # 如果驗證狀態為真
22 + # 確保配置文件讀取成功並包含必要的鍵
23 + if config and "credentials" in config and "cookie" in config:
24 + # 檢查 credentials 結構
29 25 try:
30 - if authenticator.reset_password(st.session_state["username"], "Reset password"): # 嘗試重設密碼,並顯示 "Reset password" 按鈕
31 - st.success("Password modified successfully") # 顯示成功訊息,提示密碼修改成功
32 - except Exception as e: # 處理可能的例外狀況
33 - st.error(e) # 顯示錯誤訊息,提示發生了例外狀況
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}")
35 + else:
36 + st.error("配置文件不完整或無法讀取")
37 +
38 + # User Authentication with Authenticator
39 + try:
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 + )
47 + except Exception as e:
48 + st.error(f"初始化 Authenticator 時發生錯誤: {e}")
49 +
50 + # Attempt User Login with Authenticator
51 + try:
52 + authenticator.login(
53 + fields={
54 + "Form name": "登入",
55 + "Username": "使用者名稱",
56 + "Password": "密碼",
57 + "Login": "登入",
58 + },
59 + location="main",
60 + )
61 + except Exception as e:
62 + st.error(f"登入時發生錯誤: {e}")
63 +
64 + # 根據驗證的情況執行不同的操作
65 + if 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)
72 + elif st.session_state.get("authentication_status") is False:
73 + st.error("使用者名稱/密碼不正確")
74 + elif st.session_state.get("authentication_status") is None:
75 + st.warning("請輸入你的使用者名稱和密碼")
34 76
35 - with open("./config.yaml", "w") as file: # 開啟名為 config.yaml 的檔案,以寫入模式
36 - yaml.dump(config, file, default_flow_style=False) # 將配置資訊寫入檔案,不使用預設流風格
77 + with open("./config.yaml", "w") as file:
78 + yaml.dump(config, file, default_flow_style=False)

timmy a révisé ce gist 2 years ago. Aller à la révision

1 file changed, 18 insertions

config.yaml(fichier créé)

@@ -0,0 +1,18 @@
1 + credentials:
2 + usernames:
3 + user1:
4 + email: user1@example.com
5 + name: User One
6 + password: $2b$12$RVn2UdS.KJiM24xT3Vb9fOIEv4S3hvP6Pjw2xzaP5d/fDq1U2pX2e
7 + user2:
8 + email: user2@example.com
9 + name: User Two
10 + password: $2b$12$C4E7p9kXQKoM3W8Jp5s1zOtk0D2q7T2zJtOjVg22uW/1sLp7B4sGW
11 + cookie:
12 + expiry_days: 30
13 + key: some_signature_key
14 + name: my_auth_cookie
15 + preauthorized:
16 + emails:
17 + - admin@example.com
18 + - manager@example.com

timmy a révisé ce gist 2 years ago. Aller à la révision

1 file changed, 36 insertions

streamlit_authentication_with_yaml.py(fichier créé)

@@ -0,0 +1,36 @@
1 + import streamlit as st # 匯入 streamlit 模組
2 + import streamlit_authenticator as stauth # 匯入 streamlit_authenticator 模組
3 + import yaml # 匯入 yaml 模組
4 + from yaml.loader import SafeLoader # 從 yaml.loader 匯入 SafeLoader
5 +
6 + with open("./config.yaml") as file: # 開啟名為 config.yaml 的檔案
7 + config = yaml.load(file, Loader=SafeLoader) # 使用 SafeLoader 從檔案讀取配置資訊並存入 config 變數中
8 +
9 + authenticator = stauth.Authenticate( # 建立一個 stauth.Authenticate 的實例 authenticator
10 + config["credentials"], # 使用配置中的 credentials 屬性
11 + config["cookie"]["name"], # 使用配置中的 cookie 的 name 屬性
12 + config["cookie"]["key"], # 使用配置中的 cookie 的 key 屬性
13 + config["cookie"]["expiry_days"], # 使用配置中的 cookie 的 expiry_days 屬性
14 + config["preauthorized"], # 使用配置中的 preauthorized 屬性
15 + )
16 +
17 + authenticator.login("Login", "main") # 進行登入驗證,並顯示 "Login" 按鈕,連接到 "main"
18 +
19 + if st.session_state["authentication_status"]: # 如果驗證狀態為真
20 + authenticator.logout("Logout", "main", key="unique_key") # 顯示 "Logout" 按鈕,連接到 "main",並使用特定的 key
21 + st.write(f'Welcome *{st.session_state["name"]}*') # 顯示歡迎訊息,使用 st.session_state 中的 name 屬性
22 + st.title("Some content") # 顯示標題為 "Some content"
23 + elif st.session_state["authentication_status"] is False: # 如果驗證狀態為假
24 + st.error("Username/password is incorrect") # 顯示錯誤訊息,提示使用者帳號或密碼不正確
25 + elif st.session_state["authentication_status"] is None: # 如果驗證狀態為空
26 + st.warning("Please enter your username and password") # 顯示警告訊息,提示使用者輸入帳號和密碼
27 +
28 + if st.session_state["authentication_status"]: # 如果驗證狀態為真
29 + try:
30 + if authenticator.reset_password(st.session_state["username"], "Reset password"): # 嘗試重設密碼,並顯示 "Reset password" 按鈕
31 + st.success("Password modified successfully") # 顯示成功訊息,提示密碼修改成功
32 + except Exception as e: # 處理可能的例外狀況
33 + st.error(e) # 顯示錯誤訊息,提示發生了例外狀況
34 +
35 + with open("./config.yaml", "w") as file: # 開啟名為 config.yaml 的檔案,以寫入模式
36 + yaml.dump(config, file, default_flow_style=False) # 將配置資訊寫入檔案,不使用預設流風格
Plus récent Plus ancien