Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user has Update/Select/Insert permissions before execute

I am building a winforms app that uses Integrated Security on SQL Server. Right now, i do the following to ensure that a user is informed that he/she does not have access to a certain schema (everyone has select permissions but few have update and insert).

 try
        {
            string sqlx = "select * from test.t";
            SqlCommand comm = new SqlCommand(sqlx, conn);


            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
            return;
        }
        catch (SqlException ex)
        {
            if (ex.Number == 229 | ex.Number == 230)
                System.Windows.Forms.MessageBox.Show("You do not have permission to update this table. Please contact your system admin for permission.");
            else
                System.Windows.Forms.MessageBox.Show(ex.Message);
        }

        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);

        }
        finally
        {
            conn.Close();
        }

Instead of giving the users the ability to even click the delete button, for example, is there a way to "prescreen" a users privileges from C#?

like image 986
brhardwick Avatar asked Mar 31 '26 05:03

brhardwick


1 Answers

Try this:

SELECT * FROM fn_my_permissions('dbo', 'SCHEMA')

It will return the list of permissions against the 'dbo' schema for the connected user:

entity_name subentity_name  permission_name
dbo         NULL            SELECT
dbo         NULL            INSERT
dbo         NULL            UPDATE
dbo         NULL            DELETE
dbo         NULL            REFERENCES
dbo         NULL            EXECUTE
dbo         NULL            VIEW CHANGE TRACKING
dbo         NULL            VIEW DEFINITION
dbo         NULL            ALTER
dbo         NULL            TAKE OWNERSHIP
dbo         NULL            CONTROL

So you could just look for INSERT or UPDATE as necessary:

if exists (SELECT * FROM fn_my_permissions('dbo', 'SCHEMA') where permission_name = 'INSERT')
begin
    select 'Yes'
end
else
begin
    select 'No'
end
like image 155
Chris Steele Avatar answered Apr 02 '26 18:04

Chris Steele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!