Login in C# with database

Asked

Viewed 1,676 times

1

I’m trying to make a login panel, but it doesn’t recognize the data recorded in the database.

Code:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\Trabalho Programação - VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True;Connect Timeout=30");

if (txtPass.Text == "" & txtUser.Text == "") //Campos vazios
{
    MessageBox.Show("Por favor preencha os dados de login!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else if(txtPass.Text == "") //txtPass vazia
{
    MessageBox.Show("Campo Password vazio!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else if(txtUser.Text == "") //txtuser vazia
{
    MessageBox.Show("Campo Utilziador vazio!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else
{
    MessageBox.Show("Por favor verifique os dados de login!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}


try
{
    con.Open();
    string user = txtUser.Text;
    string pass = txtPass.Text;
    SqlCommand cmd = new SqlCommand("SELECT * FROM Login WHERE User='" + txtUser.Text + "' AND Pass ='" + txtPass.Text + "'", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        this.Hide();
        //Abre Form Geral caso os dados do Login estejam certos
        Form1 btHome = new Form1();
        btHome.Show();
    }
}
catch(Exception error)
{
    MessageBox.Show(error.Message, "ERRO!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    if  (con != null)
    {
        con.Close();
    }
}
  • Try to explain your problem better, there is no way to understand what you need this way. By the way, you do not need to write "help" in the title.

  • Apparently it is a Windows Forms application. Is giving some error?

  • Which error gives ? place break points and check at runtime what happens...

  • can start by taking out that last if Else, which Zera the fields if both are filled in...

2 answers

3

Some remarks:

If the password field is empty, why force the user to type the user again? just set the cursor focus to the password field... txtPass.Focus(); Also for the opposite situation.

To check whether a string is empty, I use String.IsNullOrEmpty(txtPass.Text);

Just below where you open the connection, you declare two variables:

string user = txtUser.Text;
string pass = txtPass.Text;

but uses them for nothing.

And when executing the SQL command, use parameters, and do not concatenate the string this way. The way it is an SQL Injection is very easy.

I made a very simple code of how to make a login screen in your case:

The main application form (what opens in the method Main with Application.Run) should be your main form, not the login form. So I put the login dialog and if the result is OK, I continue with the application and open the FormPrincipal, in your case the Form1 or Formgeneral.

Program:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        FormLogin formLogin = new FormLogin();
        if (formLogin.ShowDialog() == DialogResult.OK)
        {
            Application.Run(new FormPrincipal(formLogin.UsuarioLogado));
        }
    }
}

Formlogin: That would be the code of FormLogin:

public partial class FormLogin : Form
{
    public Usuarios UsuarioLogado { get; set; }

    public FormLogin()
    {
        InitializeComponent();
        //O botão cancela, retorna 'Cancel'
        buttonCancela.DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }

    //Botão Login ou OK
    private void buttonLogin_Click(object sender, EventArgs e)
    {
        try
        {
            if (!String.IsNullOrEmpty(txtUser.Text))
            {
                if (!String.IsNullOrEmpty(txtPass.Text))
                {

                    //A rotina que valida o login do usuário, está dentro da 
                    //classe Usuarios, e se for válido, retorna um objeto do 
                    //tipo Usuarios, caso contrário, retorna null
                    UsuarioLogado = Usuarios.ValidarLogin(txtUser.Text, txtPass.Text);

                    if (UsuarioLogado != null)
                    {
                        //Se retornou o usuário, ou seja: é válido, retorna OK
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;

                    }
                    else
                    {
                        txtUser.Text = txtPass.Text = "";
                        labelStatus.Text = "Usuario / Senha inválido";
                    }
                }
                else
                {
                    labelStatus.Text = "Informe a senha do usuário";
                    txtPass.Focus();
                }
            }
            else
            {
                labelStatus.Text = "Informe o nome de usuário";
                txtUser.Focus();
            }
        }
        catch (Exception ex)
        {
            labelStatus.Text = ex.Message;
        }

    }
}

Users: This would be a class of users, here are the user properties, and Insert / Update / Delete methods, plus the login validation method that is used in Formlogin

public class Usuarios
{
    public string Usuario { get; set; }
    public string Senha { get; set; }
    public string Nome { get; set; }

    //Quaisquer outras propriedades

    public static Usuarios ValidarLogin(string _user, string _senha)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\Trabalho Programação - VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True;Connect Timeout=30");

        con.Open();

        SqlCommand cmd = new SqlCommand("SELECT * FROM Login WHERE User= @usuario AND Pass = @senha;", con);

        cmd.Parameters.Add(new SqlParameter("@usuario", _user));
        cmd.Parameters.Add(new SqlParameter("@senha", _senha));

        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            Usuarios obj = new Usuarios();
            obj.Nome = reader["coluna_nome"].ToString();
            obj.Usuario = reader["User"].ToString();

            return obj;
        }
        else
            return null;
    }

}

Formprincipal: In Formprincipal, in your constructor, I put a parameter of the type Users that will be the user logged in to the application, from there you can have which user is using the system.

public partial class FormPrincipal : Form
{
    public FormPrincipal(Usuarios _usuarioLogado)
    {
        InitializeComponent();
        labelUsuario.Text = _usuarioLogado.Nome;
    }
}

I tried not to extend too much, if any other member has suggestions please feel free. Any questions, available.

I made the changes to your code, not taking into account the observations I gave you, and object orientation concepts:

SqlConnection sqlCon = null; //Conexão começa em Null

private string strCmd = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True"; //Conection String da BD

private string strSQL = string.Empty;

public bool logado = false;


public void Sign_in()
{

    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        if (!String.IsNullOrEmpty(txtPass.Text))
        {
            string usuarioLogado =null;


            try
            {
                sqlCon = new SqlConnection(strCmd);
                strSQL = "SELECT Nome FROM [Login] WHERE [User] = @utilizador AND [Pass] = @password";                      
                sqlCon.Open();

                SqlCommand cmd = new SqlCommand(strSQL, con);

                cmd.Parameters.Add(new SqlParameter("@utilizador", txtUser.Text));
                cmd.Parameters.Add(new SqlParameter("@password", txtPass.Text));

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    //usuário é válido e o nome está na variável usuarioLogado
                    logado = true;
                    usuarioLogado = reader["Nome"].ToString();
                }
                else
                {
                    //usuário não é válido
                    txtUser.Text = txtPass.Text = "";
                    labelStatus.Text = "Usuario / Senha inválido";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        else
        {
            labelStatus.Text = "Informe a senha do usuário";
            txtPass.Focus();
        }
    }
    else
    {
        labelStatus.Text = "Informe o nome de usuário";
        txtUser.Focus();
    }
}
  • 2

    One important thing: not only is it too complicated to check the authentication pair separately since 3 ifs are necessary, as it is insecure since it delivers which of them is already right and the invader no longer need to try to hit him in brute force, only the other. And I don’t think this answers the question.

  • In fact it checks only if the fields are filled in, at this point I believe that it does not fit the issue of security, only user usability. And I just showed the error in his logic that is preventing login, since will always be executed the SQL command with empty login and password.

  • 1

    @Rovannlinhalis I think it would be interesting other addendums in the answer about the parts of the code that are not good. Even if it’s just a study, but it’s interesting that he and everyone who sees the question already learns how not to.

  • 1

    @Georgewurthmann yes, the problem is to extend the question too much, but feel free to edit or suggest. I just looked at the simplest parts.

0


Solved the login

SqlConnection sqlCon = null; //Conexão começa em Null

    private string strCmd = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True"; //Conection String da BD

    private string strSQL = string.Empty;

    public bool logado = false;




    public void Sign_in() //Class com as condições do Login
    {
        sqlCon = new SqlConnection(strCmd);

        //Declaração variavéis ( user = txtUser.txt & pass = txtPass.text)
        string senha, uti; 

        try
        {
            //Variáveis = TextBoxs
            uti = txtUser.Text;
            senha = txtPass.Text;

            strSQL = "SELECT COUNT(ID) FROM [Login] WHERE [User] = @utilizador AND [Pass] = @password";

            SqlCommand cmd = new SqlCommand(strSQL, sqlCon);

            cmd.Parameters.Add("@utilizador", SqlDbType.VarChar).Value = uti;
            cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = senha;

            sqlCon.Open(); //Abre a conexão com a BD

            int count = (int)cmd.ExecuteScalar(); 

            if(count > 0) //Login com sucesso
            {
                MessageBox.Show("Login realizado com sucesso!", "Parabéns!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                logado = true;
                this.Dispose();

            }
            else if (txtPass.Text =="" & txtUser.Text=="") //txtUser & txtPass vazia
            {
                MessageBox.Show("Por favor preencha os campos Utilizador & Password!", "Campos vazios!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUser.Focus();
                logado = false;
            }
            else if (txtUser.Text == "") //txtUser &vazia
            {
                MessageBox.Show("Por favor preencha o campo Utilizador!", "Campo Utilizador vazio!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUser.Focus();
                logado = false;
            }
            else if (txtPass.Text == "") //txtPass vazia
            {
                MessageBox.Show("Por favor preencha o campo Password!", "Campo Password vazio!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPass.Focus();
                logado = false;
            }
            else
            {
                MessageBox.Show("Dados de login errados. Por favor verifique os seus daods!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                logado = false;

            }

        }
        catch(SqlException erro)
        {
            MessageBox.Show(erro + "");
        }
  • What is the logic of checking if the fields are empty after running sql and login is wrong ?

  • I put them before Try?

  • Another thing is possible to put the name of the logged-in user in another form?

  • You say leave the ifs of the empty fields before the Try, and then the other correct part?

  • See the Formlogin code that I posted in my reply, the reply also shows how to pass the logged in user

  • public formprincipal(Users _userLog) { Initializecomponent(); labelUsuario.Text = _userLog.Name; }

  • Is that right? But for him to get that name I have to do something else in the login form?

  • In my example I returned a User object in the method that validates login

  • How Voce does the user’s Insert ?

  • I entered the user through the show data table in c#

  • And in the application, won’t you have the option to register? You know about classes and objects?

  • No.I’m on a course that gives me level 5, it’s called CET here in Portugal. Only that my class does not understand programming or have much interest, so the teacher has not given anything very complicated, I’m the one who has been trying to learn asking for help

  • All right, I’m gonna look at some stuff to help you out and I’ll be over it, I’m on my lunch break, as soon as I get back on

  • Thanks a lot, man, you’re helping too much. As to the registration for now will not be necessary, since the program is for a video club manager, but if it could put the name of the logged in user in the other Forms would be legal. One thing, I will try to register movies, where I wanted to add the cover, category and so. for the category I would like to use a combo box, but I don’t really know how they work.

  • one step at a time, rsrs, watch this video: https://www.youtube.com/watch?v=NY2ENg4ejXk

  • I edited my answer by changing your code in a simple way, if I help you only with this login question, check the green V below the answer evaluation

  • Thanks for all the support. I will try to test tomorrow, I will start doing the part of movies and how to add movies,which will give me a terrible headache :S

  • If I want to do this in another form other than the login will change a lot?

  • So I think you should first understand the object orientation question before you get to the Forms. At the beginning you will have two classes: Users and Movies, to create the user interface.

  • Ok. it’s just because I wanted the name of the user in the General form. Thanks. I’ll try to advance my work

Show 15 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.