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();
}
}
Related
I am creating a program to allow users of different types to login in
using the three login options done in C#.
Usertype
Username
Password
The database connection string and the query are working. I have done the login and added data without the USERTYPE variable to check connection issues. However, I'm having a problem with this snippet of code:
private void button1_Click(object sender, EventArgs e)
{
string usernamedt, passworddt;
usernamedt = username.Text;
passworddt = password.Text;
try
{
string query = "SELECT * FROM log_data WHERE username = '" + username.Text.Trim() + "' AND password = '" + password.Text.Trim() + "' ";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlco);
DataTable dt = new DataTable();
sda.Fill(dt);
string usertype = user_type.SelectedItem.ToString();
if (dt.Rows.Count > 0)
{
// state rows in table
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["usertype"].ToString() == usertype)
{
MessageBox.Show("You are logged in as " + dt.Rows[i][2]);
if (user_type.SelectedIndex == 0)
{
customer customer1 = new customer();
customer1.Show();
this.Hide();
}
else if (user_type.SelectedIndex == 1)
{
Staff staff1 = new Staff();
staff1.Show();
this.Hide();
}
else if (user_type.SelectedIndex == 2)
{
Trainer trainer1 = new Trainer();
trainer1.Show();
this.Hide();
} // end nested if*/
} //end check for user type
}// end for loop
}// end row count
else
{
MessageBox.Show("The username or password is incorrect,Try Again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} // end try block
catch
{
MessageBox.Show("Error ");
}
finally
{
sqlco.Close();
}
} // end button LOG IN CLICK
I'm student and I have one project, to make a program and database for Coffee shop.
I have login window and it's connected with mysql database. You have only textbox for enter password and when you enter correct password(password is in database) you are logged on, and move to another form(main interface). Now I want to only display name of logged user and I don't know how to...
This is the code, I'm from Croatia so some of words are Croatian.
public void button_1_Click(object sender, EventArgs e)
{
string upit = "SELECT * FROM zaposlenik WHERE sifra_z = '" + textbox_prijava.Text+"'";
string manager = "SELECT * FROM manager WHERE sifra_m = '" + textbox_prijava.Text + "'";
MySqlDataAdapter sda = new MySqlDataAdapter(upit, connection);
DataTable tablica = new DataTable();
sda.Fill(tablica);
MySqlDataAdapter sda2 = new MySqlDataAdapter(manager, connection);
DataTable tablica2 = new DataTable();
sda2.Fill(tablica2);
if (tablica.Rows.Count >= 1 || tablica2.Rows.Count >= 1)
{
GlavnoSučelje x = new GlavnoSučelje();
x.Show();
this.Hide();
}
else if (textbox_prijava.Text == "")
{
MessageBox.Show("Niste upisali šifru!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Kriva šifra konobara!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
textbox_prijava.Clear();
This is what I would do.
Have a static class to save user details:
public class UserDetails
{
private static string _username;
public static string Username
{
get
{
return _username;
}
set
{
_username = value;
}
}
}
Here we are logging in and saving user details.
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
//Login Button
private void loginBtn(object sender, EventArgs e)
{
//MySQL connection to retrieve user details into a class on successful log in
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
conn.Open();
//Get count, username
using (var cmd = new MySqlCommand("select count(*), username from users where username = #username and password = MD5(#password)", conn))
{
cmd.Parameters.AddWithValue("#username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#password", passwordTextBox.Text);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
//Check whether user exists
if (dt.Rows[0][0].ToString() == "1")
{
//If the user exist - allow to log in
//Store the information from the query to UserDetails class to be used in other forms
UserDetails.Username = dt.Rows[0][1].ToString();
//Hide this form and open the main Dashboard Form
this.Hide();
var dashboard = new Dashboard();
dashboard.Closed += (s, args) => this.Close();
dashboard.Show();
}
//If failed login - show message
else
{
MessageBox.Show("Login failed", "Technical - Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
}
To use the username.. just simply use UserDetails.Username
I am using session to carry the value to another page in ASP.NET using C#, but the page I am redirecting to is getting null value. However, I tried passing value through session in simple application, and it's working well. Please help me out where am I going wrong?
// Login.aspx.cs
con.Open();
cmd = new SqlCommand("select Username, Password, Fname from Customer where Username = '" + txtCust.Text + "' and Password = '" + txtPass3.Text + "'",con);
rd = cmd.ExecuteReader();
if (rd.Read())
{
a = rd.GetValue(0).ToString();
b = rd.GetValue(1).ToString();
c = rd.GetValue(2).ToString();
}
con.Close();
if (a != txtCust.Text)
Response.Write("<script>alert('Invalid Username')</script>");
else if (b != txtPass3.Text)
Response.Write("<script>alert('Invalid Password')</script>");
else
{
Session["user"] = c;
Response.Redirect("Customer_Home.aspx");
}
// Customer_Home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
lblUser.Text = Session["user"].ToString();
}
else
{
lblUser.Text = "No value returned";
}
}
I expect the output of the above code to be "Fname", but the actual output is "No value returned"
This code seems to have no problem. But you can try using QueryString.
// Login.aspx.cs
Response.Redirect("Customer_Home.aspx?user=" + Server.UrlEncode(c);
// Customer_Home.aspx.cs
string value = Request.QueryString["user"].ToString();
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.
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();
}
}