Solved

Check Password against database

Posted on 2010-09-02
17
598 Views
Last Modified: 2013-11-27
I am trying to create a log in for a page. My goal is to have  the user hit’s the submit then  the information entered  on the username and password textboxes are checked against the table “Account_Info” with the collum names Email and Password. Now here comes the tricky part. If the username does not exist the Username and Password are saved to the database and the panel dissipates. If the Username is correct but the password is wrong it propts you to enter the correct password. AND if the user is new and new information is saved then the panel dissipates.

here is my code so far...
protected void btnSubmitUserInfo_Click(object sender, EventArgs e)
    {

        if (textBox1.Text.Trim().Length <= 0) 
        {
            Label1.Visible = true;
            Label1.Text = "Please enter User Name.";
           // MessageBox.Show("Please enter User Name and Password.", "Message", MessageBoxButtons.OK);
        }
        else if (textBox2.Text.Trim().Length <= 0)
        {
            Label1.Visible = true;
            Label1.Text = "Please enter Password.";
        }

        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
        con.Open();
        string slelectString = "Select Email, Password from Account_Info where Email = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'";
        SqlCommand cmd = new SqlCommand();
        String strResult = String.Empty;
        strResult = (String)cmd.ExecuteScalar();
        con.Close();

        if (strResult.Length > 0)
        {
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
            con.Open();
            SqlCommand cmdinsert = new SqlCommand();
            cmdinsert.CommandText = "update Account_Info set Email =" + textBox1.Text + " 
            string strInsert = "Insert into Account_Info (Email, Password) Values ("textBox1.Text +"," + textBox2.Text);
            


        }


        

    }

Open in new window

0
Comment
Question by:HawaiiDragon
  • 6
  • 5
  • 3
  • +2
17 Comments
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586236
What are you looking for?
0
 

Author Comment

by:HawaiiDragon
ID: 33586274
How to insert in to the database and also check the database to see if it exists.
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586314
you can use ExecuteNonQuery on the SQLCommand to persist

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

and subsequently use the ExecuteReader to verify it's been persisted?
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 10

Expert Comment

by:Jini Jose
ID: 33586348
you can do like below..

select count(*) from account_info where email=your email and password=your password.
take the count

if the count =0 then you can display the error message as user name or password not matching etc...

if the count=1 then it is successfull login.
so you can save the log and continue.
0
 

Author Comment

by:HawaiiDragon
ID: 33586363
not enough detail..... would it be?

System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
            con.Open();
            SqlCommand cmdinsert = new SqlCommand();
            cmdinsert.CommandText = "Insert into Account_Info (Email, Password) Values ("textBox1.Text +"," + textBox2.Text);
            cmdinsert.ExecuteNonQuery();
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586416
yes correct, that's for persisting.

using(SQLConnection conn = new SQLConnection(connString))
{
SQLCommand cmd = new SQLCommand(conn);
cmd.CommandText = "Select count(*) from Acount_Info where [Email] = <Value> AND [Password] = <value>"

SqlDataReader myReader = cmd.ExecuteReader();

while(myReader.Read())
   {
      // Verify if it's here and data is correct
   }
   myReader.Close();
}
0
 
LVL 20

Expert Comment

by:Marten Rune
ID: 33586492
Please don't store passwords in plain text. Hash them (with or without a salt, a salt is better ofcourse). Then use a hash function to compare passwords. This is how its done in a professional way.

Regards Marten
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33586523
That's true. You should never store plain passwds. Encode/Encrypt them properly. And for verification you will have Encode/Encrypt the passwd and compare against that of DB.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33586596
You also shouldn't allow user input to be used directly in a query.  Instead do something like:


SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password")
cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = textBox2.Text;

Open in new window

0
 

Author Comment

by:HawaiiDragon
ID: 33586743
getting error on ExecuteScalar(); (It states that the connection has not been established... but it has on the third line)......

System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password");
        cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
        cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
        cmd.ExecuteScalar();
        con.Close();
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33589911

try
{
	using(var con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString))
	{
		con.Open();
		SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password", con);
		cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
		cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
		cmd.ExecuteScalar();
		con.Close();
	}
}
catch(Exception e)
{
	//...
}

Open in new window

0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33589949
Er, rather, the con.Close() is no longer needed within the using statement as well.
0
 
LVL 7

Accepted Solution

by:
jdavistx earned 500 total points
ID: 33589969
Sorry for the multiple posts. I should've taken a little more time before initially posting.
SqlConnection con = new SqlConnection();
try
{
	using(var con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["strDBCourseStandard"].ConnectionString))
	{
		con.Open();
		SqlCommand cmd = new SqlCommand("SELECT Email, Password FROM Account_Info WHERE Email = @Email and Password = @password", con);
		cmd.Parameters.Add("@email", SqlDbType.Char).Value = textBox1.Text;
		cmd.Parameters.Add("@password", SqlDbType.Char).Value = textBox2.Text;
		cmd.ExecuteScalar();
	}
}
catch(Exception e)
{
	//...
}
finally
{
	con.Close();
}

Open in new window

0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33589990
finally block will throw a compile error as con is limited to using block. isn't it
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33590482
No, it's been initialized outside of the try block.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33590573
Ah, but you'd need to remove the "var" before con in the using statement. I'm apparently awesome at typos!
0
 
LVL 20

Expert Comment

by:Marten Rune
ID: 33590834
the sql portion i e 'SqlCommand cmd = new SqlCommand("SELECT Email, Password ...' ought to go against a stored proc imho.

It enhances security, speeds up the database and is considered good practice.

create a proc, that accepts username and pwd. let it do the logic in adding or verifying the user and check responce from the stored proc.

the security enhancement lies in ONLY granting execute to the proc. the underlying tables is not directly accesible for the iis worker process account. this redimes any attempt to sql inject, and also controls the damnage of a compromised application/iis server.

These simple guidelines makes a vast impact on security for your application.

//Marten
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question