I need to check in C# if the user has a particular role from the database and in windows form my login code is
SqlCommand cmd = new SqlCommand("SELECT UserName,Password FROM EMP_Info WHERE UserName='" + txt_Username.Text + "' and Password='" + txt_password.Text + "'", sqlcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
// I need to make if here to check the role if the user is admin or not
// if admin do something
MessageBox.Show("Welcome " + txt_Username.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
sqlcon.Close();
}
My database code
create proc Check_role
#EMP_Role varchar (10),
as
begin
if (exists(select EMP_Role from EMP_Info where EMP_Role ='Admin' ))
return 1
else
return 2
end
so i need to solve this problem
To avoid SQL Inject Attack use parametrized query something like this.....
SqlCommand cmd = new SqlCommand("SELECT [UserName] , [Password] FROM EMP_Info WHERE [UserName] = #UserName and [Password] = #Password", sqlcon);
cmd.Parameters.AddWithValue("#UserName" , txt_Username.Text);
cmd.Parameters.AddWithValue("#Password" , txt_password.Text);
//rest of the code
Anyway I would create a procedure to make just one call to database to verify the user logging in. A stored procedure can look something like ....
CREATE PROCEDURE Check_role
#UserName VARCHAR(100)
,#Password VARCHAR(100)
,#IsValid INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Emp_Role VARCHAR(10);
DECLARE #UserName_check VARCHAR(10);
DECLARE #PassWord_check VARCHAR(10);
SELECT TOP 1 #Emp_Role = EMP_Role
,#UserName_check = [UserName]
,#PassWord_check = [Password]
FROM EMP_Info
WHERE [UserName] = #UserName
AND [Password] = #Password
IF ((#UserName_check = #UserName) AND (#PassWord_check = #Password))
BEGIN
SET #IsValid = 1;
IF (#Emp_Role = 'Admin')
BEGIN
SET #IsValid = 2;
END
END
ELSE
BEGIN
SET #IsValid = 0;
END
END
C# Code
using(SqlConnection Sqlcon = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("dbo.Check_role", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName", txt_Username.Text);
cmd.Parameters.AddWithValue("#Password", txt_password.Text);
cmd.Parameters.Add("#IsValid", SqlDbType.Int);
cmd.Parameters["#IsValid"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
string LoginStatus = cmd.Parameters["#IsValid"].Value.ToString();
if (LoginStatus == 1 || LoginStatus == 2)
{
if(LoginStatus == 2)
{
// if a user is admin do stuff here
}
else
{
// if a user is NOT admin do stuff here
}
MessageBox.Show("Welcome " + txt_Username.Text);
}
else
{
MessageBox.Show("The Username or Password you entered is incorrect. Please try again");
}
}
Related
I currently working on Linq to Sql. I have some knowledge write the linq query and how to convert it but with this query I am facing some problems . Any one can help me what will this linq query for this following sql query.
Here is store procedure .The name of procedure is spAuthenticateUser..
CREATE proc [dbo].[spAuthenticateUser]
#UserName nvarchar(100),
#Password nvarchar(200)
as
Begin
Declare #AccountLocked bit
Declare #Count int
Declare #RetryCount int
Select #AccountLocked = IsLocked
from tblUsers where UserName = #UserName
--If the account is already locked
if(#AccountLocked = 1)
Begin
Select 1 as AccountLocked, 0 as Authenticated, 0 as RetryAttempts
End
Else
Begin
-- Check if the username and password match
Select #Count = COUNT(UserName) from tblUsers
where [UserName] = #UserName and [Password] = #Password
-- If match found
if(#Count = 1)
Begin
-- Reset RetryAttempts
Update tblUsers set RetryAttempts = 0
where UserName = #UserName
Select 0 as AccountLocked, 1 as Authenticated, 0 as RetryAttempts
End
Else
Begin
-- If a match is not found
Select #RetryCount = IsNULL(RetryAttempts, 0)
from tblUsers
where UserName = #UserName
Set #RetryCount = #RetryCount + 1
if(#RetryCount <= 3)
Begin
-- If re-try attempts are not completed
Update tblUsers set RetryAttempts = #RetryCount
where UserName = #UserName
Select 0 as AccountLocked, 0 as Authenticated, #RetryCount as RetryAttempts
End
Else
Begin
-- If re-try attempts are completed
Update tblUsers set RetryAttempts = #RetryCount,
IsLocked = 1, LockedDateTime = GETDATE()
where UserName = #UserName
Select 1 as AccountLocked, 0 as Authenticated, 0 as RetryAttempts
End
End
End
End
GO
Here is ADO.NET CODE ..
public bool AuthenticateUser(UserLogin userLogin)
{
// ConfigurationManager class is in System.Configuration namespace
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
cmd.CommandType = CommandType.StoredProcedure;
//Formsauthentication is in system.web.security
string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");
//sqlparameter is in System.Data namespace
SqlParameter paramUsername = new SqlParameter("#UserName", userLogin.Username);
SqlParameter paramPassword = new SqlParameter("#Password", encryptedpassword);
cmd.Parameters.Add(paramUsername);
cmd.Parameters.Add(paramPassword);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);
if (Convert.ToBoolean(rdr["AccountLocked"]))
{
return true;
}
else if (RetryAttempts > 0)
{
int AttemptsLeft = (4 - RetryAttempts);
//lblMessage.Text = "Invalid user name and/or password. " +
// AttemptsLeft.ToString() + "attempt(s) left";
}
else if (Convert.ToBoolean(rdr["Authenticated"]))
{
return true;
}
}
return false;
}
}
Thanks .
I would like to parse the user already signed-up email-address into my master page without asking user to enter it from login page. From the AuthenticateUser function, I'm able to parse username into my my master page correctly by "string loginName " because I get it by user key in through log in module. Just don't know how to get email since user do not key in.
protected void btnLogin_Click(object sender, EventArgs e)
{
if (AuthenticateUser(txtUserName.Text, txtPassword.Text))
{
// Create the authentication cookie and redirect the user to welcome page
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkBoxRememberMe.Checked);
Response.Redirect("homePage.aspx");
}
else
{
lblMessage.Text = "Invalid UserName and/or password";
}
}
private bool AuthenticateUser(string username, string password)
{
// ConfigurationManager class is in System.Configuration namespace
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
string loginEmail = "";
string loginName = "";
SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
// SqlDataReader reader;
cmd.CommandType = CommandType.StoredProcedure;
// FormsAuthentication is in System.Web.Security
string EncryptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
// SqlParameter is in System.Data namespace
SqlParameter paramUsername = new SqlParameter("#UserName", username);
SqlParameter paramPassword = new SqlParameter("#Password", EncryptedPassword);
//SqlParameter paramEmail = cmd.Parameters.Add("#Email", SqlDbType.NVarChar);
//SqlParameter paramEmail = new SqlParameter("#Email", SqlDbType.NVarChar);
cmd.Parameters.Add(paramUsername);
cmd.Parameters.Add(paramPassword);
// cmd.Parameters.Add(paramEmail);
loginName = paramUsername.ToString();
// loginEmail = paramEmail.ToString();
con.Open();
// reader = cmd.ExecuteReader();
int ReturnCode = (int)cmd.ExecuteScalar();
Session["Status"] = "Login";
Session["LoginName"] = username;
Session["LoginEmail"] = loginEmail;
return ReturnCode == 1;
}
}
database:
CREATE TABLE [dbo].[tblUsers] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (100) NULL,
[Password] NVARCHAR (400) NULL,
[Email] NVARCHAR (200) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
stored procedure : spAuthenticateUser
CREATE Procedure spAuthenticateUser
#UserName nvarchar(100),
#Password nvarchar(400)
as
Begin
Declare #Count int
Select #Count = COUNT(UserName) from tblUsers
where [UserName] = #UserName and [Password] = #Password
if(#Count = 1)
Begin
Select 1 as ReturnCode
End
Else
Begin
Select -1 as ReturnCode
End
End*
When someone log into your website, you can write his ID in the session.
So in your log in you have something like that
Select * from [user] where password=#password and email=#email
Here you will take the User.ID and write it in the session so you will know which user is in your website.
Session["__UserID"] = row["ID"]// row from previous query.
Now when you need some data for the logged user you just take from the session his ID and make a query to fetch the data.
P.S If you need to store more data in the session on log in, it is best practise to create class and write it in the session. In this class you will have UserID, UserName or whatever you want as properties.
I am working on group level login system in asp.net and SQL server. This script works fine but how do implement group level security system if the user is admin should be directed to admin page and user should be redirected to users page
private bool AuthenticateUser(string username, string password)
{
string cs = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("sp_authenticateuser", con);
cmd.CommandType = CommandType.StoredProcedure;
string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(Login1.Password, "SHA1");
SqlParameter parmusername = new SqlParameter("#UserName", Login1.UserName);
SqlParameter parmpassword = new SqlParameter("#Password", encryptedpassword);
cmd.Parameters.Add(parmusername);
cmd.Parameters.Add(parmpassword);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
//it will get Only one row will be ExecuteScalar();
return ReturnCode == 1;
}
}
If user is and password is correct here should be the trick
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (AuthenticateUser(Login1.UserName, Login1.Password))
{
Session["Username"] = Login1.UserName;
Response.Redirect("Home.aspx");
}
else
lab_status.Text = "Invalid User";
}
}
Procedure to validate user with return code
create procedure [dbo].[sp_authenticateuser]
#Username varchar(100),
#Password varchar(100)
as
begin
declare #count int
select #count = count(Username) from users
where Username=#UserName and pass=#Password
if (#count=1)
begin
select 1 as ReturnCode
end
else
begin
select -1 as ReturnCode
end
end
GO
Table Structure
CREATE TABLE [dbo].[users](
[usid] [int] IDENTITY(100,1) NOT NULL,
[Username] [varchar](100) NULL,
[pass] [varchar](100) NULL,
[Email] [varchar](100) NULL,
[Roles] [int]
constraint [pk_uid] PRIMARY KEY CLUSTERED
);
The script works perfectly now but how to redirect user to admin page if he is admin something like
if(AuthenticateUser(userrole=='1'){
response.redirect("admin.aspx");
}else{
response.redirect("users.aspx");
}
if(RadioButton1.Checked)
{
if (txtUsername.Text == "admin" && txtPassword.Text == "admin")
Response.Redirect("Default.aspx");
else
//Response.Write("error");
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Enter Currect Passward');", true);
}
else if (RadioButton2.Checked)
{
string query = "SP_StudLogin";
SqlCommand com = new SqlCommand(query,con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#username", txtUsername.Text.ToString()); //for username
com.Parameters.AddWithValue("#password", txtPassword.Text.ToString()); //for password
con.Open();
//int usercount = (int)com.ExecuteScalar();// for taking single value
int usercount = (Int32)com.ExecuteScalar();
con.Close();
if (usercount == 1) // comparing users from table
{
Response.Redirect("DeafultStaff.aspx"); //for sucsseful login
}
else
{
//lblmsg.Text = "Invalid User Name or Password"; //for invalid login
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Enter Currect Passward');", true);
}
}
I am the admin who wants to change the password for anyone by entering their email address and the new password in textbox.The stored procedure is as below:
Alter proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS (SELECT * FROM tblRegister WHERE Email=#Email)
begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 0
end
ELSE
BEGIN
Select -1
end
end
and the code-behind is as below:
private void ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ChangePassword();
}
But i want to check if the email exists in the table using if and else statements.If the email exists then change password else throw an exception.What can i do?
You could simply change a bit the code of your procedure and have it to return a value.
0 would mean that the password updated and -1 that there is not an email like the one provided.
ALTER proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
AS
BEGIN
IF EXISTS (SELECT * FROM Users WHERE Email=#Email) THEN
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 0 AS Result
END
ELSE
BEGIN
SELECT -1 AS Result
END
END
Then you have to read the result of the stored procedure and act correspondingly. So your server side code must be changed to the following:
var reader = cmd.ExecuteReader();
while (reader.Read())
{
if(int.Parse(reader["Result"].ToString())==0)
{
// success
}
else
{
// failure
}
};
update In the if statement, you could also use this one:
Convert.ToInt32(reader["Result"])==0
I think it will work like a charm.
Inside your Stored procedure add this
Begin
DECLARE #id AS INT
SELECT #id = tblRegisterId FROM tblRegisterWHERE Email =#Email
IF #id IS not NULL
Begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 1
End
Else
Begin
Select 0
End
End
Try this :-
private bool ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool success = ChangePassword(); //Use this success variable to show a message.
}
You can also change your stored procedure, but it wont throw any exception, only it will check. If the Email exists, it will execute the update query :-
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
end
SQL
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
ELSE
BEGIN
RAISEERROR('Email does not exists',0,1)
END
end
c#
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
try{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
catch(SqlException ee)
{
...
}
}
Try this Store Procedure ( Please use IF EXISTS)
CREATE PROCEDURE InsertName
(
#Email varchar(25),
#Passwordd varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM tblRegister WHERE Email = #Email)
BEGIN
--This means it exists,update
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 'Changed successfully'
END
ELSE
BEGIN
--This means the record isn't in there already
SELECT 'Does Not Exist'
END
private string ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
return cmd.ExecuteNonQuery().ToString();
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
returning int value from stored procedure and check it in asp.net code to validate login form
hello all please i need help in this code as it is stored procedure validate username and password , the problem here is that form validate any data even it doesn't stored in database and i tried to fix code many times but really i haven't any more thing to do in it , any one can help me to solve this problem
this is stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[login_procedure] #username Varchar =50, #password varchar=50, #result int OUTPUT
as
Declare #user_name varchar , #pass_word varchar
Set #user_name = #username
Set #pass_word = #password
if EXISTS (select #username , #password from data where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
and this is asp.net code
SqlConnection conn = new SqlConnection ("Data Source=ANAGUIB-LAPNEW\\SQLEXPRESS;Initial Catalog=account;Integrated Security=True");
SqlCommand cmd = new SqlCommand("login_procedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "#result";
paramReturnValue.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(paramReturnValue);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
conn.Open();
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
int resultID = Convert.ToInt32(cmd.ExecuteScalar());
if (Convert.ToInt32(resultID) == 0)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
conn.Close();
}
Your stored-procedure has OUTPUT parameter and it is good practice to access value of output parameter after closing the connection.
I've changed proc.
ALTER PROCEDURE login_procedure
#username Varchar(50),
#password varchar(50),
#result int OUTPUT
AS
IF EXISTS (select username from data where username= #username and password=#password)
set #result=1
else
set #result=0
Demo: How to pass parameters (IN and OUT)?
SqlConnection cn = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "login_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter("#username", System.Data.SqlDbType.VarChar, 50);
SqlParameter param2 = new SqlParameter("#password", System.Data.SqlDbType.VarChar, 50);
SqlParameter resultParam= new SqlParameter("#result", System.Data.SqlDbType.Int);
resultParam.Direction = System.Data.ParameterDirection.Output;
param1.Value = TextBox1.Text;
param2.Value = TextBox2.Text;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(resultParam);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int retVal;
int.TryParse(resultParam.Value.ToString(),out retVal);
if(retVal==1)
//
else
//
In this code
if EXISTS (select #username ,
#password
from data
where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
You are returning 1 if the given input is validated in your C# code you are giving error when the return value is not 0, that is why every input even which does not exist in your table is validated.Try this;
if (resultID == 1)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
And you do not have to Convert the return value of stored procedure twice, once is enough.