Solved

Check Password against database

Posted on 2010-09-02
17
594 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
 
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
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.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

762 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now