Logout user after three unsuccesfull attempts - ASP.NET - c#

I am new to programming. In my web application, user will receive a popup alert when he attempts to access restricted page. After three unsuccessful attempts i want him to be logged-out(i.e redirect to logout page). My question is, how to capture each failed attempts.
My existing code for giving alerts,
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
}
}

You can capture each failed attemped by using another session . Please check below code. I am test this in ASP.NET MVC. Session["StaffID"] is your condition check or any condition so use another session to count attempt. Hope it will help you.
public ActionResult OnInit()
{
base.OnInit(e);
var accessCount = Convert.ToInt16(Session["AccessCount"]);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
//Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
accessCount++;
if (accessCount <= 3)
{
Session["AccessCount"] = accessCount;
return Content("<script>alert('You are not allowed to view this page')</script>");
}
else
{
Session["AccessCount"] = 0;
return RedirectToAction("logout");
}
}
}

Related

Value from Session is lost in IE

All!
I've website with multiples idioms. I can select/change idiom in any page. The idiom is saved in Session, if I change idiom, I changed session value.
The problem is:
If I change my default idiom in Homepage and go to other page, this session value is lost, consequently, this page not translated.
But if I reload this page one or more times, translates current page.
This occur just in Webserver (Pheonix - US). In localhost, session not lost value.
This issue occur to any page, but just in IE. To Chrome works correctly.
Below, my source code to Homepage. To all pages is basically this code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//to set default session value. (first time).
if (Session["idioma"] == null)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
Idioma.MudaCultura(idioma);
Session["idioma"] = idioma;
}
//if I've other session value (Change Idiom).
else if (Session["idioma"] != null)
{
string idioma = Session["idioma"].ToString();
Idioma.MudaCultura(idioma);
}
lblWelcome.Text = Idioma.RetornaMensagem("welcome");
btnRequestAccess.Text = Idioma.RetornaMensagem("btnRequestAccess");
btnTickets.Text = Idioma.RetornaMensagem("btnTickets");
btnManager.Text = Idioma.RetornaMensagem("btnManager");
btnManageFolders.Text = Idioma.RetornaMensagem("btnManageFolders");
IdiomaList.Items.Add("PORTUGUÊS");
IdiomaList.Items.Add("ENGLISH");
IdiomaList.Items.Add("ESPAÑOL");
//Set value that show in DropDown list according to Session value.
if (Session["idioma"].ToString() == "pt")
{
IdiomaList.SelectedValue = "PORTUGUÊS";
}
else if (Session["idioma"].ToString() == "en")
{
IdiomaList.SelectedValue = "ENGLISH";
}
else if (Session["idioma"].ToString() == "es")
{
IdiomaList.SelectedValue = "ESPAÑOL";
}
}
}
protected void Idioma_OnChange(object sender, EventArgs e)
{
if (IdiomaList.SelectedValue == "PORTUGUÊS")
{
Idioma.MudaCultura("pt");
Session["idioma"] = "pt";
}
else if (IdiomaList.SelectedValue == "ENGLISH")
{
Idioma.MudaCultura("en");
Session["idioma"] = "en";
}
else if (IdiomaList.SelectedValue == "ESPAÑOL")
{
Idioma.MudaCultura("es");
Session["idioma"] = "es";
}
lblWelcome.Text = Idioma.RetornaMensagem("welcome");
btnRequestAccess.Text = Idioma.RetornaMensagem("btnRequestAccess");
btnTickets.Text = Idioma.RetornaMensagem("btnTickets");
btnManager.Text = Idioma.RetornaMensagem("btnManager");
btnManageFolders.Text = Idioma.RetornaMensagem("btnManageFolders");
}
I have experienced the same problem with IE losing the session each time the page reloads. In my case it was caused by the server having an out of sync timezone which caused the cookies to already be expired when it reached the client. It seems most browsers still work, whereas IE will destroy the cookies when navigating to the next page.
This can be a browser setting problem.
to solve this problem you can view as below link.
Cookie blocked/not saved in IFRAME in Internet Explorer
I hope it will helpful to you.

Permission Check Code Snippet for an ASPX Page

I have a permission check code snippet in each page in my application like below,
<%
int permission = Int32.Parse(Session["userpermission"].ToString());
if (permission != 1) {
Response.Redirect("Login.aspx");
}
%>
So if it is not equals 1, then it will redirect to Login Page, but now i need to add permission = 2 also into this condition in a specific page, where both permission levels 1 & 2 can enter, but I tried using OR operator "|" inside if condition like (permission != 1 | permission != 2), but then neither both permission levels can enter the page, Please suggest a solution.
It is not a good design practice to authorize a user. The future maintenance will be nightmare.
Ideally, you want to use Role based authorization.
If you cannot implement Role base authorization, you can at least use a BasePage, and inherit all xxx.aspx.cs from the BasePage.
public partial class Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
public class BasePage : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
int permission = Convert.ToInt32(Session["userpermission"] ?? "0");
if (permission == 1 || permission == 2)
{
// User is authorized, so allow access.
}
else
{
Response.Redirect("Login.aspx");
}
}
}
You can also use the logic like this. I personally do not like it because it is hard to read.
if (permission != 1 && permission != 2)
{
Response.Redirect("Login.aspx");
}
Checking whether the permission doesn't equal 1 or doesn't equal 2 will always be true.
After all, no possible number can equal both 1 and 2, so it will always be equal to one of them.
You want to check whether it is unequal to 1 and also unequal to 2.

C# - WP8: error during validating if it is null?

If the Password boxes are empty. It shows Passwords created Successfully. I dunno whats wrong I did here. But, if entered passwords are not matched, if condition works as per code. Error for validating null.
Code;
void savePassword(object sender, RoutedEventArgs e)
{
string password1 = createPassword.Password;
string password2 = repeatPassword.Password;
if (password1 != null || password2 != null)
{
if (password1 == password2)
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}
}
else
{
MessageBox.Show("Both fields are required");
}
}
You can check if the PasswordBox is filled properly with the string.IsNullOrWhiteSpace or string.IsNullOrEmpty methods. Also, you might want to remove the != because your logic validates as soon as one of the PasswordBoxes has content.
Here's a sample:
//Is true only if both passwords have content
if(!string.IsNullOrWhiteSpace(password1) && !string.IsNullOrWhiteSpace(password2))
Try this
if (password1.Length == 0 || password2.Length == 0)
You have to check that password is empty or null
try this
if (!string.IsNullOrEmpty(password1) &&!string.IsNullOrEmpty(password2))
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}

Resting a private variable that should not happen

I have a strange problem I'm checking in my code behind the user if he is active or not with as simple if .. in my Page_Load method as you can see here
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
this.getParameters();
if (!this.IsPostBack)
{
if (paramTR.ZevUser.Active == 0)
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
}
But when I make a go throw to this method I get allays nullreferenceexception why so ever .. but the private ZevUser variable is not null it's full..
I really don't have a clue why is this happing, it would be really cool if someone could explain me this why this is happening
Thanks for help and fast answer
You need to break your code down so you can debug it easier or add logging if you cannot debug this code locally.
Remember that when debugging something, the worse mistake you can make is to make assumptions. Start from the beginning and follow the process through. Don't assume that the problem is something and don't assume that the problem can't be something:
I've included a broken down, more readable version below. You can now add logging around this or easily add breakpoints:
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
this.getParameters();
if (!this.IsPostBack)
{
if ((this.paramTR != null) &&
(this.paramTR.ZevUser != null) &&
(this.paramTR.ZevUser.Active == 0))
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
string sessionId = Session["SessionId"] as string;
if (sessionId != null)
{
int session = int32.Parse(sessionId);
ZevUser user = ZevUser.GetById(session);
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
}
}
Why are you passing the session id to ZevUser.GetById()? I would expect this to take a user id, or for the method to be called something like ZevUser.GetBySessionId(). At the moment it's quite confusing.
This line is causing the issue:
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
This is because Session["SessionId"] can be null, and is null in this case.
If you are looking to get the SessionId that is set by ASP.net, then use this.Session.SessionID (source).
If you are storing a value in Session["SessionId"] that you are trying to retrieve, then do a null-check first:
if (Session["SessionId"] != null) { ...
You should consider testing the SessionId variable before using it by doing something like that :
if (!string.IsNullOrEmpty(Session["SessionId"].ToString()))
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
The best way to debug your exception is to enable debug when the exception is thrown.
For this, go to Debug>>Exceptions
and then enable first four checkboxes (maybe) and then try debugging the project. You will be halted at the position from where the exception will be thrown.

Check if unassigned variable exists in Request.QueryString

Within the context of an ASP.NET page, I can use Request.QueryString to get a collection of the key/value pairs in the query string portion of the URI.
For example, if I load my page using http://local/Default.aspx?test=value, then I can call the following code:
//http://local/Default.aspx?test=value
protected void Page_Load(object sender, EventArgs e)
{
string value = Request.QueryString["test"]; // == "value"
}
Ideally what I want to do is check to see if test exists at all, so I can call the page using http://local/Default.aspx?test and get a boolean telling me whether test exists in the query string. Something like this:
//http://local/Default.aspx?test
protected void Page_Load(object sender, EventArgs e)
{
bool testExists = Request.QueryString.HasKey("test"); // == True
}
So ideally what I want is a boolean value that tell me whether the test variable is present in the string or not.
I suppose I could just use regex to check the string, but I was curious if anybody had a more elegant solution.
I've tried the following:
//http://local/Default.aspx?test
Request.QueryString.AllKeys.Contains("test"); // == False (Should be true)
Request.QueryString.Keys[0]; // == null (Should be "test")
Request.QueryString.GetKey(0); // == null (Should be "test")
This behavior is different than PHP, for example, where I can just use
$testExists = isset($_REQUEST['test']); // == True
Request.QueryString.GetValues(null) will get a list of keys with no values
Request.QueryString.GetValues(null).Contains("test") will return true
I wrote an extension method to solve this task:
public static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.AllKeys.Contains(key))
return true;
// ReSharper disable once AssignNullToNotNullAttribute
var keysWithoutValues = collection.GetValues(null);
return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
Request.QueryString is a NameValueCollection, but items are only added to it if the query string is in the usual [name=value]* format. If not, it is empty.
If your QueryString was of the form ?test=value, then Request.QueryString.AllKeys.Contains("test") would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query.
I use this.
if (Request.Params["test"] != null)
{
//Is Set
}
else if(Request.QueryString.GetValues(null) != null &&
Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
//Not set
}
else
{
//Does not exist
}
TRY this one, it solved my issue!
It will count either the query string has a value or empty and then you can check the required query string value with the Key.
if (!Page.IsPostBack)
{
if (Request.QueryString.Count > 0)
{
if (Request.QueryString["departmentId"] != null)
{
GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
rbListEmpsSurvey.Items[1].Selected = true;
}
else if (Request.QueryString["SurveyStatus"] != null)
{
SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
GetSurveyByDeptAndStatus(status: SatisfactionStatus);
GetDepartments();
}}}
Request.QueryString.ToString().Contains("test")
This works in the special case where you're looking for a single querystring parameter, e.g. MyFile.aspx?test
For more complex, general, cases then other solutions would be better.

Categories