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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import datetime
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import joblib
|
| 5 |
+
from sklearn.cluster import HDBSCAN
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
# --- 1. 載入模型與歷史資料 ---
|
| 9 |
+
try:
|
| 10 |
+
le_action = joblib.load('le_action.pkl')
|
| 11 |
+
le_ip = joblib.load('le_ip.pkl')
|
| 12 |
+
|
| 13 |
+
baseline_df = pd.read_csv('baseline_logs.csv')
|
| 14 |
+
baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
|
| 15 |
+
|
| 16 |
+
baseline_df['month'] = baseline_df['timestamp'].dt.month
|
| 17 |
+
baseline_df['day'] = baseline_df['timestamp'].dt.day
|
| 18 |
+
baseline_df['hour'] = baseline_df['timestamp'].dt.hour
|
| 19 |
+
|
| 20 |
+
baseline_X = np.column_stack((
|
| 21 |
+
baseline_df['month'].values,
|
| 22 |
+
baseline_df['day'].values,
|
| 23 |
+
baseline_df['hour'].values,
|
| 24 |
+
le_ip.transform(baseline_df['ip_address'].values),
|
| 25 |
+
le_action.transform(baseline_df['action'].values)
|
| 26 |
+
))
|
| 27 |
+
|
| 28 |
+
AI_READY = True
|
| 29 |
+
print("✅ AI 模組與歷史基準資料載入成功!")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
AI_READY = False
|
| 32 |
+
print(f"⚠️ AI 模組載入失敗,請確認檔案。錯誤: {e}")
|
| 33 |
+
|
| 34 |
+
USER_DB = {
|
| 35 |
+
"student": ["1234", "學生", "同學"],
|
| 36 |
+
"admin": ["1234", "管理", "管理員"],
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
log_history = []
|
| 40 |
+
|
| 41 |
+
# --- 3. 核心邏輯與真實 HDBSCAN 異常偵測 ---
|
| 42 |
+
def check_anomaly(ip, action, log_time, overall_w, time_w, ip_w, dev_w):
|
| 43 |
+
if not AI_READY: return "success"
|
| 44 |
+
if action in ["login_attempt", "logout"]: return "success"
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
clean_ip = ip.split(" ")[0]
|
| 48 |
+
ip_code = le_ip.transform([clean_ip])[0]
|
| 49 |
+
action_code = le_action.transform([action])[0]
|
| 50 |
+
|
| 51 |
+
current_time = pd.to_datetime(log_time)
|
| 52 |
+
current_month = current_time.month
|
| 53 |
+
current_day = current_time.day
|
| 54 |
+
current_hour = current_time.hour
|
| 55 |
+
|
| 56 |
+
action_scale = (dev_w / 100.0) * 100.0
|
| 57 |
+
|
| 58 |
+
scaled_baseline = baseline_X.copy().astype(float)
|
| 59 |
+
scaled_baseline[:, 0] *= (time_w / 100.0) * 10.0
|
| 60 |
+
scaled_baseline[:, 1] *= (time_w / 100.0) * 0.5
|
| 61 |
+
scaled_baseline[:, 2] *= (time_w / 100.0) * 2.0
|
| 62 |
+
scaled_baseline[:, 3] *= (ip_w / 100.0) * 10.0
|
| 63 |
+
scaled_baseline[:, 4] *= action_scale
|
| 64 |
+
|
| 65 |
+
new_data_point = np.array([[
|
| 66 |
+
current_month * (time_w / 100.0) * 10.0,
|
| 67 |
+
current_day * (time_w / 100.0) * 0.5,
|
| 68 |
+
current_hour * (time_w / 100.0) * 2.0,
|
| 69 |
+
ip_code * (ip_w / 100.0) * 10.0,
|
| 70 |
+
action_code * action_scale
|
| 71 |
+
]])
|
| 72 |
+
|
| 73 |
+
combined_X = np.vstack((scaled_baseline, new_data_point))
|
| 74 |
+
strictness = max(2, int(2 + (overall_w / 100.0) * 4))
|
| 75 |
+
|
| 76 |
+
model = HDBSCAN(min_cluster_size=strictness, min_samples=2)
|
| 77 |
+
clusters = model.fit_predict(combined_X)
|
| 78 |
+
|
| 79 |
+
if clusters[-1] == -1: return "⚠️異常_作息或行為不符"
|
| 80 |
+
else: return "success"
|
| 81 |
+
except ValueError:
|
| 82 |
+
return "⚠️異常_未知特徵"
|
| 83 |
+
|
| 84 |
+
def record_log(ip, cookie, account, role, action, status, time_mode, custom_time, ow, tw, iw, dw):
|
| 85 |
+
global baseline_X
|
| 86 |
+
if time_mode == "自訂時間 (模擬過去/未來)" and custom_time.strip() != "":
|
| 87 |
+
log_time = custom_time
|
| 88 |
+
else:
|
| 89 |
+
tw_tz = datetime.timezone(datetime.timedelta(hours=8))
|
| 90 |
+
log_time = datetime.datetime.now(tw_tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 91 |
+
|
| 92 |
+
if status == "success":
|
| 93 |
+
ai_judgment = check_anomaly(ip, action, log_time, ow, tw, iw, dw)
|
| 94 |
+
if ai_judgment != "success": status = ai_judgment
|
| 95 |
+
|
| 96 |
+
new_log = {
|
| 97 |
+
"timestamp": log_time, "ip_address": ip, "cookie_id": cookie,
|
| 98 |
+
"account": account, "role": role, "action": action, "status": status
|
| 99 |
+
}
|
| 100 |
+
log_history.insert(0, new_log)
|
| 101 |
+
|
| 102 |
+
if status == "success" and AI_READY:
|
| 103 |
+
try:
|
| 104 |
+
pd.DataFrame([new_log]).to_csv('baseline_logs.csv', mode='a', header=False, index=False, encoding='utf-8-sig')
|
| 105 |
+
|
| 106 |
+
current_time = pd.to_datetime(log_time)
|
| 107 |
+
clean_ip = ip.split(" ")[0]
|
| 108 |
+
new_row = np.array([[
|
| 109 |
+
current_time.month,
|
| 110 |
+
current_time.day,
|
| 111 |
+
current_time.hour,
|
| 112 |
+
le_ip.transform([clean_ip])[0],
|
| 113 |
+
le_action.transform([action])[0]
|
| 114 |
+
]])
|
| 115 |
+
baseline_X = np.vstack((baseline_X, new_row))
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"寫入 baseline 發生錯誤: {e}")
|
| 118 |
+
|
| 119 |
+
return pd.DataFrame(log_history)
|
| 120 |
+
|
| 121 |
+
def fast_login(target_account, ip, cookie, time_mode, custom_time, ow, tw, iw, dw):
|
| 122 |
+
role, name = USER_DB[target_account][1], USER_DB[target_account][2]
|
| 123 |
+
df = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 124 |
+
|
| 125 |
+
welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938 (⚡快速登入模式)"
|
| 126 |
+
is_student = (role == "學生")
|
| 127 |
+
is_admin = (role == "管理")
|
| 128 |
+
|
| 129 |
+
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_student), gr.update(visible=is_admin), "", welcome_msg, df, target_account
|
| 130 |
+
|
| 131 |
+
def process_login(ip, cookie, account, password, captcha, time_mode, custom_time, ow, tw, iw, dw):
|
| 132 |
+
valid_captcha = "FEIK"
|
| 133 |
+
def fail_response(msg, df):
|
| 134 |
+
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), msg, gr.update(), df
|
| 135 |
+
|
| 136 |
+
if account not in USER_DB:
|
| 137 |
+
df = record_log(ip, cookie, account, "Unknown", "login_attempt", "failed_no_account", time_mode, custom_time, ow, tw, iw, dw)
|
| 138 |
+
return fail_response("帳號不存在!", df)
|
| 139 |
+
|
| 140 |
+
role, name = USER_DB[account][1], USER_DB[account][2]
|
| 141 |
+
|
| 142 |
+
if captcha.upper() != valid_captcha:
|
| 143 |
+
df = record_log(ip, cookie, account, role, "login_attempt", "failed_captcha", time_mode, custom_time, ow, tw, iw, dw)
|
| 144 |
+
return fail_response("驗證碼錯誤!", df)
|
| 145 |
+
|
| 146 |
+
if USER_DB[account][0] == password:
|
| 147 |
+
welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938"
|
| 148 |
+
df = record_log(ip, cookie, account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 149 |
+
is_student = (role == "學生")
|
| 150 |
+
is_admin = (role == "管理")
|
| 151 |
+
|
| 152 |
+
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_student), gr.update(visible=is_admin), "", welcome_msg, df
|
| 153 |
+
|
| 154 |
+
df = record_log(ip, cookie, account, role, "login_attempt", "failed_password", time_mode, custom_time, ow, tw, iw, dw)
|
| 155 |
+
return fail_response("密碼錯誤!", df)
|
| 156 |
+
|
| 157 |
+
def simulate_click(ip, cookie, account, button_name, time_mode, custom_time, ow, tw, iw, dw):
|
| 158 |
+
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 159 |
+
return record_log(ip, cookie, account, role, button_name, "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 160 |
+
|
| 161 |
+
# 🌟 新增:管理員專用的快速測試函式 (強制寫入指定的時間)
|
| 162 |
+
def test_anomaly(ip, cookie, account, action_name, test_time_str, ow, tw, iw, dw):
|
| 163 |
+
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 164 |
+
# 強制將 time_mode 設為自訂,並傳入測試的具體時間
|
| 165 |
+
return record_log(ip, cookie, account, role, action_name, "success", "自訂時間 (模擬過去/未來)", test_time_str, ow, tw, iw, dw)
|
| 166 |
+
|
| 167 |
+
def logout(ip, cookie, account, time_mode, custom_time, ow, tw, iw, dw):
|
| 168 |
+
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 169 |
+
df = record_log(ip, cookie, account, role, "logout", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 170 |
+
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "", "", "", "", df
|
| 171 |
+
|
| 172 |
+
def toggle_time_input(mode):
|
| 173 |
+
return gr.update(visible=(mode == "自訂時間 (模擬過去/未來)"))
|
| 174 |
+
|
| 175 |
+
# --- 4. UI 介面設計 ---
|
| 176 |
+
custom_css = """
|
| 177 |
+
.mock-panel { background-color: var(--background-fill-secondary); padding: 15px; border-radius: 8px; border: 1px dashed var(--border-color-primary); }
|
| 178 |
+
.login-container { max-width: 500px; margin: 0 auto; padding: 20px; }
|
| 179 |
+
.ntut-title { color: #d9534f; font-size: 22px; font-weight: bold; text-align: center; margin-bottom: 20px;}
|
| 180 |
+
.weight-card { padding: 10px; background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
with gr.Blocks(title="模擬校園入口與資安防護系統", css=custom_css) as demo:
|
| 184 |
+
with gr.Row():
|
| 185 |
+
with gr.Column(scale=1, elem_classes="mock-panel"):
|
| 186 |
+
gr.Markdown("### ⚙️ 環境變數模擬器")
|
| 187 |
+
mock_ip = gr.Dropdown(choices=["140.124.71.55 (校內預設)", "140.124.18.22 (宿舍)", "45.33.22.11 (國外異常IP)"], value="140.124.71.55 (校內預設)", allow_custom_value=True, label="模擬來源 IP")
|
| 188 |
+
mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
|
| 189 |
+
gr.Markdown("---")
|
| 190 |
+
time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
|
| 191 |
+
custom_time_input = gr.Textbox(label="輸入自訂時間", placeholder="格式: YYYY-MM-DD HH:MM:SS", value="2026-03-17 03:00:00", visible=False)
|
| 192 |
+
gr.Markdown("---")
|
| 193 |
+
gr.Markdown("### 📊 即時 Log 與 AI 判定區")
|
| 194 |
+
log_display = gr.Dataframe(headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"], datatype=["str", "str", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
|
| 195 |
+
|
| 196 |
+
with gr.Column(scale=2):
|
| 197 |
+
with gr.Column(visible=True, elem_classes="login-container") as login_view:
|
| 198 |
+
gr.Markdown("<div class='ntut-title'>校園入口網站 Taipei Tech Portal</div>")
|
| 199 |
+
login_msg = gr.Markdown(value="", visible=True)
|
| 200 |
+
with gr.Row(): acc_input = gr.Textbox(label="使用者帳號 (Account)", placeholder="student or admin")
|
| 201 |
+
with gr.Row(): pwd_input = gr.Textbox(label="使用者密碼 (Password)", type="password", placeholder="password : 1234")
|
| 202 |
+
with gr.Row(): gr.HTML("<div style='background:var(--background-fill-secondary); color:var(--body-text-color); padding:10px; font-weight:bold; letter-spacing: 3px; border:1px solid var(--border-color-primary); text-align:center;'>F E I K</div>")
|
| 203 |
+
with gr.Row(): captcha_input = gr.Textbox(label="請輸入驗證碼 (Keyin Code)")
|
| 204 |
+
login_btn = gr.Button("登入 Login", variant="primary")
|
| 205 |
+
|
| 206 |
+
gr.Markdown("---")
|
| 207 |
+
gr.Markdown("<div style='text-align:center; color:gray; font-size: 0.9em;'>🛠️ 開發與測試專用捷徑</div>")
|
| 208 |
+
with gr.Row():
|
| 209 |
+
btn_fast_student = gr.Button("🚀 快速登入 (學生)", variant="secondary")
|
| 210 |
+
btn_fast_admin = gr.Button("🚀 快速登入 (管理員)", variant="secondary")
|
| 211 |
+
|
| 212 |
+
with gr.Column(visible=False) as dashboard_view:
|
| 213 |
+
with gr.Row():
|
| 214 |
+
gr.Markdown("### 資訊系統")
|
| 215 |
+
welcome_text = gr.Markdown(value="", elem_classes="text-right")
|
| 216 |
+
logout_btn = gr.Button("登出", size="sm")
|
| 217 |
+
gr.Markdown("---")
|
| 218 |
+
|
| 219 |
+
with gr.Column(visible=False) as student_view:
|
| 220 |
+
btn_switch_admin = gr.Button("🔄 快速切換為管理員 (Admin) 視角", size="sm", variant="secondary")
|
| 221 |
+
with gr.Accordion("▼ 1. 教務系統", open=True):
|
| 222 |
+
with gr.Row(): btn_eval = gr.Button("▶ 期末網路教學評量", size="sm"); btn_pre_select = gr.Button("▶ 期末網路預選系統", size="sm"); btn_add_drop = gr.Button("▶ 開學後加退選系統", size="sm")
|
| 223 |
+
with gr.Row(): btn_istudy = gr.Button("▶ 北科i學園PLUS", size="sm"); btn_card = gr.Button("▶ 學生證掛失及補發系統", size="sm"); btn_course = gr.Button("▶ 課程系統", size="sm")
|
| 224 |
+
with gr.Row(): btn_score = gr.Button("▶ 學業成績查詢系統", size="sm")
|
| 225 |
+
with gr.Accordion("▼ 2. 學務系統", open=True):
|
| 226 |
+
with gr.Row(): btn_leave = gr.Button("▶ 學生請假系統", size="sm"); btn_dorm = gr.Button("▶ 學生宿舍登錄(抽籤)系統", size="sm"); btn_scholarship = gr.Button("▶ 獎助學金申請系統", size="sm")
|
| 227 |
+
with gr.Accordion("▼ 3. 資訊服務", open=True):
|
| 228 |
+
with gr.Row(): btn_webmail = gr.Button("▶ 網路郵局 WebMail", size="sm"); btn_vdesk = gr.Button("▶ 北科軟體雲", size="sm")
|
| 229 |
+
with gr.Accordion("▼ 惡意操作測試區", open=True):
|
| 230 |
+
btn_hack_score = gr.Button("💀 嘗試偷改成績 (SQL Injection)", variant="stop", size="sm")
|
| 231 |
+
|
| 232 |
+
with gr.Column(visible=False) as admin_view:
|
| 233 |
+
btn_switch_student = gr.Button("🔄 快速切換為學生 (Student) 視角", size="sm", variant="secondary")
|
| 234 |
+
with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):
|
| 235 |
+
gr.Markdown("<span style='color:gray; font-size:0.9em;'>手動輸入 0~100 的數值。提高強度會增加誤報率,但能更有效攔截新型攻擊。</span>")
|
| 236 |
+
with gr.Row():
|
| 237 |
+
overall_weight = gr.Number(label="總體防護強度 (%)", value=75, minimum=0, maximum=100)
|
| 238 |
+
time_weight = gr.Number(label="時間特徵權重 (%)", value=80, minimum=0, maximum=100)
|
| 239 |
+
with gr.Row():
|
| 240 |
+
ip_weight = gr.Number(label="IP 聲譽權重 (%)", value=65, minimum=0, maximum=100)
|
| 241 |
+
device_weight = gr.Number(label="裝置指紋/行為權重 (%)", value=45, minimum=0, maximum=100)
|
| 242 |
+
|
| 243 |
+
# 🌟 新增:HDBSCAN 自動化測試面板
|
| 244 |
+
with gr.Accordion("▼ HDBSCAN 異常辨識自動化測試區", open=True, elem_classes="weight-card"):
|
| 245 |
+
gr.Markdown("<span style='color:gray; font-size:0.9em;'>點擊按鈕將直接以指定時間點執行該系統的操作,結果將顯示於左側 Log 區。</span>")
|
| 246 |
+
|
| 247 |
+
gr.Markdown("#### 1. 選課相關系統 (具備強烈季節性)")
|
| 248 |
+
with gr.Row():
|
| 249 |
+
t_pre_sel_norm = gr.Button("✅ 正常: 期末網路預選系統 (06-10 22:00)", size="sm")
|
| 250 |
+
t_pre_sel_anom = gr.Button("⚠️ 異常: 期末網路預選系統 (10-15 14:00)", size="sm")
|
| 251 |
+
with gr.Row():
|
| 252 |
+
t_course_norm = gr.Button("✅ 正常: 課程系統 (02-15 16:00)", size="sm")
|
| 253 |
+
t_course_anom = gr.Button("⚠️ 異常: 課程系統 (05-20 09:00)", size="sm")
|
| 254 |
+
with gr.Row():
|
| 255 |
+
t_add_drop_norm = gr.Button("✅ 正常: 開學後加退選系統 (09-15 08:00)", size="sm")
|
| 256 |
+
t_add_drop_anom = gr.Button("⚠️ 異常: 開學後加退選系統 (04-10 21:00)", size="sm")
|
| 257 |
+
|
| 258 |
+
gr.Markdown("#### 2. 期末與成績相關 (具備週期性)")
|
| 259 |
+
with gr.Row():
|
| 260 |
+
t_eval_norm = gr.Button("✅ 正常: 期末網路教學評量 (12-20 23:00)", size="sm")
|
| 261 |
+
t_eval_anom = gr.Button("⚠️ 異常: 期末網路教學評量 (03-05 11:00)", size="sm")
|
| 262 |
+
with gr.Row():
|
| 263 |
+
t_score_norm = gr.Button("✅ 正常: 學業成績查詢系統 (04-20 11:00)", size="sm")
|
| 264 |
+
t_score_anom = gr.Button("⚠️ 異常: 學業成績查詢系統 (08-15 10:00)", size="sm")
|
| 265 |
+
|
| 266 |
+
gr.Markdown("#### 3. 校務與行政服務 (生活與常規)")
|
| 267 |
+
with gr.Row():
|
| 268 |
+
t_dorm_norm = gr.Button("✅ 正常: 學生宿舍登錄(抽籤)系統 (07-25 16:00)", size="sm")
|
| 269 |
+
t_dorm_anom = gr.Button("⚠️ 異常: 學生宿舍登錄(抽籤)系統 (11-15 14:00)", size="sm")
|
| 270 |
+
with gr.Row():
|
| 271 |
+
t_schol_norm = gr.Button("✅ 正常: 獎助學金申請系統 (03-15 12:00)", size="sm")
|
| 272 |
+
t_schol_anom = gr.Button("⚠️ 異常: 獎助學金申請系統 (08-10 05:00)", size="sm")
|
| 273 |
+
with gr.Row():
|
| 274 |
+
t_card_norm = gr.Button("✅ 正常: 學生證掛失 (任何月份 16:00)", size="sm")
|
| 275 |
+
t_card_anom = gr.Button("⚠️ 異常: 學生證掛失 (任何月份 04:00)", size="sm")
|
| 276 |
+
|
| 277 |
+
gr.Markdown("#### 4. 學習與日常輔助系統 (具備作息規律)")
|
| 278 |
+
with gr.Row():
|
| 279 |
+
t_istudy_norm = gr.Button("✅ 正常: 北科i學園PLUS (03-20 13:00)", size="sm")
|
| 280 |
+
t_istudy_anom = gr.Button("⚠️ 異常: 北科i學園PLUS (06-29 03:00)", size="sm")
|
| 281 |
+
with gr.Row():
|
| 282 |
+
t_leave_norm = gr.Button("✅ 正常: 學生請假系統 (10-05 08:00)", size="sm")
|
| 283 |
+
t_leave_anom = gr.Button("⚠️ 異常: 學生請假系統 (週日 02:00)", size="sm")
|
| 284 |
+
with gr.Row():
|
| 285 |
+
t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/WebMail (11-10 10:00)", size="sm")
|
| 286 |
+
t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/WebMail (深夜 04:00)", size="sm")
|
| 287 |
+
|
| 288 |
+
# --- 綁定事件 ---
|
| 289 |
+
time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)
|
| 290 |
+
|
| 291 |
+
weight_inputs = [overall_weight, time_weight, ip_weight, device_weight]
|
| 292 |
+
|
| 293 |
+
login_btn.click(
|
| 294 |
+
fn=process_login,
|
| 295 |
+
inputs=[mock_ip, mock_cookie, acc_input, pwd_input, captcha_input, time_mode, custom_time_input] + weight_inputs,
|
| 296 |
+
outputs=[login_view, dashboard_view, student_view, admin_view, login_msg, welcome_text, log_display]
|
| 297 |
+
)
|
| 298 |
+
logout_btn.click(
|
| 299 |
+
fn=logout,
|
| 300 |
+
inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
|
| 301 |
+
outputs=[login_view, dashboard_view, student_view, admin_view, acc_input, pwd_input, captcha_input, login_msg, log_display]
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
fast_inputs = [mock_ip, mock_cookie, time_mode, custom_time_input] + weight_inputs
|
| 305 |
+
fast_outputs = [login_view, dashboard_view, student_view, admin_view, login_msg, welcome_text, log_display, acc_input]
|
| 306 |
+
|
| 307 |
+
btn_fast_student.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("student", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
|
| 308 |
+
btn_fast_admin.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("admin", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
|
| 309 |
+
btn_switch_admin.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("admin", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
|
| 310 |
+
btn_switch_student.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("student", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
|
| 311 |
+
|
| 312 |
+
action_mapping = [
|
| 313 |
+
(btn_eval, "click_eval_system"), (btn_pre_select, "click_pre_select_system"),
|
| 314 |
+
(btn_add_drop, "click_add_drop_system"), (btn_istudy, "click_istudy"),
|
| 315 |
+
(btn_card, "click_card_loss"), (btn_course, "click_course_system"),
|
| 316 |
+
(btn_score, "click_score_query"), (btn_leave, "click_leave_system"),
|
| 317 |
+
(btn_dorm, "click_dorm_system"), (btn_scholarship, "click_scholarship"),
|
| 318 |
+
(btn_webmail, "click_webmail"), (btn_vdesk, "click_vdesk"),
|
| 319 |
+
(btn_hack_score, "malicious_sql_injection")
|
| 320 |
+
]
|
| 321 |
+
|
| 322 |
+
for btn, action_name in action_mapping:
|
| 323 |
+
btn.click(
|
| 324 |
+
fn=lambda ip, c, acc, t_mode, t_custom, ow, tw, iw, dw, n=action_name: simulate_click(ip, c, acc, n, t_mode, t_custom, ow, tw, iw, dw),
|
| 325 |
+
inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
|
| 326 |
+
outputs=[log_display]
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
# 🌟 綁定自動化測試按鈕 (帶入固定時間字串)
|
| 330 |
+
test_mapping = [
|
| 331 |
+
# 1. 選課相關
|
| 332 |
+
(t_pre_sel_norm, "click_pre_select_system", "2026-06-10 22:00:00"),
|
| 333 |
+
(t_pre_sel_anom, "click_pre_select_system", "2026-10-15 14:00:00"),
|
| 334 |
+
(t_course_norm, "click_course_system", "2026-02-15 16:00:00"),
|
| 335 |
+
(t_course_anom, "click_course_system", "2026-05-20 09:00:00"),
|
| 336 |
+
(t_add_drop_norm, "click_add_drop_system", "2026-09-15 08:00:00"),
|
| 337 |
+
(t_add_drop_anom, "click_add_drop_system", "2026-04-10 21:00:00"),
|
| 338 |
+
|
| 339 |
+
# 2. 期末與成績
|
| 340 |
+
(t_eval_norm, "click_eval_system", "2026-12-20 23:00:00"),
|
| 341 |
+
(t_eval_anom, "click_eval_system", "2026-03-05 11:00:00"),
|
| 342 |
+
(t_score_norm, "click_score_query", "2026-04-20 11:00:00"),
|
| 343 |
+
(t_score_anom, "click_score_query", "2026-08-15 10:00:00"),
|
| 344 |
+
|
| 345 |
+
# 3. 校務與行政
|
| 346 |
+
(t_dorm_norm, "click_dorm_system", "2026-07-25 16:00:00"),
|
| 347 |
+
(t_dorm_anom, "click_dorm_system", "2026-11-15 14:00:00"),
|
| 348 |
+
(t_schol_norm, "click_scholarship", "2026-03-15 12:00:00"),
|
| 349 |
+
(t_schol_anom, "click_scholarship", "2026-08-10 05:00:00"),
|
| 350 |
+
(t_card_norm, "click_card_loss", "2026-10-01 16:00:00"), # 任何月份,取 10 月代表
|
| 351 |
+
(t_card_anom, "click_card_loss", "2026-10-01 04:00:00"),
|
| 352 |
+
|
| 353 |
+
# 4. 學習與日常
|
| 354 |
+
(t_istudy_norm, "click_istudy", "2026-03-20 13:00:00"),
|
| 355 |
+
(t_istudy_anom, "click_istudy", "2026-06-29 03:00:00"),
|
| 356 |
+
(t_leave_norm, "click_leave_system", "2026-10-05 08:00:00"),
|
| 357 |
+
(t_leave_anom, "click_leave_system", "2026-10-11 02:00:00"), # 10/11 是週日
|
| 358 |
+
(t_vdesk_norm, "click_vdesk", "2026-11-10 10:00:00"),
|
| 359 |
+
(t_vdesk_anom, "click_vdesk", "2026-11-10 04:00:00")
|
| 360 |
+
]
|
| 361 |
+
|
| 362 |
+
for btn, action_name, test_time_str in test_mapping:
|
| 363 |
+
btn.click(
|
| 364 |
+
fn=lambda ip, c, acc, ow, tw, iw, dw, n=action_name, t_str=test_time_str: test_anomaly(ip, c, acc, n, t_str, ow, tw, iw, dw),
|
| 365 |
+
inputs=[mock_ip, mock_cookie, acc_input, overall_weight, time_weight, ip_weight, device_weight],
|
| 366 |
+
outputs=[log_display]
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
if __name__ == "__main__":
|
| 370 |
+
demo.launch()
|