1
votes

I got a login where depending of the type of user it will open a different menu but I dont know how to make it recognize the type without specifying it, this is the code I got:

private void btnaceptar_Click(object sender, EventArgs e) { if (txtusuario.Text == "" || txtcontraseña.Text == "") { MessageBox.Show("TODOS LOS CAMPOS DEBEN ESTAR LLENOS.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); txtusuario.Clear(); txtusuario.Focus(); }

        n = n - 1;
        if (n <= 3 && n >= 0)
        {

            if (n == 1)
            {
                MessageBox.Show("Solo le quedan 1 intento, porfavor asegurese de poner los datos correctos!", "AVISO!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                MessageBox.Show("Usuario y/o contraseña incorrectos, verifique porfavor", "Error al ingresar datos.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtusuario.Clear();
                this.txtcontraseña.Clear();
                this.txtusuario.Focus();
            }

            else
            {
                SqlConnection miconexion = new SqlConnection(@"Data Source=USER-PC;Initial Catalog=dbpuntodeventa;Integrated Security=True");
                miconexion.Open();
               SqlCommand comando1 = new SqlCommand("select * from usuarios where usuario='" + txtusuario.Text + "'and contraseña='" + txtcontraseña.Text + "'", miconexion);
                SqlDataReader Ejecuta = comando1.ExecuteReader();

                if (Ejecuta.Read() == true)
                {
                    MessageBox.Show("Bienvenido Administrador , Ingreso de datos correctos", "Ingreso exitoso!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Hide();
                    frmmenuadmin frmprincipal = new frmmenuadmin();
                    frmprincipal.Show();
                    frmprincipal.lblid.Text = txtusuario.Text;
                 }


                else
                {
                    SqlConnection miconexion2 = new SqlConnection(@"Data Source=USER-PC;Initial Catalog=dbpuntodeventa;Integrated Security=True");
                    miconexion2.Open();
                    SqlCommand comando = new SqlCommand("select * from usuarios where usuario='" + txtusuario.Text + "'and contraseña='" + txtcontraseña.Text + "'", miconexion2);
                    SqlDataReader ejecutar1 = comando.ExecuteReader();


                    if (ejecutar1.Read() == true)
                    {

                        MessageBox.Show("Bienvenido Empleado , Ingreso de datos correctos", "Ingreso exitoso!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Hide();
                        frmmenu frm2 = new frmmenu();
                        frm2.Show();
                        frm2.lblnombre.Text = txtusuario.Text;

                    }
                    else
                    {
                        if (n == 0)
                        {
                            MessageBox.Show("Error,se han agotado los intentos", "AVISO!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            Application.Exit();
                        } 
                        MessageBox.Show("Usuario y/o contraseña incorrectos, verifique porfavor", "Error al ingresar datos.", MessageBoxButtons.OK, MessageBoxIcon.Error);                         
                        this.txtusuario.Clear();
                        this.txtcontraseña.Clear();
                        this.txtusuario.Focus();
                    }

                }
            }
        }

    }
    }

}

for those who dont speack spanish, usuario means user and contraseña means password now I need to implement tipo which means type

2

2 Answers

2
votes
public static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

Try this if you are talking about windows user, if you are talking about admin user in your application you should have column in your database: IsAdmin or something like that.

Edit:

You should fetch data from the database for current user and password in DataTable and check if the flag field IsAdmin=0 or IsAdmin=1. Depending of the result you are showing the correct menu.

Also you need to use SqlParameters to prevent of SqlInjection.

Here simple code how to retrieve the data in DataTable:

string connectionString = "Your connection";

SqlConnection conn = new SqlConnection(connectionString);

conn.Open();

SqlCommand cmd = new SqlCommand(@"Select * from [User] WHERE UserName=@UserName AND Password=@Password AND Deleted=0", connectionString);

cmd.Parameters.AddWithValue("@UserName", userName.Text);
cmd.Parameters.AddWithValue("@Password", password.Text);

DataSet dst = new DataSet();
string tableName = "Your table Name";

using(SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
    adapter.Fill(dst, tableName);
}

conn.Close();

if(dst.Tables[0].Rows.Count == 0)
//show error

if(dst.Tables[0].Rows.Count > 0)
{
    if(Convert.ToInt32(dst.Tables[0].Rows[0]["IsAdmin"]) == 1)
        //load admin menu
    else
        // load normal user menu
}

Deleted is another flag which is good to have in your code. This will represent if the current user is deleted. It is good practice to not deleted data physically from the database.

It will be good to have Data access in another class in this case you will not write every time SQL connections, only the query for SqlCommands. I will leave this to figure it by yourself.

0
votes

Make an extra column in the DB name it like UserType or something. Then after you do select * just check on the field value.

P.S. if you want good design pattern then create another UserType table with ID and TypeName, and do an inner join. But for beginners it is not necessary.