首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

利用控制項 Tag 屬性實現靈活的軟體權限控制機制

     編輯:關於SqlServer

設計概念

傳統權限控制多透過 ActionList 對應資料庫權限表。本文分享利用每個控制項固有的 Tag 屬性(預設值 0,表示無需權限控制)實現精細權限管理的實作模式。

實作步驟

  1. 分配 Tag 值:所有需權限控制的選單項目與按鈕,Tag 依序指派唯一正整數 (1, 2, 3...)。
  2. 建立權限清單:在 CheckBoxList 中列出所有權限名稱(選單與按鈕),順序必須與 Tag 指派順序完全一致。
  3. 資料庫權限欄位:操作員表加入 Privilege 字串欄位(預留 50 字元),以 0 表示「有權限/啟用」,1 表示「無權限/停用」。
  4. 儲存權限設定:遍歷 CheckBoxList,勾選者寫 '0',未勾選寫 '1',組成字串更新至資料庫。
    AnsiString qx = "";
    for (int i = 1; i <= CheckListBox1.Items.Count; i++) {
        qx += CheckListBox1.Checked[i-1] ? "0" : "1";
    }
    Sql = "UPDATE Operator SET Privilege = '" + qx + "' WHERE Operator_Name = '" + CboOperatorName.Text + "'";
    
  5. 表單載入時套用權限:在 FormShow 事件中讀取使用者權限字串,遍歷元件集合,依 Tag 值對應字串位置決定 Enabled 屬性。
    if (UserName != "系統管理員") {
        if (strPrivilege.Length == 0) {  // 未設定權限:全部停用
            for (int j = 0; j <= Parent.ComponentCount-1; j++) {
                if (Parent.Components[j].Tag != 0) {
                    if (Parent.Components[j] is TMenuItem)
                        ((TMenuItem)Parent.Components[j]).Enabled = false;
                    else if (Parent.Components[j] is TButton)
                        ((TButton)Parent.Components[j]).Enabled = false;
                }
            }
        } else {  // 已設定權限:依字串逐項啟用/停用
            for (int i = 1; i <= strPrivilege.Length; i++) {
                string qx = strPrivilege.Substring(i, 1);
                if (qx == "1") {  // 無權限
                    for (int j = 0; j <= Parent.ComponentCount-1; j++) {
                        if (Parent.Components[j].Tag == i) {
                            if (Parent.Components[j] is TMenuItem)
                                ((TMenuItem)Parent.Components[j]).Enabled = false;
                            else if (Parent.Components[j] is TButton)
                                ((TButton)Parent.Components[j]).Enabled = false;
                        }
                    }
                }
            }
        }
    }
    

優點

  • 無需維護額外權限對應表,Tag 值即為索引鍵。
  • 權限字串緊湊,易於儲存、備份與遷移。
  • 動態新增控制項只需指派新 Tag 值並同步更新 CheckBoxList,擴充性極佳。
  • 系統管理員可繞過檢查,擁有完整權限。

適用範圍

適用於 Windows Forms (Delphi/C++Builder/VB6 等) 應用程式,概念亦可移植至 Web 表單 (ASP.NET) 控制項 Attributes["Tag"] 實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved