SQL用户对Windows窗体按钮的管理权限C#

问题描述 投票:0回答:1

请帮助我完成我的项目我是编码的新手。我正在使用库存系统制作销售点,我使用TabControl和TabPages作为我的UI。我的问题是我希望我的程序知道当前登录的是我的SQL数据库上的管理员还是普通用户。我没有使用IsUserAdmin或WindowsIdentity来理解他们阅读WindowsSystem管理员权限。我想要的是我的程序只读取我的sql数据库上提供的userlevel。我仍在使用“用户”选项卡,我已完成登录表单。我希望如果我按下删除更新或添加按钮,我的程序将从我的sql数据库中读取我是否是管理员,如果我只是用户级别并且无法更新添加或删除,则会弹出一条消息任何条目。

这是我的登录代码:对我来说已经很好了。不是我的原始代码归功于我复制的代码的所有者。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SecretCafe
{
    public partial class frmLogin : Form
    {
        static int attempt = 3;
        static string role;
        public frmLogin()
        {
            InitializeComponent();    
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (attempt == 0)
            {
                lblMsg.Text = ("ALL 3 ATTEMPTS HAVE FAILED - CONTACT ADMIN");
                return;
            }

            SqlConnection scn = new SqlConnection();
            scn.ConnectionString = @"Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True";
            SqlCommand scmd = new SqlCommand("select count (*) as count from tblUsers where [User Name]=@usr and Password=@pwd", scn);
            scmd.Parameters.Clear();
            scmd.Parameters.AddWithValue("@usr", txtUser.Text);
            scmd.Parameters.AddWithValue("@pwd", txtPass.Text);
            scn.Open();           

            if (scmd.ExecuteScalar().ToString() == "1")
            {

                MessageBox.Show("You are granted with access.");
                this.Hide();
                frmMain frmmain = new frmMain();
                frmmain.Closed += (s, args) => this.Close();
                frmmain.Show();

            }

            else
            {
                MessageBox.Show("Invalid Username or Password.");
                lblMsg.Text = ("You have only " + Convert.ToString(attempt) + " attempt left to try.");
                --attempt;
                txtUser.Clear();
                txtPass.Clear();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

这是我的主窗口代码,它有tabControls和tabPages。工作正常,但我希望如果我按删除更新或添加按钮我的程序将读取,如果我是一个管理员或不从我的SQL数据库,并给出一个弹出消息,如果我只是一个用户级别,无法更新添加或删除任何条目。不是我的原始代码归功于我复制的代码的所有者。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SecretCafe
{
    public partial class frmMain : Form
    {

        SqlConnection scn = new SqlConnection(@"Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True");
        SqlDataAdapter sda;
        DataTable dt;
        SqlCommand scmd;

        public frmMain()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            show();
        }           

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                scn.Open();                                       
                String qry = "insert into tblUsers values ('" + txtLastName.Text + "', '" + txtName.Text + "', '" + txtAddress.Text + "', '" +dateTimePicker1.Value + "', '" + txtUserLevel.Text + "', '" + txtUserName.Text + "', '" + txtPassword.Text + "')";
                scmd = new SqlCommand(qry, scn);
                int i = scmd.ExecuteNonQuery();

                if (i >= 1)
                    MessageBox.Show(i + " User has been added successfully: " + txtName.Text);
                else
                    MessageBox.Show("User not added!");

                show();
                scn.Close();
                btnClear_Click(sender, e);

            }
            catch (System.Exception exp)
            {
                MessageBox.Show("Error is " + exp.ToString());
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                scn.Open();                                        
                String qry = "update tblUsers set [First Name]='" + txtName.Text + "', Address='" + txtAddress.Text + "', Birthday= '" + dateTimePicker1.Value + "', [User Level]= '" + txtUserLevel.Text + "', [User Name]= '" + txtUserName.Text + "', Password= '" + txtPassword.Text + "' where [Last Name]='" + txtLastName.Text + "'";
                scmd = new SqlCommand(qry, scn);
                int i = scmd.ExecuteNonQuery();

                if (i >= 1)
                    MessageBox.Show(i + " User has been updated successfully: " + txtName.Text);
                else
                    MessageBox.Show("Update Failed! - Last Name can't be updated.");

                show();
                scn.Close();
                btnClear_Click(sender, e);

            }
            catch (System.Exception exp)
            {
                MessageBox.Show("Error is " + exp.ToString());
            }
        }

        void show() {

            sda = new SqlDataAdapter("select [Last Name], [First Name], Address, Birthday, [User Name], [User Level], Password from tblUsers", scn);
            dt = new DataTable();
            sda.Fill(dt);

            dataGridView1.Rows.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[0].Value = dr[0].ToString();
                dataGridView1.Rows[n].Cells[1].Value = dr[1].ToString();
                dataGridView1.Rows[n].Cells[2].Value = dr[2].ToString();
                dataGridView1.Rows[n].Cells[3].Value = dr[3].ToString();
                dataGridView1.Rows[n].Cells[4].Value = dr[4].ToString();
                dataGridView1.Rows[n].Cells[5].Value = dr[5].ToString();
                dataGridView1.Rows[n].Cells[6].Value = dr[6].ToString();                
            }
        }    
        private void dataGridView1_MouseClick_1(object sender, MouseEventArgs e)
        {
            try
            {                   

                txtLastName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                txtAddress.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
                dateTimePicker1.Value = Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[3].Value);
                //dateTimePicker1.Value = DateTime.ParseExact(dataGridView1.Rows[e.GetType].Cells[3].Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                txtUserName.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
                txtUserLevel.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
                txtPassword.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
            }
            catch (Exception exp)
            {
                MessageBox.Show("Error is " + exp.ToString());
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dlteUser = MessageBox.Show("Do you intend to remove this User?", "Warning",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (dlteUser == DialogResult.Yes)
                {
                    scn.Open();
                    String qry = "delete from tblUsers where [Last Name]='" + txtLastName.Text + "'";
                    scmd = new SqlCommand(qry, scn);
                    int i = scmd.ExecuteNonQuery();

                    if (i >= 1)
                        MessageBox.Show(i + " User has been removed successfully: " + txtName.Text);
                    else
                        MessageBox.Show("User deletion failed!");

                    show();
                    scn.Close();
                    btnClear_Click(sender, e);
                }
                else if (dlteUser == DialogResult.No)
                {

                }

            }
            catch (System.Exception exp)
            {
                MessageBox.Show("Error is " + exp.ToString());
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtName.Clear();
            txtLastName.Clear();
            txtAddress.Clear();
            dateTimePicker1.Value = DateTime.Now;
            txtUserLevel.Clear();
            txtUserName.Clear();
            txtPassword.Clear();
        }


    }
}

my sql database for users picture

c# sql-server
1个回答
0
投票

您可以按照本文中的建议查询当前用户的SQL Server角色。

How to query current user's roles

SELECT u.name, r.name
  FROM sys.database_role_members AS m
  INNER JOIN sys.database_principals AS r
  ON m.role_principal_id = r.principal_id
  INNER JOIN sys.database_principals AS u
  ON u.principal_id = m.member_principal_id
  WHERE u.name = @user;

这将提供您在SQL Server中为用户指定的角色的名称

© www.soinside.com 2019 - 2024. All rights reserved.