Login Redirect Issue - asp.net

I want to re-direct people logging in based on their role. When I use the code below, the roles are coming up empty when debugging - I suspect because they haven't been completely logged in yet? I may be tapping into the the wrong event, can someone point me in the right direction?
<asp:Login ID="LoginUser" OnLoggedIn="Login1_LoggedIn" runat="server"
DestinationPageUrl="~/Login.aspx" EnableViewState="false"
RenderOuterTable="false">
<p>
<asp:Button ID="LoginButton" CssClass="submitButton" runat="server" Width="70"
CommandName="Login" Text="Log In"
ValidationGroup="LoginUserValidationGroup" />
</p>
</asp:login>
protected void Login1_LoggedIn(object sender, System.EventArgs e)
{
// Overrides ReturnUrl page parameter
//Response.Redirect(LoginUser.DestinationPageUrl);
if (User.IsInRole("Member"))
Response.Redirect("~/AskExpert/AskQuestion.aspx");
else if (User.IsInRole("Expert"))
Response.Redirect("~/Admin/Experts/ViewQuestions.aspx");
else if (User.IsInRole("Admin"))
Response.Redirect("~/Admin/AdminHome.aspx");
}

You could use Roles.IsUserInRole() instead. User.IsInRole reads the authentication data from the auth cookie and it seems that this data is not yet set when that event is fired.
if (Roles.IsUserInRole("Member"))
Response.Redirect("~/AskExpert/AskQuestion.aspx");
else if (Roles.IsUserInRole("Expert"))
Response.Redirect("~/Admin/Experts/ViewQuestions.aspx");
else if (Roles.IsUserInRole("Admin"))
Response.Redirect("~/Admin/AdminHome.aspx");
The downside to Roles.IsUserInRole is that if you're using a database provider, it results in a roundtrip.

I usually avoid the go and back turn of redirection, transferring the control with Server.Transfer.

Related

Change the buttons if user is logged

I have this navbar which shows some links on the left side and Sign in/sign up links on the right one. I want to check if the user is logged and if it is, instead of the sign in/up links, to show his name. I know how to check if there is something in the session in the code behind, but I have a hard time changing the view. Thanks in advance.
You can do this. It uses the build in Request.IsAuthenticated to show/hide controls on the page. And you can use the LoginStatus Control for generating a login/logout link. See Microsoft site for more info.
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="Login.aspx">Login</asp:HyperLink>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
HyperLink1.Visible = false;
Label1.Text = User.Identity.Name;
}
}
You can use inline code,
<% if (Session["User"] != null) { %>
//button goes here
<% } %>

Duplicate PK Check on saving - Alert not firing

I'm trying to check for duplicate pks when trying to insert a new record. I want to show an error if it does, but i'm not sure where i am going wrong/if this is the right way to go.
Please see below. I put a breakpoint at the function AgentSave_Click and saw its its not going into the IF statement
<asp:Button ID="AgentSave" runat="server" CausesValidation="true" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
protected void AgentSave_Click(object sender, EventArgs e)
{
try
{
if (AccountNumber.Text.Trim().Equals("select PRIMARYKEYNAME from TABLEXYZ"))
{
Response.Write("<script type=\"text/javascript\">" + "window.alert('ERROR: The Account Number entered is already assigned to an Agent.');" + "</script>");
AccountNumber.Focus();
}
else
{.....
OnClientClick property is meant to execute some javascript code on client before data is send back to server.
According your answer you are trying to execute server code. So you should replace onclientclick with onclick="duplicate_PK" which gets executed on server.
Regards,
Uros
<asp:Button ID="AgentSave" runat="server" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
remove CausesValidation="true" or chANGE TO CausesValidation="false"

How do I hide the "Register" link after user successfully logs in?

A user opens our web app and is automatically taken to the default page.
While on default page, if the user has not logged in or created an account, the Register or Login link is displayed at the top of the page.
<table bgcolor="#003366" width="100%">
<tr><td align="right"><span style=" color:darkOrange;font-weight:bold">Login or Register</span></td></tr></table>
This is fine.
However, after user successfully logged in, s/he is redirected to his/her page.
The problem is that the user clicks the default page for whatever reason, the Register or Log in link appears again.
Is there a way to hide this link as long as the user is logged in and only show it after the user logs off?
Thanks in advance for your help.
This is the change I made so far, added label control:
<table bgcolor="#003366" width="100%">
<tr><td align="right"><span style=" color:darkOrange;font-weight:bold"><label id="loginId" runat="server" Text="Login / Register"></label></span></td></tr></table>
Based on the fact that your link is pointing to a login.aspx page, I can see that you are probably using the Web Forms section of asp.net
Usually when working with Authentication and showing/hiding elements on a page within Web Forms, you can make use of some asp.net controls.
If you are using the build in .net Membership provider, then there is a control called the Login View. This is a simple control that allows you to show different content when a user is Logged in/out.
You can do something as simple as this;
<asp:loginview ID="Loginview1" runat="server">
<AnonymousTemplate>
Login / Register
</AnonymousTemplate>
<LoggedInTemplate>
Logout
</LoggedInTemplate>
</asp:loginview>
This will automatically show/hide the correct content.
You can also make use of any server side control and using the Visible property of this. So in your code you can set controls to be visible or not depending on the logged in status.
Also you could wrap your code within a <asp:Panel> then just show hide depending;
<asp:Panel id="pnlLoggedOut" runat="server" Visible="True">
<span style=" color:darkOrange;font-weight:bold">Login or Register</span>
</asp:Panel>
<asp:Panel id="pnlLoggedIn" runat="server" Visible="False">
<span style=" color:darkOrange;font-weight:bold">Logout</span>
</asp:Panel>
In your code behind you can show either or.
Another way is to just have your <a> tag as a server control. You can then update the text and hyper link depending on the logged in status.
<asp:HyperLink ID="hlLoginStatus" runat="server" NavigateUrl="Login.aspx" Text="Login / Register" />
In your code behind if the user is logged in, then you can change the NavigateUrl and the Text property.
If you want to maintain your code, as much as possible, then I recommend wrapping your markup with a control that can be accessed server-side, like this:
<asp:Panel id="PanelLogin" runat="server" Visible="True">
<table bgcolor="#003366" width="100%">
<tr>
<td align="right">
<span style=" color:darkOrange;font-weight:bold">Login or Register</span>
</td>
</tr>
</table>
</asp:Panel>
Now in your code-behind Page_Load event, you can check to see if the user has logged in or not. I suggest you store whether or not they are logged in cache (i.e. Session value IsLoggedOn). You will toggle the visibility of the ASP.NET Panel, based upon the value of IsLoggedOn, like this:
protected void Page_Load(object sender, EventArgs e)
{
bool isUserLoggedOn = (bool)Session["IsLoggedOn"];
if(isUserLoggedOn)
{
PanelLogin.Visible = false;
}
else
{
PanelLogin.Visible = true;
}
}
when the user logins upon successful login. you should keep his username in Session as
Session["user"] = username;
Now on page Load() check if Session["user"] is null then label.text = "register"
else = label.text = "";
hope it will help.

ASP.Net: Ajax check for registration as a user?

I have an user registration on my site.
I want to look it cool, so my plan is, that after a textbox is left, a green or red sign right behind the textbox tell the user if e.g. the username is unused, the email-adress is unused, the password is correct entered twice and so on.
Yes, I know the validation controls, but there are only a bunch of functions, isn't it? E.g. for checking if the email-adress is unused I must check by database and so on...
Any Ideas?
I would wrap the whole thing in an update panel, this is something I do quite often...
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional">
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
and in the code behind
protected void tbUsername_TextChanged(object sender, EventArgs e)
{
//call DB etc and mark validator as needed
cusValEmail.IsValid = false;
}
The key is setting the textbox autopostback to true and utilising the ontextchanged event.
A simple way of doing this would be to create a controller action (if you are using MVC) or a page (if you are using regular asp/asp.net) that you post the username, e-mail address, etc to that returns a simple plain-text colour value - red or green, depending on whether all the parameters have been posted are ok. You could then apply that to the colour-style of the box. If you don't have/want that to be an https call then I probably wouldn't include the passwords in that, you ajax return code could maybe say
if (<password are equal>)
{
set style-colour to the return value
}
else
{
set to red
}
or probably, even better, something like
if (<passwords are equal>)
{
run ajax call
}
else
{
set style-colour to red
}
and the the ajax return sets the colour to the return value, that way you also save a round trip to the server if the passwords aren't equal
Any reason you want/need to do this via ajax rather than a regular postback (you could use an update panel to do a partial postback)?

Need help in login validation using javascript

Please could somebody point me out what is the error here? Using javascript i am validating the user input. When i click the login button without checking the javascript function, it goes to the welcome page. Here is my code:
<script type="text/javascript">
function validLogin()
{
if(document.getElementById("txtUserName").value == "")
{
alert("Please enter your UserName");
return false;
}
if(document.getElementById("txtPassword").value == "")
{
alert("Please enter your Password");
return false;
}
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
BtnLogin.Attributes.Add("onClick","return ValidLogin();");
}
I see that you're using ASP .NET (the Page_Load event on your posted code).
I think that will be easier to handle validation through ASP .NET Validation Controls, i.e. RequiredFieldValidator.
Check your case on return ValidLogin(); it doesn't match.
P.S.: I hope you aren't performing all user validation client-side.
It would probably be easier to user ASP .NET validation controls, here's a sample:
User Name:
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator
ID="UserNameValidator"
ControlToValidate="UserName"
ErrorMessage="User Name Required"
runat="server" />
Password:
<asp:TextBox ID="Password" runat="server" />
<asp:RequiredFieldValidator
ID="PasswordValidator"
ControlToValidate="Password"
ErrorMessage="Password Required"
runat="server" />
first make sure it's not a difference in case... your javascript function is validLogin and in Page_Load you have ValidLogin

Resources