如何让我的登录识别用户是管理员还是普通用户?

时间:2014-10-07 18:46:14

标签: c# authentication login usertype

我有一个登录,根据用户的类型,它将打开一个不同的菜单,但我不知道如何让它识别类型而不指定它,这是我得到的代码:

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

                }
            }
        }

    }
    }

}

对于那些不讲西班牙语的人,usuario意味着用户和contraseña意味着密码现在我需要实现tipo,这意味着类型

2 个答案:

答案 0 :(得分:1)

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

如果您正在谈论Windows用户,请尝试此操作,如果您在应用程序中讨论管理员用户,则应在数据库中包含列:IsAdmin或类似的内容。

修改

您应该从数据库中获取DataTable中当前用户和密码的数据,并检查标志字段IsAdmin = 0或IsAdmin = 1。根据结果​​显示正确的菜单。

此外,您需要使用SqlParameters来阻止SqlInjection

这里简单的代码如何检索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
}

已删除是您的代码中的另一个标志。这将表示是否删除当前用户。最好不要从数据库中物理删除数据。

在这种情况下,在另一个类中进行数据访问会很好,每次SQL连接都不会写,只有SqlCommands的查询。我会留下这个来自己解决。

答案 1 :(得分:0)

在数据库名称中创建一个额外的列,如UserType或其他内容。然后选择*后,只需检查字段值。

P.S。如果你想要好的设计模式,那么用ID和TypeName创建另一个UserType表,然后进行内连接。但对于初学者来说,没有必要。