How to get logged user id c# - c#

I created simple login page but I got problem with getting logged in user ID
public partial class LoginwithEncryption : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"select * from dbo.UserInfo where Login =#Login and Password=#Password", con);
cmd.Parameters.AddWithValue("#Login", txtUserName.Text);
cmd.Parameters.AddWithValue("#Password", txtPWD.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("StartPage.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation",
"<script language='javascript'>alert('Invalid UserName and Password')</script>");
}
}
}
How can I get ID of user after login (im able to login) ? I tried few methods but it wont work ;(
My database:

You could store the username in a Session variable. For example:
if (dt.Rows.Count > 0)
{
//Store username in session
Session["UserName"] = txtUserName.Text;
Response.Redirect("StartPage.aspx");
}
You can then retrieve it on following pages like:
if (Session["UserName"] != null)
{
Literal1.Text = (string)Session["UserName"];
}

Based on the info you have provided all you have to do is just extract the row data from the datatable containing the logged in user.
For example:
//Extract data
User objUser = new User();
objUser.Id = int.parse(dt.Rows[0]["ID"].ToString());
objUser.Login = dt.Rows[0]["Login"].ToString();
objUser.Password = dt.Rows[0]["Password"].ToString();
objUser.Type= int.parse(dt.Rows[0]["Password"].ToString());

Related

ASP.NET C# Login with Roles is not Redirecting

I want to create a login module with roles. I have two tables Users and UserType.
The problem is after clicking the login it does not redirect to assigned pages, its still in the login page.
Here's the Login.cs code
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT u.UserID, u.Username, u.Password, t.UserType FROM Users u INNER JOIN UserType t ON t.TypeID = u.TypeID WHERE Username=#Username AND Username=#Username";
//string query = #"SELECT UserID, Username, Password, TypeID FROM Users WHERE Username=#Username AND Username=#Username";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPassword.Text));
DataTable dt = new DataTable();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
Session["UserID"] = dr["UserID"].ToString();
}
if (dt.Rows.Count != 0)
{
string Utype;
Utype = dt.Rows.ToString().Trim();
if (Utype == "HR Admin")
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/Administrator/Home.aspx");
}
if (Utype == "Employee")
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/HrPortal/Home.aspx");
}
}
}
else
{
error.Visible = true;
}
}
}
}
}

c# validating login with sql database

protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
lblMessage.Text = "Invalid login credentials";
}
else
{
Response.Redirect("SubmitViewingRequest.aspx");
}
}
the codes above doesn't validate the email address and password with the database. any email address and password entered is considered correct. can i get help? thank you!
Change your if condition
if (result.Tables["Login"].Rows.Count > 0) // For Successfully Login
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else // For Invalid User credentials
{
lblMessage.Text = "Invalid login credentials";
}
This happens when we mistakenly put if conditions in reverse order. Please change your code with if conditions replaced like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else
{
lblMessage.Text = "Invalid login credentials";
}
}
Hope this helps

Admin and User Login C#

I'm using Access db. I need to validate if its Admin or user because I want to open different forms for them. But I can't find a way to do it. I used a checkbox to register if the employee is admin or not like this:
private void button2_Click(object sender, EventArgs e)
{
string strincon = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\flavi\Desktop\Pet&Shop.2\PetShop\TelaAbertura\bin\Debug\DatabasePS.mdb;Persist Security Info=True";
string comando = "INSERT INTO Funcionario (Nome, Login, Senha, Email, Cargo, Admin) Values (#Nome, #Login, #Senha, #Email, #Cargo, #Admin) ";
OleDbConnection con = new OleDbConnection(strincon);
OleDbCommand com = new OleDbCommand(comando, con);
com.Parameters.Add("#Nome", OleDbType.VarChar).Value = txtNome.Text;
com.Parameters.Add("#Login", OleDbType.VarChar).Value = txtLogin.Text;
com.Parameters.Add("#Senha", OleDbType.VarChar).Value = txtSenha.Text;
com.Parameters.Add("#Email", OleDbType.VarChar).Value = txtEmail.Text;
com.Parameters.Add("#Cargo", OleDbType.VarChar).Value = txtCargo.Text;
com.Parameters.Add("#Admin", OleDbType.Boolean).Value = checkBox1.Checked;
This is working fine, but in the login form there's no difference because I don't know how to validate the checkbox with the login and password, so it's like this.
OleDbDataAdapter da;
DataTable dt = new DataTable();
da = new OleDbDataAdapter("Select * from Funcionario where Login='" + txtLogin.Text + "'and Senha= '" + txtSenha.Text + "'", con); //Senha = Password
da.Fill(dt);
if (dt.Rows.Count > 0)
{
FrmPrincipal frm = new FrmPrincipal();
frm.Show();
this.Visible = false;
}
else
{
MessageBox.Show("Login ou Senha Inválidos", "Ocorreu um Erro de Autenticação", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLogin.Clear();
txtSenha.Clear();
}
if (dt.Rows.Count > 0)
{
// you should have one row in the table. check for admin.
if(dt.Rows[0]["Admin"] == true)
{
etc.
As stated in the comments, add parameters to your adapter's query. Always use parameters. They are used to "clean" user input, if someone is trying to hack your database.

How to get value of DataTable Row in C# asp.net

i am learning asp.net with c# by myself, and i have a problem with DataRows,
in db i have users table and there is isadmin column which value is int,
i want to redirect users to different page and admins to admin page, but the problem is all users redirects to admin page.
Here is my code;
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT username, pass FROM users
where username = '"+txtUser.Text+"'
and pass='"+txtPass.Text+"'"
, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
SqlCommand cmd1 = new SqlCommand("Select username, isadmin From users", conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt1.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
/*Response.Write("<script>
alert('Please enter valid Username and Password')
</script>"); */
}
Can you please tell me what is wrong?
Use the first query with dt as it's based on a single user. The problem is dt1 gets all users and the first record in that datatable is an admin
if (dt.Rows[0]["isadmin"].ToString() == "1") {
Remove the second query with dt1 and make sure you add isadmin to the first SQL query.
SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = #UserName and pass= #Pass", conn);
See how I use parameterized username and password, that is to protect against SQL injection, definitely read up on that!!!
Please Try this
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd =
new SqlCommand(
"SELECT username, pass, isadmin FROM users where username = '" + txtUser.Text + "' and pass='" + txtPass.Text +
"'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
In your first query you need to get isadmin also and on the base of that result you can check either it is 1 or not and can redirect to what ever page you like. So it will be as follow:
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = '"+txtUser.Text+"' and pass='"+txtPass.Text+"'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
There are several things wrong with your code:
All users are redirected to the admin page since you are checking the isAdmin in the wrong query.
Your second query has no where clause which means it will return all the users in the table. The first user it returns has the isAdmin value of 1.
You don't actually need two queries, just one.
You must use parameterized queries, otherwise you are leaving an open door to SQL injection attacks.
wrap all IDisposable instances in a using statement.
Your code should look more like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(conString))
{
using(SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = #UserName and pass=#Pass", conn))
{
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUser.Text;
cmd.Parameters.Add("#Pass", SqlDbType.VarChar).Value = txtPass.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt1.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
Your second query lacks the filter on a user name:
Select username, isadmin From users
So whatever it fetches - if the first row contains 1 as IsAdmin, all users will be redirected to the admin page.

i want to view the profile(details) of a specific logged customer from sql database to gridview

here is my viewprofile.aspx code where the binding will take place. im planning to bind my data in sql to my gridview but it is showing me all of the data(from sql) instead of that of the specific logged in customer. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
bindgrid();
}
}
public void bindgrid()
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select * from UserData WHERE Username = Username ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select * from UserData WHERE Username = Username", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
it is showing me all of the data(from sql) instead of that of the
specific logged in customer
That's because of the WHERE condition in your SELECT query which says WHERE Username = Username which is a TAUTOLOGY and will always be TRUE and so fetching all rows.
In essence your SELECT query is just doing
select * from UserData;
You need to specify the logged in customerid in WHERE condition to get his/her record.
Considering that you have a variable named Username in your ASP.NET code where you have stored current logged in customer name; then change your code like below
SqlCommand cmd = new SqlCommand("select * from UserData WHERE Username = #Username ", conn);
cmd.Parameters.AddWithValue("#Username", Username);
da.SelectCommand = cmd;

Categories

Resources