here is my login button click code. i have set the session["Username"] to the input of the customer in txtUser.text.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
and here is where i call it. (ordernow.aspx) this is where the customer is redirected when he/she places and order. im planning to pass the values of the customer (email address username phone number) into the textboxes before submitting the order.
private void GetMyCart()
{
DataTable dtProducts; // declare data table = dtProducts.
if (Session["MyCart"] != null) // check whether session is null or not.
{
dtProducts = (DataTable)Session["MyCart"]; //if session is not null, assign all session to dtproducts.
}
else
{
dtProducts = new DataTable(); //if session is null, create new datatable (dtproducts).
}
if (dtProducts.Rows.Count > 0) // if rows.count is greater than 0, it means there is a value records from the session.
{
txtCustomerName.Text = Session["Username"].ToString();
//txtCustomerPhoneNo.Text = Session["Contact"].ToString();
//txtCustomerEmailID.Text = Session["Email"].ToString();
//txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
txtTotalProducts.Text = dtProducts.Rows.Count.ToString(); // this will display all of the chosen records
btnIslandGas.Text = dtProducts.Rows.Count.ToString();
dlCartProducts.DataSource = dtProducts;
dlCartProducts.DataBind();
UpdateTotalBill();
pnlMyCart.Visible = true;
pnlCheckOut.Visible = true;
pnlEmptyCart.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
}
else // session is empty
{
pnlEmptyCart.Visible = true; // since session is empty and there is no value record, pull up the empty shopping cart page
pnlMyCart.Visible = false;
pnlCheckOut.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
dlCartProducts.DataSource = null;
dlCartProducts.DataBind();
txtTotalProducts.Text = "0"; // total products, price and number logo is set to 0.
txtTotalPrice.Text = "0";
btnIslandGas.Text = "0";
}
the Session["Username"] is working. meaning it is binded with the txtCustomername.text. but the rest are not working (email,address,phone no.)
As I understand, what you are doing is that on your login page in case the user is authenticated i.e in your code when the passwords are successfully matched. The Session variables viz. Contact, Email, DeliveryAddress are not set at all. Only Name is set.
After this you make redirection to ordernow.aspx page. Hence you don't get them there. You only get one you set.
In register page you set the other Session variables but you have to understand that it's only after that they will be available in ordernow.aspx
So if you go from register to ordernow.aspx you will get the values but not when you go from login page to ordernow.aspx
You need to set the other Session variables as well in the Login page before making redirection to the ordernow page and accessing them there.
Update:
You are only getting password from the database on the basis of the username, but instead you need to get the whole user record with other details like email, contact , address as well. Then match the password, if it matches you have your user and all his other details with which you need to set Session variables.
Update Second:
if (temp == 1)
{
conn.Open();
string checkPassword = "select * from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
using (SqlDataReader oReader = passCom.ExecuteReader())
{
while (oReader.Read())
{
if(oReader["UserName"].ToString().Replace(" ", "") == txtPassword.Text.Trim())
{
Session["Username"] = oReader["FirstName"].ToString();
Session["Contact"] = oReader["Contact"].ToString();
Session["Email"] = oReader["Email"].ToString();
Session["DeliveryAddress"] = oReader["DeliveryAddress"].ToString();
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
break;
}
}
myConnection.Close();
}
}
Related
I am making a login system using C#, which successfully checks if the user's credentials match up, but for some reason, whenever I write a username that is not the newest record, it gives me the "Username doesn't exist" error, but if it is written with the correct password, it still logs in.
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data source=(local);Initial Catalog=GameStore;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Staff", conn);
//Username
String TextBoxUsername = textBox1.Text;
//Lower Casing
TextBoxUsername = TextBoxUsername.ToLower();
//Password
String TextBoxPassword = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//Username
string DatabaseUsername = (string)reader["StaffUserName"];
//Lower Casing
DatabaseUsername = DatabaseUsername.ToLower();
//Password
string DatabasePassword = (string)reader["StaffPassword"];
//If Username Matches One In DB
if (DatabaseUsername == TextBoxUsername)
{
WarningLabel.Visible = false;
WarningLabel.Text = "";
//If Password Matches One In DB
if(DatabasePassword == TextBoxPassword)
{
WarningLabel.Visible = false;
WarningLabel.Text = "";
MessageBox.Show("Logging In");
}
//Wrong Password
else
{
WarningLabel.Visible = true;
WarningLabel.Text = "Incorrect Password";
}
}
//Username doesn't exist in DB
else
{
WarningLabel.Visible = true;
WarningLabel.Text = "Username doesn't exist";
}
}
}
}
}
Yeah that's cause you are doing a select * ... and storing the data in same string variable which overwrites all the data and obviously remains with the last record and thus the behavior
while (reader.Read())
{
//Username
string DatabaseUsername = (string)reader["StaffUserName"];
Better would be filter the record based on your input like below and then your posted code should work fine
select * from stuff
where StaffUserName = #uname
and StaffPassword = #pwd;
I have multiple session variables, which both won't accept any values given to them by other variables. I have tried to debug and have found nothing. Here is the function I am using...
public void logIn(object sender, EventArgs e) //triggers when login button is clicked
{
db_connection(); //connects to database using above function
string emailAddress = email.Text.ToString();
string passwordR = password.Text.ToString(); //email and password are converted to variables
DataTable table = new DataTable();
MySqlCommand select = new MySqlCommand("SELECT personID, address_addressID from person WHERE email='" + emailAddress + "' and password = '" + passwordR + "'", connect); //brings back the person ID if user details are correct
using (MySqlDataAdapter adapter = new MySqlDataAdapter(select))
{
adapter.Fill(table);
string sessionVar = table.Rows[0]["personID"].ToString();
Session["personID"] ="";
Session["personID"] = sessionVar;
int sessionVarAddress = Int32.Parse(table.Rows[0]["address_addressID"].ToString());
Session["address_addressId"] = sessionVarAddress;
if (table.Rows.Count != 0)
{
if (Session["personID"] != null) //if the person ID is present do this following statement
{
hideDiv.Visible = false;
}
Response.Redirect("myAccount.aspx"); // if user logs in successfully redirect to my account pag
}
else
{
Response.Redirect("index.aspx"); //if login fails, home page is returned
}
connect.Close();
}
}
I have a button that when pressed, looks for a value based on a listbox choice and if it finds records in the table, it takes that value from listbox and puts it into a session, refreshes the page and the session is then used as a data source, ie. find where session = session.
Now what happens is if i want to do two consecutive searches, the button doesnt store new session, instead it takes the old session. So if I search for x first, then y, it will add x when page is refreshed.
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
JourOrigin.SelectedValue = null;
}
else
{
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
}
con.Close();
}
I managed to clear the session if there is a session already, but I have to press value twice to store it. Is it possible to "refresh" a session every time the button is pressed?
You must try this code:
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
}
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
con.Close();
}
I looked around here on stackoverflow, as well Google, but was not able to find an answer that pertained to my problem, so i'm posting it here.
I have a login page where the user is directed to input their username and password, which are both stored in a MySQL database. The username is stored as plain text and the password is hashed (using the CrackStation - https://crackstation.net/hashing-security.htm#aspsourcecode) and the hash is stored in the database. I am able to successfully have the user login one time using the username and password, but I would like to use SESSION so that the user can navigate around the website and not have to login each time they go to a different page. I was easily able to use SESSION in my test environment because the password was stored as plain text, but now with the password being hashed i'm not able to get the Session to work in my code. So I wanted to know what can I do to get the password to validate in SESSION.
My code that I am using on my login page is the following:
protected void Page_Load(object sender, EventArgs e)
{
try
{
admin = Convert.ToInt16(Request.QueryString["Admin"]);
Instructor = Convert.ToInt16(Request.QueryString["Inst"]);
if (Session["username"] == null || (string)(Session["username"]) == "")
{
token = Request.QueryString["tokenNumber"];
lblUsername.Visible = true;
txtUsername.Visible = true;
lblPassword.Visible = true;
txtPassword.Visible = true;
btnlogin.Visible = true;
}
else if (Session["username"] != null || (string)(Session["username"]) != "")
{
username = (string)Session["username"];
userType = (string)Session["userType"];
pass = (string)Session["password"];
if (userType == "Participant")
{
Response.Redirect("/srls/StudentUser");
}
else if (userType == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser");
}
else if (userType == "Instructor")
{
Response.Redirect("/srls/InstructorUser");
}
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void btnlogin_Click(object sender, System.EventArgs e)
{
char activation;
if (Request.QueryString["tokenNum"] != null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT tokenNum FROM srlslogin WHERE user_email_pk = ?";
dbCommand.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand.ExecuteNonQuery();
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.Read())
{
if (token == dataReader["tokenNum"].ToString())
{
updateActivationStatus(txtUsername.Text);
LoginWithPasswordHashFunction();
}
else
{
test.Text = "You are not authorized to login! Please activate your account following the activation link sent to your email " + txtUsername.Text + " !";
}
}
}
dbConnection.Close();
}
}
else if (Request.QueryString["tokenNum"] == null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT * FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
if (dataReader1.Read())
{
activation = Convert.ToChar(dataReader1["activation_status"]);
if (activation == 'Y')
{
activation status, activation == Y";
LoginWithPasswordHashFunction();
}
else
{
lblMessage.Text = "Please activate your account following the Activation link emailed to you at <i>" + txtUsername.Text + "</i> to Continue!";
}
}
else
{
lblMessage.Text = "Invalid Username or Password";
}
dataReader1.Close();
}
dbConnection.Close();
}
}
}
private void LoginWithPasswordHashFunction()
{
List<string> salthashList = null;
List<string> usernameList = null;
try
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT slowhashsalt, user_email_pk FROM srlslogin WHERE user_email_pk = ?;";
dbCommand.Parameters.AddWithValue(#"user_email_pk", txtUsername.Text);
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.HasRows && dataReader.Read())
{
if (salthashList == null)
{
salthashList = new List<string>();
usernameList = new List<string>();
}
string saltHashes = dataReader.GetString(dataReader.GetOrdinal("slowhashsalt"));
salthashList.Add(saltHashes);
string userInfo = dataReader.GetString(dataReader.GetOrdinal("user_email_pk"));
usernameList.Add(userInfo);
}
dataReader.Close();
if (salthashList != null)
{
for (int i = 0; i < salthashList.Count; i++)
{
bool validUser = PasswordHash.ValidatePassword(txtPassword.Text, salthashList[i]);
if (validUser == true)
{
Session["user_email_pk"] = usernameList[i];
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT user_status FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
while (dataReader1.Read())
{
user_status = dataReader1["user_status"].ToString();
Session["userType"] = user_status;
}
Response.BufferOutput = true;
if (user_status == "Participant")
{
Response.Redirect("/srls/StudentUser", false);
}
else if (user_status == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser", false);
}
else if (user_status == "Instructor")
{
Response.Redirect("/srls/InstructorUser", false);
}
dataReader1.Close();
Response.Redirect(/srls/StudentUser) - Goes to Login Page";
}
else
{
lblMessage.Text = "Invalid Username or Password! Please Try Again!";
}
}
}
}
dbConnection.Close();
}
}
catch (Exception ex)
{
}
You should not store the username and password in the session. You should store the 'fact' that the user has been successfully logged in. But actually you shouldn't even be doing that yourself. ASP.NET comes with various authentication methods. Please have a look at http://www.asp.net/identity to get started.
That is not so good solution. Don't store username's login, password, type, so on, in your sessions. Once user is logging in your system, just store his ID. I use next way: I have login page, and I have MasterPage and all my web-forms are inherited from MasterPage. And in the MasterPage on Page_Init I do something like:
string users_role = MyClass.GetUsersRoleById(Session["id"].ToString());
I have user's role in the database, so by ID I may exclude user's role. And, for example, you have by one folder for every role. You may do something like:
if (String.IsNullOrEmpty(users_role)) //if null it means that user have no any role or you didn't checked for authorization first
Response.Redirect(users_role); //redirect to role's page: e.g. Admin, User, Student, Teacher, so on.
I am building a login form. If the user attempts to login with invalid username/password for 3 attempts then the submit button must be disabled for a given duration.
How can I do that?
Here is my existing code:
protected void Button1_Click(object sender, EventArgs e)
{
int count = 0;
string username = TextBox1.Text.Trim();
string password = TextBox2.Text.Trim();
String connString = ConfigurationManager.ConnectionStrings["Myconnection"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("Login", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
conn.Open();
SqlDataReader read = cmd.ExecuteReader();
read.Read();
if (read.HasRows)
{
Session["LoggedIn"] = "correct";
Response.Redirect("WebForm2.aspx", false);
}
else
{
Label1.Visible = true;
Label1.Text = "Wrong user/password";
conn.Close();
}
if (System.Convert.ToInt32(ViewState["Tries"]) == 2)
{
Label1.Text = "Exceeded 3 times Attempts.Please Login after some time";
TextBox1.Enabled = false;
TextBox2.Enabled = false;
Button1.Enabled = false; // Button1 is the submit button
}
else
{
// Otherwise, increment number of tries.
ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1;
if (System.Convert.ToInt32(ViewState["Tries"]) == 2)
Label1.Text = "Exceeded 3 times Attempts.Please Login after some time";
}
}
For this you can create a table in your code or in database something like
LockingTime
Userid LockTime LockedDateTime
1 30 01/03/2012 12:30
As per th table
UserId = id of the user locked
LockTime - amount of time user Get locked
LockDateTime - DateTime when user account locked
When user login fails three time you enter data in table as explained...
Now when user tries to login to system you should check
select * from table name userid=#userid and GetDate() >
DATEADD (mi, LockTime, LockDateTime)
Note : query is just a suggession this not actual query as i m not added lockdate + locktime which is depends on the database and function avilable