【问题标题】:How do I display menu options based on access level?如何根据访问级别显示菜单选项?
【发布时间】:2018-11-27 22:12:35
【问题描述】:

希望这个问题有意义..

基本上,我正在为大学作业制作手术系统。

我已经制作了一个基于服务的数据库和用户表,其中包含用户名和密码等。

登录已全部排序。控制台打印正确的 RoleType 并将用户登录。

我搞砸了一个名为 RoleType 的枚举,我试图根据用户在其中的角色来更改它

这是我目前所处的位置......

登录表单

    //Declare an enum to store roletypes
    public enum RoleTypes
    {
        practiceManager, 
        doctor,
        receptionist
    }

    private void btnLogin_Click(object sender, EventArgs e)
    {

        //Try and open a connection with database and run the code
        try
        {

            //Create new instance of sql connection, pass in the connection string for BayOneSurgerySystem.mdf to connect to database.
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\davie\Documents\UniWork\Software Engineering\SurgerySystem\SurgeryDatabase\BayOneLoginSystem.mdf;Integrated Security=True;Connect Timeout=30");

            //Create new instance of SQlCommand and pass in a query to be called to retrieve table data for username and passwords aswell as the connection object.
            SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username and Password = @password", conn);
            //This passes user input into @username and @password
            cmd.Parameters.AddWithValue("@username", txtBoxUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtBoxPassword.Text);

            //Open connection with database
            conn.Open();

            //Create new instance of dataSet to hold the data retrieved from sql query
            DataSet ds = new DataSet();
            //Create new instance of DataAdpater to retrieve the data pass in Sql command
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            //using DataAdapter fill in dataSet wiht data if user input and stored data matches
            da.Fill(ds);

            //Close the connection now data table is filled with username and password
            conn.Close();

            //declare bool, true if there is a match with database and user input
            bool loginSuccess =  (ds.Tables[0].Rows.Count == 1);


            //if login success is true then open menu
            if (loginSuccess)
            {
                //Change state of enum RoleTypes bases on result from dataSet Role column.
                Console.WriteLine(ds.Tables[0].Rows[0]["Role"].ToString());

                try
                {
                    switch (ds.Tables[0].Rows[0]["Role"])
                    {
                        case "Doctor":
                            {
                                RoleTypes roleType = RoleTypes.doctor;
                                Console.WriteLine("Role type chnage to" + roleType.ToString());
                            }
                            break;
                        case "Practice Manager":
                            {
                                RoleTypes roleType = RoleTypes.practiceManager;
                                Console.WriteLine("Role type chnage to" + roleType.ToString());
                            }
                            break;
                        case "receptionist":
                            {
                                RoleTypes roleType = RoleTypes.receptionist;
                                Console.WriteLine("Role type chnage to" + roleType.ToString());
                            }
                            break;
                        default:
                            break;

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }


                Console.WriteLine("Logged in.");
                FrmMenu menu = new FrmMenu();
                this.Close();
                menu.Show();
            }
            else
            {
                MessageBox.Show("Invalid username or password.", "Error!", MessageBoxButtons.RetryCancel);
                Console.WriteLine("Not logged in");
            }

         }

        //If connection cant be opened diplsay error message and catch exception and print to console
        catch(Exception ex)
        {
            Console.WriteLine(ex);
            MessageBox.Show("Sorry can't connect");
        }
    }
}

}

这个想法是公共枚举可以在 FrmMenu 中引用,并且基于该枚举可以看到不同的控件。

它只是忽略了带有 switch 语句的 tryCatch 并且没有捕获任何异常?知道为什么吗?或者是否有更有效的方法来做到这一点?

提前致谢!

【问题讨论】:

  • 不要从用户那里获取输入并将其连接到 SQL 语句中。这就是 SQL 注入 攻击的发生方式。不要根据“用户名”做出决定。相反,创建包含用户的“组”(或“角色”)(如医生、护士)并使用它来决定显示什么。要弄清楚如何显示菜单,请在表单上创建一个菜单并查看FormName.Designer.cs 文件中生成的代码,并将其用作指导。
  • @Flydog57 - 我对登录做了什么? 'private System.Windows.Forms.Button btnPatients;' 是不是很生动?我根据 IsInRole =="" 显示不同的按钮?我快速浏览了一下,是不是我要查找的 角色管理?用于设置管理员和高级用户等?感谢您的帮助!
  • 我对 SQL 注入的东西非常认真。它是最常见、最严重的 Web 漏洞之一。阅读它。使用参数化 SQL(使用 @User 之类的变量构造查询,并将它们作为参数传递给查询)。或者,使用像 Dapper 或实体框架这样的 ORM。您不希望教授将您的代码作为“如何不做”的示例

标签: c# sql winforms


【解决方案1】:

我做过类似的事情。我创建了角色和用户角色表。

CREATE TABLE [dbo].[Role](
    [RoleID] [nvarchar](10) NOT NULL,
    [RoleName] [nvarchar](50) NOT NULL,
    [Memo] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_SYS_Role] PRIMARY KEY NONCLUSTERED 
(
    [RoleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

用户角色表

CREATE TABLE [dbo].[UserRole](
    [UserRoleID] [nvarchar](10) NOT NULL,
    [UserID] [nvarchar](10) NOT NULL,
    [RoleID] [nvarchar](10) NOT NULL,
 CONSTRAINT [PK_UserRole] PRIMARY KEY CLUSTERED 
(
    [UserRoleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[UserRole]  WITH CHECK ADD  CONSTRAINT [FK_UserRole_REF_Role] FOREIGN KEY([RoleID])
REFERENCES [dbo].[Role] ([RoleID])
GO

ALTER TABLE [dbo].[UserRole] CHECK CONSTRAINT [FK_UserRole_REF_Role]
GO

ALTER TABLE [dbo].[UserRole]  WITH CHECK ADD  CONSTRAINT [FK_UserRole_REF_USER] FOREIGN KEY([UserID])
REFERENCES [dbo].[User] ([UserID])
GO

ALTER TABLE [dbo].[UserRole] CHECK CONSTRAINT [FK_UserRole_REF_USER]
GO

在您的表单上,根据您的登录用户调用查询

【讨论】:

  • 我从来没有以编程方式创建表,我可以使用添加项 > 基于服务器的数据库来创建表,然后运行查询是一样的吗?
  • 是的,您可以手动创建表。上面的 sql 查询是在您的 sql server 上创建表(只需将此代码复制到 SQLMS 新查询窗口并执行它。部署表后,您可以在 UserRole 表中添加记录以授予权限。完成后,您可以调用您的在表单中查询以根据结果检索数据。
猜你喜欢
  • 2013-05-30
  • 2011-08-15
  • 1970-01-01
  • 2015-12-19
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多