简体   繁体   中英

ASP.NET how to check user role from PostgreSQL db?

I'm new to C# and asp.net.

In my asp.net project i have a dropdownlist that shows information from postgreSQL db depends on which user loged on. Here's my code:

 protected void Button6_Click(object sender, EventArgs e)
    {
   //here's GridView settings, connections strings etc...

 NpgsqlCommand cmd = new NpgsqlCommand();
            NpgsqlDataAdapter sqlDa1 = new NpgsqlDataAdapter("SELECT * FROM vacations", conn); //show by executor
            DataTable dtbl1 = new DataTable();
            if ((string)Session["Name"] == "Smith")
            {
                sqlDa1.Fill(dtbl1);
                GridView1.DataSource = dtbl1;
                GridView1.DataBind();
            }
            else System.Diagnostics.Debug.WriteLine("You do not have permissions!!!");

The problem is, I will have not only one user, so i cannot add each new user to my if(){} else statement. How can i automatically check users permissions and depends on it show/not show information

A solution would be to create different roles, to which you associate different rights. For example, r_visitor and r_administrator. You would add each users to the proper role(s)

Then, you can grant the permissions to the roles at the DB level, and, as you ask, you can check in your application is the user has or not the given role using the following query that returns a boolean:

SELECT EXISTS(
  SELECT b.rolname rname,
         c.rolname mname 
  FROM pg_auth_members a, 
       pg_roles b, 
       pg_roles c  
  WHERE a.roleid=b.oid 
   AND a.member = c.oid 
   AND b.rolname = 'r_visitor' 
   AND c.rolname='johnDoe');

If you want to know about inherited roles (userA belongs to R1, which is part of R2 -> we want to know if userA has R2 priviledges) , look at this answer that implements a recursive way of looking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM