今日目標是學習如何在資料庫中建立不同角色,並透過權限控管確保醫療資料安全,避免未授權使用者存取、修改或刪除敏感資料。
一、理論重點
二、案例分享
在某家大型醫院的電子病歷系統中,醫師可以查詢與修改病人的診斷與治療計畫,護理師只能查看病人的用藥與生命徵象資料,而病人透過病患入口網站只能查詢自己的病歷。這些權限透過 MySQL 的使用者帳號與權限設定(例如 GRANT SELECT, UPDATE ON medical_records TO 'doctor'@'%')來控管,確保每個角色只能存取與操作其被授權的資料,有效降低敏感資訊外洩的風險。
三、簡單程式示範
import mysql.connector
from cryptography.fernet import Fernet
# 建立加密器
key = Fernet.generate_key()
cipher = Fernet(key)
# 連線到 MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="我的密碼",
database="health"
)
cur = conn.cursor()
# 建立使用者與權限
cur.execute("CREATE USER IF NOT EXISTS 'doctor'@'localhost' IDENTIFIED BY 'docpass'")
cur.execute("CREATE USER IF NOT EXISTS 'nurse'@'localhost' IDENTIFIED BY 'nursepass'")
cur.execute("CREATE USER IF NOT EXISTS 'patient'@'localhost' IDENTIFIED BY 'patientpass'")
# 建立病歷資料表
cur.execute("DROP TABLE IF EXISTS patient_records")
cur.execute("""
CREATE TABLE patient_records (
id INT AUTO_INCREMENT PRIMARY KEY,
patient_name VARBINARY(255),
diagnosis VARBINARY(255),
vitals VARBINARY(255)
)
""")
# 分配權限
cur.execute("GRANT SELECT, UPDATE ON health.patient_records TO 'doctor'@'localhost'")
cur.execute("GRANT SELECT, INSERT ON health.patient_records TO 'nurse'@'localhost'")
cur.execute("GRANT SELECT ON health.patient_records TO 'patient'@'localhost'")
conn.commit()
# 插入加密資料(護理師角色)
patient_name = "Alice"
diagnosis = "Diabetes Type 2"
vitals = "BP:120/80, HR:72"
enc_name = cipher.encrypt(patient_name.encode())
enc_diag = cipher.encrypt(diagnosis.encode())
enc_vitals = cipher.encrypt(vitals.encode())
cur.execute(
"INSERT INTO patient_records (patient_name, diagnosis, vitals) VALUES (%s, %s, %s)",
(enc_name, enc_diag, enc_vitals)
)
conn.commit()
# 醫師查詢資料並解密
cur.execute("SELECT id, patient_name, diagnosis, vitals FROM patient_records")
for row in cur.fetchall():
dec_name = cipher.decrypt(row[1]).decode()
dec_diag = cipher.decrypt(row[2]).decode()
dec_vitals = cipher.decrypt(row[3]).decode()
print(f"病患 {dec_name} - 診斷: {dec_diag} - 生命徵象: {dec_vitals}")
conn.close()
print("資料庫權限控管 + 加密 Demo 完成!")
程式先建立一個 Fernet 加密器,確保病歷資料在儲存到資料庫前被加密;接著透過 MySQL 建立不同角色的使用者(醫師、護理師、病人),並分配不同權限。資料插入時,病患姓名、診斷與生命徵象先加密再存入資料表,醫師查詢資料時再解密顯示,完整示範了敏感資料加密與角色權限控管結合的應用,達到保護醫療資訊安全的目的。