create table tblLoginStatus(
id bigint identity(1,1) primary key,
login_Code nvarchar(100),
login_Id nvarchar(200),
first_login_time datetime,
last_login_time datetime
)
Create a procedure :
create proc SP_VerifyUserAtLoginTime(
@login_Code nvarchar(100)='',
@login_Id nvarchar(200)='',
@first_login_time datetime='',
@last_login_time datetime='',
@option nvarchar(100)=''
)
as
begin
if @option='insertupdate'
begin
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM tblLoginStatus WHERE login_Id = @login_Id)
BEGIN
UPDATE tblLoginStatus set
login_Code=@login_Code,
last_login_time=@last_login_time where login_Id=@login_Id
END
ELSE
begin
INSERT into tblLoginStatus(login_Code,login_Id,first_login_time,last_login_time)
values(@login_Code,@login_Id,@first_login_time,@last_login_time)
END
COMMIT TRANSACTION;
end
if @option='verify_user_login'
begin
Declare @Count int
Declare @ReturnCode int --check email already exist
select @Count=COUNT(login_Id)
from tblLoginStatus
where login_Id=@login_Id and login_Code=@login_Code
if @Count>0
begin
set @ReturnCode=1
end
else
begin
set @ReturnCode=-1
end
select @ReturnCode as ReturnCode
end
end
Add the following line of code in web.config file :
<appSettings>
<add key="ConnectionString" value="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=database_Name;Integrated Security=True"/>
<add key="smtp" value="smtp.xyz.com"/>
<add key="portnumber" value="587"/>
<add key="username" value=“xyz@xyz.com"/>
<add key="password" value=“your_password
<add key="IsSSL" value="true"/>
<add key="EmailTemplateFolderPath" value="EmailTemplate"/>
</appSettings>
Create a class name as CheckLoginStatus
public class CheckLoginStatus
{
public int id { get; set; }
public string login_Code { get; set; }
public string login_Id { get; set; }
public DateTime first_login_time { get; set; }
public DateTime last_login_time { get; set; }
public string option { get; set; }
}
Create class name as LoginStatusBL for connect with database
public class LoginStatusBL
{
public static string StringCon = null;
SqlConnection conn = null;
SqlCommand cmd = null;
public LoginStatusBL()
{
StringCon = ConfigurationManager.AppSettings["ConnectionString"];
conn = new SqlConnection(StringCon);
}
public bool insertUpdateLoginStatus(CheckLoginStatus loginStatus)
{
try
{
conn.Open();
cmd = new SqlCommand("SP_VerifyUserAtLoginTime", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@login_Code", loginStatus.login_Code);
cmd.Parameters.AddWithValue("@login_Id", loginStatus.login_Id);
cmd.Parameters.AddWithValue("@first_login_time", loginStatus.first_login_time);
cmd.Parameters.AddWithValue("@last_login_time", loginStatus.last_login_time);
cmd.Parameters.AddWithValue("@option", loginStatus.option);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
return true;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return false;
}
public int verifiyLoginStatus(CheckLoginStatus loginStatus)
{
try
{
conn.Open();
cmd = new SqlCommand("SP_VerifyUserAtLoginTime", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@login_Code", loginStatus.login_Code);
cmd.Parameters.AddWithValue("@login_Id", loginStatus.login_Id);
cmd.Parameters.AddWithValue("@option", loginStatus.option);
return (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return -1;
}
}
Create asp web page name as login and add the following code :
<div class="container">
<div class="row">
<form id="frm_login" runat="server" name="login">
<div class="col-md-6 col-sm-6 col-xs-12" style="margin-top: 10rem;" id="loginFormHtml" runat="server">
<p class="mar-kan-text">Enter your credentials to get access.</p>
<br />
<br />
<div class="form-group">
<label for="exampleInputEmail1">Login</label>
<input type="email" class="form-control" id="txtEmail" runat="server" placeholder="Example@client.com" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" id="txtPassword" runat="server" class="form-control" placeholder="">
<asp:Label ID="lblError" runat="server"></asp:Label>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 button-po-su">
<div class="col-md-6 col-sm-6 col-xs-6 wrapper text-center ">
<asp:Button ID="btnLogin" runat="server" class="btn btn-info lg_btn" Text="Login" OnClick="btnLogin_Click" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 wrapper text-center">
<asp:Button ID="btnForgetPassword" runat="server" class="btn btn-info lg_btn" OnClick="btnForgetPassword_Click" Text="Forgot Password" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12" style="margin-top: 10rem;" id="verifyFormHtml" runat="server" visible="false">
<p class="mar-kan-text">Two factor authentication</p>
<br />
<br />
<div class="form-group">
<input type="hidden" class="form-control" id="txtHidenEmail" runat="server" placeholder="Example@client.com" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">A message with a passcode was sent to your email</label>
<input type="text" id="txtPasscode" runat="server" class="form-control" placeholder="">
<asp:Label ID="lblVerifyError" runat="server"></asp:Label>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 button-po-su">
<div class="col-md-6 col-sm-6 col-xs-6 wrapper text-center ">
<asp:Button ID="btnVerify" runat="server" class="btn btn-info lg_btn" Text="Login" OnClick="btnVerifyUser_Click" />
</div>
</div>
</div>
</form>
</div>
</div>
Now add the following code in cs file of login.aspx page :
public partial class Login : System.Web.UI.Page
{
User u = null;
UserBL uBL = new UserBL();
Common common = new Common();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender,EventArgs e)
{
if (txtEmail.Value == "")
{
lblError.Text = "Email id Required!";
return;
}
else
{
lblError.Text = "";
}
if (txtPassword.Value == "")
{
lblError.Text = "Password Required!";
return;
}
else
{
lblError.Text = "";
}
u = uBL.checkUserLogin(txtEmail.Value.Trim(), txtPassword.Value.Trim());//common.Encrypt(txtPassword.Value.Trim())
if (u != null)
{
CheckLoginStatus checkLoginStatus = new CheckLoginStatus();
LoginStatusBL loginStatusBL = new LoginStatusBL();
checkLoginStatus.login_Code = GenerateOTPCode(8);
checkLoginStatus.login_Id = txtEmail.Value.Trim();
checkLoginStatus.first_login_time = System.DateTime.Now;
checkLoginStatus.last_login_time = DateTime.Now;
checkLoginStatus.option = "insertupdate";
if (loginStatusBL.insertUpdateLoginStatus(checkLoginStatus))
{
Session["userType"] = u.userType;
Session["profile_Pic"] = u.profile_Pic;
Session["uName"] = u.first_Name + " " + u.last_Name;
txtHidenEmail.Value = checkLoginStatus.login_Id;
verifyFormHtml.Visible = true;
loginFormHtml.Visible = false;
sendMailUsingTemplate(checkLoginStatus.login_Code, checkLoginStatus.login_Id);
}
}
else
{
lblError.Text = "Wrong email id or password!";
}
}
protected void btnVerifyUser_Click(object sender, EventArgs e)
{
CheckLoginStatus checkLoginStatus = new CheckLoginStatus();
LoginStatusBL loginStatusBL = new LoginStatusBL();
checkLoginStatus.login_Code = txtPasscode.Value;
checkLoginStatus.login_Id = txtHidenEmail.Value.Trim();
checkLoginStatus.option = "verify_user_login";
if (loginStatusBL.verifiyLoginStatus(checkLoginStatus) == 1)
{
Session["userId"] = txtHidenEmail.Value.Trim();
Response.Redirect("Welcome.aspx");
}
else
{
lblVerifyError.Text = "Wrong Passcode! Please fill correct one.";
verifyFormHtml.Visible = true;
loginFormHtml.Visible = false;
}
}
public string GenerateOTPCode(int length)
{
const string valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public void sendMailUsingTemplate(string verify_Code, string To)
{
//Fetching Settings from WEB.CONFIG file.
string emailSender = ConfigurationManager.AppSettings["username"].ToString();
string emailSenderPassword = ConfigurationManager.AppSettings["password"].ToString();
string emailSenderHost = ConfigurationManager.AppSettings["smtp"].ToString();
int emailSenderPort = Convert.ToInt16(ConfigurationManager.AppSettings["portnumber"]);
Boolean emailIsSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSSL"]);
string FolderPath = ConfigurationManager.AppSettings["EmailTemplateFolderPath"];
FolderPath = FolderPath + "\\verify_account.html";
string FilePath = Server.MapPath(FolderPath);
StreamReader str = new StreamReader(FilePath);
string MailText = str.ReadToEnd();
str.Close();
//Repalce [newusername] = signup user name
MailText = MailText.Replace("[verfify_code]", verify_Code);
string subject = "Your one-time password";
//Base class for sending email
MailMessage _mailmsg = new MailMessage();
//Make TRUE because our body text is html
_mailmsg.IsBodyHtml = true;
//Set From Email ID
_mailmsg.From = new MailAddress(emailSender);
//Set To Email ID
_mailmsg.To.Add(To);
//Set Subject
_mailmsg.Subject = subject;
//Set Body Text of Email
_mailmsg.Body = MailText;
//Now set your SMTP
SmtpClient _smtp = new SmtpClient();
//Set HOST server SMTP detail
_smtp.Host = emailSenderHost;
//Set PORT number of SMTP
_smtp.Port = emailSenderPort;
//Set SSL --> True / False
_smtp.EnableSsl = emailIsSSL;
//Set Sender UserEmailID, Password
NetworkCredential _network = new NetworkCredential(emailSender, emailSenderPassword);
_smtp.Credentials = _network;
//Send Method will send your MailMessage create above.
_smtp.Send(_mailmsg);
}
protected void btnForgetPassword_Click(object sender,EventArgs e)
{
Response.Redirect("#");
}
}
No comments:
Post a Comment