0

My question is how could simplify or improve this code?, it works but I feel like I'm putting a lot of unnecessary code or I feel like i'm doing something wrong. I'm making a user login for a nutriologist. Thank you for your response beforehand.

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (tbUser.Text == "")
            {
                MessageBox.Show("Please input user name.", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (tbPassword.Text == "")
            {
                MessageBox.Show("Please input password name.", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (SQL.ConnectionOpen() == true)
                {
                    Query = "SELECT * FROM users WHERE user_name = '" + tbUser.Text + "' AND password = '" + tbPassword.Text + "'";
                    SQL.Command = new MySqlCommand(Query, SQL.Conexion);
                    SQL.Reader = SQL.Command.ExecuteReader();
                    if (SQL.Reader.Read() == true)
                    {
                        frmMain Main = new frmMain();
                        Main.Show();
                        tbUser.Clear();
                        tbPassword.Clear();
                        SQL.Reader.Dispose();
                        SQL.Command.Dispose();
                        SQL.Reader.Close();
                        SQL.ConnectionClose();
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("User or password incorrect.", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SQL.Reader.Dispose();
                        SQL.Command.Dispose();
                        SQL.Reader.Close();
                        SQL.ConnectionClose();
                    }
                }
            }
        }

This is the SQL class, I'm using MySQL for my database:

        using System;
        using MySql.Data;
        using MySql.Data.MySqlClient;
        using System.Windows.Forms;

        namespace NutriHelp
        {
            public class SQL
            {
                public static MySqlConnection Connection = new MySqlConnection("SERVER=localhost;DATABASE=nutrihelp;UID=root;PASSWORD=1234;");
                public static MySqlDataReader Reader;
                public static MySqlCommand Command;

            public static bool ConnectionOpen()
            {
                try
                {
                    Connection.Open();
                    return true;
                }
                catch (MySqlException ex)
                {
                    switch (ex.Number)
                    {         
                        case 0:
                            MessageBox.Show("Cannot connect to server.  Contact administrator.");
                        break;

                        case 1045:
                            MessageBox.Show("Invalid username/password, please try again.");
                        break;
                    }   
                    return false;
                }
            }

            public static bool ConnectionClose()
            {
                try
                {   
                    Connection.Close();
                    return true;
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }
            }
        }

I'm also doing inserts, updates and maybe some deletes.

UPDATE I guess I improve my using Parameters and Base64Encode I didn't want to make a very complicated encryption, like a Salt and Hash encryption, because it is a simple software for a group of nutrologist.

Regardless here's my "improve" code, sort of:

private void btnLogin_Click(object sender, EventArgs e)
    {
        string strUser = tbUser.Text;
        string strPassword = tbPassword.Text;
        if (tbUser.Text == "")
        {
            MessageBox.Show("Please input username", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (tbPassword.Text == "")
        {
            MessageBox.Show("Please input password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            if (SQL.ConnectionOpen() == true)
            {
                SQL.Command = new MySqlCommand();
                SQL.Command.CommandText = "SELECT * FROM user WHERE username=@username AND password=@password;";
                SQL.Command.Parameters.AddWithValue("@username", strUser);
                SQL.Command.Parameters.AddWithValue("@password", Base64Encode(strPassword));
                SQL.Command.Connection = SQL.Connection;
                SQL.Reader = SQL.Command.ExecuteReader();
                if (SQL.Reader.Read())
                {
                    frmMain Main = new frmMain();
                    this.Hide();
                    Main.ShowDialog();
                    tbUser.Clear();
                    tbPassword.Clear();
                    SQL.CleanConnection();
                    SQL.ConnectionClose();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("User or password are incorrect", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SQL.CleanConnection();
                    SQL.ConnectionClose();
                }
            }
        }
    }

SQL Class:

public class SQL
    {
        public static MySqlConnection Connection = new MySqlConnection("SERVER=localhost;DATABASE=nutrihelp;UID=root;PASSWORD=somepassword;");
        public static MySqlDataReader Reader;
        public static MySqlCommand Command;

        public static bool ConnectionOpen()
        {
            try
            {
                Connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server. Contact administrator.");
                        break;

                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again.");
                        break;
                }
                return false;
            }
        }

        public static bool ConnectionClose()
        {
            try
            {
                Connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public static void CleanConnection()
        {
            Reader.Dispose();
            Command.Dispose();
            Reader.Close();
        }
    }

Thanks to @Tony Tom and @Soumen Mukherjee for advice.

  • You should be using sqlcommand parameters this kind of text query is vulnerabke to sql injection attack. Also you can use some ORM frameworks they will simplify your code to a much larger extent – Soumen Mukherjee Mar 10 '19 at 05:42
  • Bad design! Not hashing passwords before storing them in database! No action to protect against Sql Injection! – Amir Molaei Mar 10 '19 at 05:46
  • Whole code can be simplified to "login successful" as you included SQL injection in the code for everyone to exploit. May as well just make everyone equal and allow everyone to pass through instead limiting login to those who can properly exploit the hole. (looks like you just need `this.Hide()` as it is what happening in success case now) – Alexei Levenkov Mar 10 '19 at 05:52

1 Answers1

1

Instead of passing inline query create a stored procedure in mysql database and pass parameters as sqlcommand parameters.

https://www.w3schools.com/sql/sql_stored_procedures.asp

And you should always store password as encrypted in database so while user enter a password you have to encrypt it and compare with the password in database.

How do I encode and decode a base64 string?

Tony Tom
  • 1,435
  • 1
  • 10
  • 17