How to handle password Expired pop up in asp.net - asp.net

I am working in asp.net using SQL server 2005.
In my web application user name, password, Validity date like that i have three fields
for example:
User name: reka
password : reka123
Validity date : 24-01-2013
It is working fine, but
suppose when you are logging into that form at this date 25-01-2013 , I want to show the pop up message Your Password Expired. How do I tackle this?

If you are only asking about determining if the current date is greater than the validation period date. then you can do :
if(DateTime.Today > validationPeriodDate)
{
//Password expired
//Redirect to change password screen
}
else
{
//password is valid with valid validation period
}

First : you need to design your database table as following ,
ID as int
userName as varchar
password as varchar
ValidityDate as Date
then use any ORM to create class of this table in your asp.net application , ORM like linq-to-sql , entity framework or you can just execute your sql query using SqlConnection , SqlCommand objects , check example here : Example of using SqlCommand
, every time login select his ValidityDate from the database .
if (DateTime.Today > ValidityDate)
{
// password expired , there are many ways to show a popup
// simple way a javascript alert
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "
<script>alert('password expired!');</script>");
// check here for many jquery elegant popups
/* http://collegegfx.com/10-best-jquery-popup-plugins/ */
}
else
{
//password not expired ,login
}

Related

Login authentication to asp.net and postgresql

I have tried to implement login page in ASP.NET Core MVC and using postgresql as database.
It should check whether user exits in the database table of postgresql and verify, so what is the query to search for user in database and made them sign in?
I have written my code like this:
public IActionResult Login(string seller_email, string seller_password)
{
using var connection = new NpgsqlConnection(connString);
connection.Open();
string main_query = String.Format(#"select exists(select 1 from public.""sellers"" where ""seller_email""='{0}')", seller_email);
using var command_main = new NpgsqlCommand(main_query, connection);
int result_main = command_main.ExecuteNonQuery();
if (result_main < 0)
{
return View(nameof(Create));
}
else
{
return View(nameof(Sign));
}
}
There is a seller table in the database, so just have to check seller exists or not - if exists the have to create a view for it
You are doing a select query, so you must use a command.ExecuteReader.
The ExecuteNonQuery is to be used with statements that update/insert/delete records.
BUT, most importantly, don't concatenate user submitted values into the query string, as it opens the door to SQL injections. Instead, used a parameter.
See the getting started doc for a simple example.

ASP.Net Registration Page - how to get foreign key from another table

I am creating an ASP.net website using Visual Studio 2013. Specifically, I am trying to register a customer and insert the data in the customer table at the same time. When I register a customer, I also want to get the user id for that customer (which is inserted into my user accounts table in the database). So essentially I need to get the user id but also need to make sure that is the user id of the current user.
Here's what I tried to do:
String userQueryStr = "SELECT UserAccountID FROM UserAccounts WHERE Username = " + Email.Text;
System.Data.SqlClient.SqlCommand selectCommand = new System.Data.SqlClient.SqlCommand(userQueryStr, conn);
int userID = Convert.ToInt32(selectCommand.ExecuteScalar());
Email is the username btw. Essentially I am trying to make sure the Username field in the UserAccounts matches what is typed in the textbox on the registration page.
Then I tried to store an insert statement and also pass the userID int variable which is storing the Current user id from the User Account Table.
My problem is, after I run the application when I click the Registration button I get this error when I type the username test#testers.com:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The multi-part identifier "test#testers.com" could not be bound. The exception is thrown at this line:
int userID = Convert.ToInt32(selectCommand.ExecuteScalar());
Sql thinks your email is a field, because you don't have quotes before and after
String userQueryStr = "SELECT UserAccountID FROM UserAccounts WHERE Username = '" + Email.Text+"'";

ASP Membership / Role Provider -> how to report the number of users currently logged in?

I'm using the ASP.NET Membership and Role provider. My question is about if there is a built in way to report the number of users who are currently logged in. The question is not get the information about the user who is logged in but from a high level view of everyone who is logged in.
I would like to create a user management dashboard and this metric would be great. also showing the usernames of users who are currently logged in would be useful.
thank you for any help you can provide.
Yes there's a built-in way, see Membership.GetNumberOfUsersOnline(). You can change the "window" for what's considered online, see Membership.UserIsOnlineTimeWindow. (you set the threshold in web.config)
UPDATE:
In response to your comment about getting a list of online usernames...
The Membership API is lacking what you want, so you have to roll your own. You can use the following as starter code, it's similar to what I've done in the past:
public static List<string> GetUsersOnline() {
List<string> l = new List<string>();
string CS = WebConfigurationManager
.ConnectionStrings[YOUR_WEB_CONFIG_KEY]
.ConnectionString
;
string sql = #"
SELECT UserName,LastActivityDate
FROM aspnet_Users
WHERE LastActivityDate > #window
ORDER BY LastActivityDate DESC"
;
using (SqlConnection c = new SqlConnection(CS) ) {
using (SqlCommand cmd = new SqlCommand(sql, c) ) {
DateTime window = DateTime.UtcNow.AddMinutes(
-Membership.UserIsOnlineTimeWindow
);
cmd.Parameters.AddWithValue("#window", window);
c.Open();
using (SqlDataReader r = cmd.ExecuteReader() ) {
while ( r.Read() ) {
l.Add(r.GetString(0));
}
}
}
}
return l;
}
A couple of notes:
Replace YOUR_WEB_CONFIG_KEY above with the key in your web.config <connectionStrings> section.
The LastActivityDate field in the aspnet_Users table (aspnetdb database) is stored as a GMT/UTC Datetime value, so that's why DateTime.UtcNow is used to calculate the window.
Not sure how your Membership database permissions are setup, but you may need to make permission changes, since above code is directly querying the database.

Do action if button clicked for 3 times

I want to do some action if button clicked for 3 times. Just like if users enters a wrong password for 3 times the page the page must be redirected to another page or something.
How to do action in ASP.NET C# if button clicked for 3rd time?
To check if a user has taken an action fox "x" times you need to store it somehwere. If you're using a relation database you could for example call a table LoginAttempts and there you store all unsuccesfull logins. When you have that table you can build your logic against it.
I'd use a session variable.
Another solution could be having a column in the users table named LoginAttempt(int)(default 0), how I would use that column is
Let's say you have a table in your databese called TblUsers with these columns
Id,
UserName,
Password,
LoginAttempt.
And let's say you have two TextBoxes on your Login.aspx page
TextBoxUserName,
TextBoxPassword.
Let's say you have one record in your TblUsers like this
Id : 1
UserName : rammstein
Password : ohnedich
LoginAttempt : 0
Now, you are in your Login.aspx.cs code
you have a method and in it you have
TblUsers user = new TblUsers();
And you have a bool login = false;.
You've got the username from TextBoxUserName.Text, you check if a user with this username exists then if it exist you do the below code.
Let's follow this scenerio
The given user tried to login with
UserName:rammstein
Password:duhast
Checked your database with username rammstein and found it, and took that record in your TblpUsers user then you checked whether user.Password and TextBoxPassword.Text matches.Well it won't match for the above example because
user.Password is ohnedich however TextBox.Password is duhast.This means the login is not successfull so you set false to your bool login.
Everything else belongs to the below code with if-else condition
if(user.LoginAttempt < 3){
if(!login)
{
user.LoginAttempt = user.LoginAttempt + 1;
}
else
{
user.LoginAttempt = 0;
}
}
else
{
//do something
}
Multiple solutions:
1) Session variable (Okay solution)
2) Static class variable (Not a good solution)
3) DB record field (Best solution)
4) Pass flag variable back and forth between view and controller (not a very good idea).
5) Browser cookie (can be cleared)

ASP.NET username change

I have an asp.net site which uses the ASP.net Membership provider. Each comment, entry etc in the DB is tracked by the userID.
Since MS doesn't provide a way to change the username, I've found the userNAME in the "users" table in the DB and there is only 1 place where the username appears.
My question is,
Is it safe to provide an "edit profile" page where the user is allowed to edit their own username. Of course i would handle this change in the background by directly changing the "username" value in the DB.
Are there any downsides to this ? I've created and modified some test accounts and it seems to be fine, i am just wondering if there is any known negatives to this before putting it into production.
cptScarlet's link was good, however I despise using stored procedures if I don't have to and I favor Entity Framework whenever possible. Here's what I did to change the user name, using EF 4.0 and .NET 4.0:
Right click project -> Add New Item -> ADO.NET Entity Data Model
Give it a proper name, I chose "MembershipModel.edmx" and click Add
Select Generate from database and click Next
Add the connection to your 'aspnetdb' database (the ASP.NET membership database)
Give it a proper name, I chose "MembershipEntities"
Click Next
Drill into Tables and select aspnet_Users
Change the Model Namespace to MembershipModel
Click Finish
Now you can add code to create the EF object context and modify the database:
public void ChangeUserName(string currentUserName, string newUserName)
{
using (var context = new MembershipEntities())
{
// Get the membership record from the database
var currentUserNameLowered = currentUserName.ToLower();
var membershipUser = context.aspnet_Users
.Where(u => u.LoweredUserName == currentUserNameLowered)
.FirstOrDefault();
if (membershipUser != null)
{
// Ensure that the new user name is not already being used
string newUserNameLowered = newUserName.ToLower();
if (!context.aspnet_Users.Any(u => u.LoweredUserName == newUserNameLowered))
{
membershipUser.UserName = newUserName;
membershipUser.LoweredUserName = newUserNameLowered;
context.SaveChanges();
}
}
}
}
Note: I did not account for application ID's in my code. I typically only ever have one application using the ASP.NET membership database, so if you have multiple apps, you'll need to account for that.

Resources