0

Please help me on my project I'm a newbie in coding. I'm making a Point of Sale with Inventory System and I'm using TabControl and TabPages as my UI. My problem is that I want my program to know if the currently logged in is an Admin or a normal User on my SQL database. I'm not using IsUserAdmin or WindowsIdentity as to my understanding that they read WindowsSystem admin rights. What I want is that my program only reads on the provided userlevel on my sql database. I'm still working on the Users tab and I'm done on my login form. I want that if I press delete update or add button my program will read if I'm an admin or not from my sql database and give a pop-up message if I'm only a user level and can't update add or delete any entry.

Here's my log-in code: which for me is already fine. Not my original code credits to the owner/s of the code that I copied.

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();
        }
    }
}

And here is my main window code which has tabControls and tabPages. Works fine but I want that if I press delete update or add button my program will read if I'm an admin or not from my sql database and give a pop-up message if I'm only a user level and can't update add or delete any entry. Not my original code credits to the owner/s of the code that I copied.

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

Chres Abte
  • 39
  • 1
  • 6

1 Answers1

0

You can query the current user's SQL Server Roles by following the advice in this post.

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;

This will provide the name of the Role you assinged the user to in SQL Server

Ricardo Pontual
  • 3,749
  • 3
  • 28
  • 43
PhillipH
  • 6,182
  • 1
  • 15
  • 25