9 Replies - 4460 Views - Last Post: 19 June 2011 - 11:01 AM Rate Topic: -----

#1 metador  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 21
  • Joined: 18-June 11

After login ... User privileges in Csharp

Posted 18 June 2011 - 10:59 AM

hello brother:

i am bit new in dotnet.So kindly help me.....

i have created a login form in C# which works fine and login button take m to next form.But my question is that how i restrict user means when user login then in form2 some buttons will hide which are only visible when admin login.So please just tell how i restrict user.

This post has been edited by metador: 18 June 2011 - 11:00 AM

Is This A Good Question/Topic? 0
  • +

Replies To: After login ... User privileges in Csharp

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 6490
  • View blog
  • Posts: 23,579
  • Joined: 12-June 08

Re: After login ... User privileges in Csharp

Posted 18 June 2011 - 12:10 PM

You have a series of roles and responsibilities that each user is assigned to. When the form loads up it enables/disables controls based on the user group.
Was This Post Helpful? 1
  • +
  • -

#3 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 934
  • View blog
  • Posts: 2,332
  • Joined: 15-February 11

Re: After login ... User privileges in Csharp

Posted 18 June 2011 - 12:25 PM

You could even make a class User with one of the property variables being this enum.
private enum USER_LEVEL { ADMINISTRATOR = 100, POWER_USER = 60, USER = 20 };

Then certain controls are hidden or disabled if the user's level is below that of the required level.
Was This Post Helpful? 1
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Closing in on 5,000
  • member icon

Reputation: 4929
  • View blog
  • Posts: 10,465
  • Joined: 02-June 10

Re: After login ... User privileges in Csharp

Posted 18 June 2011 - 02:01 PM

I've never much cared for user groups. I like expressly setting a user's ability

class User
{
   public bool CanCloseProgram;
   public bool CanChangeSettings;
   public bool CanChangeOwnPassword;
   public bool CanChangeDesktopImage;
   public bool CanMakeNewUsers;
   public bool CanEditExistingUsers;
   public bool CanMakeNewProducts;
   public bool CanRefundSales;
   public bool CanMakeInvntoryAdjustments;
}

Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4892
  • View blog
  • Posts: 11,288
  • Joined: 16-October 07

Re: After login ... User privileges in Csharp

Posted 18 June 2011 - 02:35 PM

There are two standard interfaces implemented by Microsoft's System.Security namespace. They are IIdentity and IPrincipal. In a windows environment, you get IIdentity for free, as the current. It's not big trick to go from there.

Any User object will want to implement something like bool IsInRole(string role). Programming to these interfaces make it easy to hook your application into existing authentication mechanisms as well as just rolling your own.
Was This Post Helpful? 3
  • +
  • -

#6 metador  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 21
  • Joined: 18-June 11

Re: After login ... User privileges in Csharp

Posted 18 June 2011 - 10:56 PM

Thanks dreaming coder..
I tried to use public interface IIdentity() but i didn't understand what to do .. IIdentity has three properties authenticationType and isauthenticated , which one to use and where.Can u embed this in my code please

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Principal;
namespace Login
{
    public partial class Form1 : Form
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlDataReader dr = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(Convert.ToInt16(e.KeyChar) == 13 && textBox1.Text !="")
                textBox2.Focus();
        }
       
        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Convert.ToInt16(e.KeyChar) == 13 && textBox2.Text != "")
            {
                string connection;
                string sql;
                try
                {
                    //connect to the sql server through app.config
                    connection = ConfigurationSettings.AppSettings["Database"];
                    con = new SqlConnection(connection);
                    sql = "select * from userLogin where username='" + textBox1.Text + "' and password='" + textBox2.Text + "'";
                    con.Open();
                    cmd = new SqlCommand(sql, con);
                    dr = cmd.ExecuteReader();
                    // String xx = " ";
                    //String yy = " ";


                    while (dr.Read())
                    {
                        // MessageBox.Show("successfully login");
                        frmtest f1 = new frmtest();
                        f1.Show();
                        this.Hide();
                      
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.ToString());
                }
                finally
                {
                    con.Close();
                }
               
            }
        }
    }
}

View Postbaavgai, on 18 June 2011 - 02:35 PM, said:

There are two standard interfaces implemented by Microsoft's System.Security namespace. They are IIdentity and IPrincipal. In a windows environment, you get IIdentity for free, as the current. It's not big trick to go from there.

Any User object will want to implement something like bool IsInRole(string role). Programming to these interfaces make it easy to hook your application into existing authentication mechanisms as well as just rolling your own.

Was This Post Helpful? 0
  • +
  • -

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4892
  • View blog
  • Posts: 11,288
  • Joined: 16-October 07

Re: After login ... User privileges in Csharp

Posted 19 June 2011 - 02:49 AM

Please, use parameters! Your code is asking to be hacked. What if I gave you a user name of '; delete userLogin;? Or, even more simplistic, a password of ' or password like '%?

Also, methods are our friends. Pass form data when you can, don't incorporated it into large event methods.

Let's see...
public partial class Form1 : Form {
	// these don't need to be in this scope
	// SqlConnection con;
	// SqlCommand cmd;
	// SqlDataReader dr = null;
	public Form1() {
		InitializeComponent();
	}
	
	private SqlConnection GetConnection() {
		return new SqlConnection(ConfigurationSettings.AppSettings["Database"];)/>;
	}
	
	private IIdentity ValidateLogin(string username, string password) {
		SqlCommand cmd = GetConnection().CreateCommand();
		cmd.CommandText = "select username from userLogin where username=@username and password=@password";
		cmd.Parameters.AddWithValue("@username", username);
		cmd.Parameters.AddWithValue("@password", password);
		try {
			cmd.Connection.Open();
			SqlDataReader reader = cmd.ExecuteReader();
			if (reader.Read()) {
				return new GenericIdentity(username);
			}
		} finaly {
			cmd.Connection.Close();
		}
		return null;
	}
	
	private void textBox2_KeyPress(object sender, KeyPressEventArgs e) {
		if (Convert.ToInt16(e.KeyChar) == 13 && textBox2.Text != "") {
			IIdentity user;
			try {
				user = ValidateLogin(textBox1.Text, textBox2.Text);
			} catch (Exception ee) {
				MessageBox.Show(ee.ToString());
			}
			if (user!=null) {
				frmtest f1 = new frmtest();
				// this is a property you write.  The form needs to know the user, right?
				f1.User = user; 
				f1.Show();
				this.Hide();
			}
		}
	}
}



GenericIdentity is just that; it will get you to the next round. Ideally, you'd have another class responsible for authentication and a User class that implemented everything itself. Here's a very simple user class:
class User : IIdentity, IPrincipal {
	private string name;
	private List<string> roles;
	public User(string name) {
		this.name = name;
		roles = new List<string>();
	}
	public string AuthenticationType { get { return "Custom"; } }
	public bool IsAuthenticated { get { return true; } }
	public string Name { get { return this.name; } }
	public IIdentity Identity { get { return this; } }
	public bool IsInRole(string role) { return this.roles.Contains(role.ToLower()); }
	public void AddRole(string role) { this.roles.Add(role.ToLower()); }
}



That has pretty much all you need. If you have another table in your database that has roles, then adding them isn't a big deal. Just join and call AddRole for each name returned.

I've probably written too much code for this. :P Good luck.
Was This Post Helpful? 1
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Closing in on 5,000
  • member icon

Reputation: 4929
  • View blog
  • Posts: 10,465
  • Joined: 02-June 10

Re: After login ... User privileges in Csharp

Posted 19 June 2011 - 07:12 AM

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
  • Try to avoid having work actually take place in GUI control event handlers. It is usually better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    btnSave(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    Form1_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    

Was This Post Helpful? 1
  • +
  • -

#9 metador  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 21
  • Joined: 18-June 11

Re: After login ... User privileges in Csharp

Posted 19 June 2011 - 10:49 AM

Thanks for alot of help sir,,,,,,

almost problem is solved but it give an error on line 42 f1.user= user

error is Error 1 'Login.frmtest' does not contain a definition for 'User' and no extension method 'User' accepting a first argument of type 'Login.frmtest' could be found (are you missing a using directive or an assembly reference?





View Postbaavgai, on 19 June 2011 - 02:49 AM, said:

Please, use parameters! Your code is asking to be hacked. What if I gave you a user name of '; delete userLogin;? Or, even more simplistic, a password of ' or password like '%?

Also, methods are our friends. Pass form data when you can, don't incorporated it into large event methods.

Let's see...
public partial class Form1 : Form {
	// these don't need to be in this scope
	// SqlConnection con;
	// SqlCommand cmd;
	// SqlDataReader dr = null;
	public Form1() {
		InitializeComponent();
	}
	
	private SqlConnection GetConnection() {
		return new SqlConnection(ConfigurationSettings.AppSettings["Database"];)/>;
	}
	
	private IIdentity ValidateLogin(string username, string password) {
		SqlCommand cmd = GetConnection().CreateCommand();
		cmd.CommandText = "select username from userLogin where username=@username and password=@password";
		cmd.Parameters.AddWithValue("@username", username);
		cmd.Parameters.AddWithValue("@password", password);
		try {
			cmd.Connection.Open();
			SqlDataReader reader = cmd.ExecuteReader();
			if (reader.Read()) {
				return new GenericIdentity(username);
			}
		} finaly {
			cmd.Connection.Close();
		}
		return null;
	}
	
	private void textBox2_KeyPress(object sender, KeyPressEventArgs e) {
		if (Convert.ToInt16(e.KeyChar) == 13 && textBox2.Text != "") {
			IIdentity user;
			try {
				user = ValidateLogin(textBox1.Text, textBox2.Text);
			} catch (Exception ee) {
				MessageBox.Show(ee.ToString());
			}
			if (user!=null) {
				frmtest f1 = new frmtest();
				// this is a property you write.  The form needs to know the user, right?
				f1.User = user; 
				f1.Show();
				this.Hide();
			}
		}
	}
}



GenericIdentity is just that; it will get you to the next round. Ideally, you'd have another class responsible for authentication and a User class that implemented everything itself. Here's a very simple user class:
class User : IIdentity, IPrincipal {
	private string name;
	private List<string> roles;
	public User(string name) {
		this.name = name;
		roles = new List<string>();
	}
	public string AuthenticationType { get { return "Custom"; } }
	public bool IsAuthenticated { get { return true; } }
	public string Name { get { return this.name; } }
	public IIdentity Identity { get { return this; } }
	public bool IsInRole(string role) { return this.roles.Contains(role.ToLower()); }
	public void AddRole(string role) { this.roles.Add(role.ToLower()); }
}



That has pretty much all you need. If you have another table in your database that has roles, then adding them isn't a big deal. Just join and call AddRole for each name returned.

I've probably written too much code for this. :P Good luck.

Was This Post Helpful? 0
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4892
  • View blog
  • Posts: 11,288
  • Joined: 16-October 07

Re: After login ... User privileges in Csharp

Posted 19 June 2011 - 11:01 AM

Quote

frmtest f1 = new frmtest();
// this is a property you write. The form needs to know the user, right?
f1.User = user;


You need to pass your user to you form. Else, how does it know about it. To implement this, you have to write code that allows you to pass the validated user to the your form instance.

This post has been edited by baavgai: 19 June 2011 - 11:01 AM

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1