Link to home
Start Free TrialLog in
Avatar of mathieu_cupryk
mathieu_cuprykFlag for Canada

asked on

need to add an administrator page or site.

I need to add an administrator site for login

I can create an admin directory
and have a default page,
how can I modify the web.config to do this
if I have this
  <authentication mode="Forms">
       <forms  loginUrl="Login.aspx" defaultUrl="UserProfile.aspx" slidingExpiration="false"/>
    </authentication>
    <authorization>
      <allow users="*" />
      <deny users="?" />
    </authorization>

How can I point my admin to another page.
ASKER CERTIFIED SOLUTION
Avatar of Espavo
Espavo
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's an example of the Login Control...
    <asp:LoginView ID="LoginView1" runat="server">
        <LoggedInTemplate>
            <p class="bodytext">Please select an item from the menu</p>
        </LoggedInTemplate>
        <AnonymousTemplate>
            <asp:Login ID="Login1" runat="server" UserNameLabelText="User Name / Email:" 
                TitleTextStyle-Height="40px" TitleTextStyle-VerticalAlign="Top" 
                TitleTextStyle-CssClass="header" TitleTextStyle-HorizontalAlign="left" 
                BorderPadding="4" DestinationPageUrl="~/admin/Default.aspx" >
                <TextBoxStyle />
                <LoginButtonStyle cssclass="Button" />
                <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
                <TitleTextStyle CssClass="header" Font-Bold="True" 
                    HorizontalAlign="Left" 
                    VerticalAlign="Top" />
            </asp:Login><p>Click <a href="forgotPassword.aspx">here</a> if you've forgotten your password<br/>Click <a href="register.aspx">here</a> to register</p>
        </AnonymousTemplate>
    </asp:LoginView>

Open in new window

Avatar of mathieu_cupryk

ASKER

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
   <system.web>
          <authorization>
              <allow roles="Admin" />
              <deny users="*" />
          </authorization>
   </system.web>

   <location path="Default.aspx">
      <system.web>
         <authorization>
            <allow roles="Administrators,Editors,Contributors,Moderators,StoreKeepers" />
            <deny users="*" />
         </authorization>
      </system.web>
   </location>

</configuration>

this is my webconfig in the admin folder needs fixing.
I am not sure right now the site goes to default.aspx page
and in the behind code I do a redirect response to login.aspx page
in my case if the user's credit. are ok then goto userprofile.aspx
this implies we must put this in admin folder?
this is what i have in my page
<div id="loginbox">
             <asp:LoginView ID="LoginView1" runat="server">
             <AnonymousTemplate>
               <asp:Login ID="LoginStatus" runat="server" Height="31px" width="100%" FailureAction="RedirectToLoginPage"
                    onloggedin="LoginStatus_LoggedIn" onloggingin="LoginStatus_LoggingIn">
                  <LayoutTemplate>
                   <table border="0" cellpadding="0" cellspacing="0" width="100%">
                        <tr>
                           <td nowrap="nowrap" width="25%">
                           <asp:Label runat="server" ID="lblUserName" AssociatedControlID="UserName" Text="Username:"  />
                           <asp:TextBox id="UserName" runat="server" BorderColor="DarkGray"  
                                   BorderStyle="Inset" BorderWidth="2px" Width="125px" />
                           </td>
                           
                           <td width="8px" style="text-align: left;" valign="middle">
                           <asp:RequiredFieldValidator ID="valRequireUserName" runat="server" SetFocusOnError="True"
                                 ControlToValidate="UserName" Text="*" ValidationGroup="Login"  
                                   Font-Bold="True"  />                    
                           </td>
                         
                          <td nowrap="nowrap" width="25%">
                          <asp:Label ID="lblPassword" runat="server" AssociatedControlID="Password" Text="Password:" />
                          <asp:TextBox ID="Password" runat="server" TextMode="Password"
                                   BorderColor="DarkGray" BorderStyle="Inset" BorderWidth="2px"
                                  Width="125px" />
                          </td>
                         
                          <td width="8px" style="text-align: left;" valign="middle">
                                <asp:RequiredFieldValidator ID="valRequirePassword" runat="server"
                                    ControlToValidate="Password" SetFocusOnError="True" Text="*"
                                    ValidationGroup="Login" Font-Bold="True" />
                          </td>
                         
                          <td width="25%">
                               <asp:Button CssClass="button-login" validationgroup="Login"
                                   CommandName="Login" ID="btnLogin"
                                   runat="server" Text="Login" Font-Bold="True" />
                                   
                          </td>
                             
                                       
                        </tr>
                       
                        <tr>
                            <td width="100%" colspan="5" style="text-align: right;">
                                <asp:CheckBox ID="RememberMe" runat="server" ForeColor="DarkSlateGray"
                                    Text="Remember me" />
                                | <asp:HyperLink ID="lnkRegister" runat="server" NavigateUrl="~/Register.aspx">Create New Account
                                </asp:HyperLink>
                                | <asp:HyperLink ID="lnkPasswordRecovery" runat="server"
                                    NavigateUrl="~/PasswordRecovery.aspx">Forgot
                                password?</asp:HyperLink>
                            </td>
                        </tr>

                        <tr>
                            <td width="100%" colspan="5" style="text-align: right;">
                               <br />
                               <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
                               <input type="text" class="value" name="theTime" size="25" readonly="readonly" style="border: 0px;">
                            </td>
                        </tr>

                     </table>
                    </LayoutTemplate>
               </asp:Login>
              </AnonymousTemplate>
               
            <LoggedInTemplate>
               <div id="welcomebox">
                  <asp:LoginName ID="LoginName1" runat="server" FormatString="Welcome {0}" />
                  <asp:Button CssClass="button-login" ID="btnLogout" runat="server" Text="Logout" Font-Bold="True"
                   OnClick="btnLogout_Click" /><br />
                   <input type="text" class="value" name="theTime" size="25" readonly="readonly" style="border: 0px;">
              </div>
            </LoggedInTemplate>
         </asp:LoginView>
                         
               
        </div>
this is the behind
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using System.Collections.Generic;


public partial class Controls_Login : System.Web.UI.UserControl
{
    protected MembershipUser loginUser;
 
   
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!this.IsPostBack)
        {
           

            // Search recursively for a Login control, called LoginStatus
            // starting from within the Page object.
            System.Web.UI.WebControls.Login curLogin = FindControl<System.Web.UI.WebControls.Login>(this, "LoginStatus");

            // You still should check whether you got something back!
            if (curLogin != null)
                this.Page.SetFocus(curLogin.FindControl("UserName"));            

           
        }
    }

   
    // Search recursively a control sub-tree for a specific control.
    // It searches every control in the sub-tree, so it potentially
    // could be optimized to search only, say, INamingContainers.
    public T FindControl<T>(string id) where T : Control
    {
        return FindControl<T>(Page, id);
    }

    public static T FindControl<T>(Control startingControl, string id) where T : Control
    {
        T found = null;
        foreach (Control activeControl in startingControl.Controls)
        {
            found = activeControl as T;
            if (found == null)
            {
                found = FindControl<T>(activeControl, id);
            }
            else if (string.Compare(id, found.ID, true) != 0)
            {
                found = null;
            }
            if (found != null)
            {
                break;
            }
        }
        return found;
    }



    protected void btnLogout_Click(object sender, System.EventArgs e)
    {
        MembershipUser mu = Membership.GetUser();
        mu.Comment = String.Empty;
        Membership.UpdateUser(mu);
        FormsAuthentication.SignOut();
        FormsAuthentication.RedirectToLoginPage();
       
    }


    protected void LoginStatus_LoggedIn(object sender, EventArgs e)
    {
        if (loginUser == null)
        {
            Login lgnMain = ((Login)LoginView1.FindControl("LoginStatus"));
            string username = lgnMain.UserName;

            loginUser = Membership.GetUser(username);
        }

        //represents the active login session
        Guid g = System.Guid.NewGuid();
        HttpCookie c = Response.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket ft = FormsAuthentication.Decrypt(c.Value);

        //Generate a new ticket that includes the login session ID
        FormsAuthenticationTicket ftNew = new FormsAuthenticationTicket(
                                            ft.Version,
                                            ft.Name,
                                            ft.IssueDate,
                                            ft.Expiration,
                                            ft.IsPersistent,
                                            g.ToString(),
                                            ft.CookiePath);

        //Store the expiration date and login session ID in Membership
        loginUser.Comment = "LoginExpiration;" + ft.Expiration.ToString() + "|LoginSessionID;" + g.ToString();
        Membership.UpdateUser(loginUser);

        //Re-issue the updated forms authentication ticket
        Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

        //Basically clone the original cookie except for the payload
        HttpCookie newAuthCookie = new HttpCookie(
                                        FormsAuthentication.FormsCookieName,
                                        FormsAuthentication.Encrypt(ftNew));

        //Re-use the cookie settings from forms authentication
        newAuthCookie.HttpOnly = c.HttpOnly;
        newAuthCookie.Path = c.Path;
        newAuthCookie.Secure = c.Secure;
        newAuthCookie.Domain = c.Domain;
        newAuthCookie.Expires = c.Expires;

        //And set it back in the response
        Response.Cookies.Add(newAuthCookie);
     

    }
    protected void LoginStatus_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        if (loginUser == null)
        {
            Login lgnMain = ((Login)LoginView1.FindControl("LoginStatus"));
            string username = lgnMain.UserName;

            loginUser = Membership.GetUser(username);
        }


        //Only need to check if the user instance already has login information
        //stored in the Comment field.
        if ((!MembershipUser.Equals(loginUser, null)) &&
                (!String.IsNullOrEmpty(loginUser.Comment)) &&
                loginUser.Comment.Contains("LoginExpiration"))
         {

           

             string currentExpirationString = loginUser.Comment.Split("|".ToCharArray())[0];
             DateTime currentExpiration = DateTime.Parse((currentExpirationString.Split(";".ToCharArray()))[1]);
           
           
            //The user was logged in at some point previously and the login is still
            //valid
            if (DateTime.Now <= currentExpiration)
            {
                e.Cancel = true;
                Literal tx = (Literal)LoginView1.FindControl("FailureText");
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "message", "alert('You are already logged in.');", true);

            }
        }
    }


}
Why are you using such a complicated method in the background code?
My total login CodeBehind looks like this...

Partial Class Login
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim MetaTitle As Object = Master.FindControl("metaTitle")
        MetaTitle.Text = ConfigurationManager.AppSettings("MetaTitle") & "Login" & ConfigurationManager.AppSettings("MetaTitleDmn")
 
        If Request.QueryString("email") <> "" Then
            CType(LoginView1.FindControl("Login1").FindControl("UserName"), TextBox).Text = Server.UrlDecode(Request.QueryString("email"))
        End If
    End Sub
End Class

Open in new window

maybe u can help me the reason is that I don't want multiple users logged in under one account.

Is there another approach.
Oh, that's an interesting point and idea...
Well surley it's only the
 "protected void LoginStatus_LoggingIn(object sender, LoginCancelEventArgs e)" sub that you need then...
   
u confused me
Sorry,
What I was saying / suggesting was that if you need to check to see if that user is logged-in before logging them in again, then I don't think you need to do ALL of the login processes manually, you could let the wizard to the bulk of it (it does it really well), and just use your piece of script to check at the actual time of the login, to see if they should be logged-in or not.
Gayo
do u have an example of this?
Not off-hand... will be quite quick and easy to do... (I think)
I've gone back and had a "quick" look... it "seems" as though you are writing a comment when the user log's in, and then checking for an expiry time on the next login... (Is that correct?)
How do you update the expiry date/time while the 1st person is logged-on? (As long as they are active on the site that date/time should be increasing?)
I haven't had a look anywhere, but doesn't .Net possibly monitor this all automagically?
Gayo
I did a quick look on Google and found this article:

http://forums.asp.net/p/1119826/1745387.aspx
Looks like it can be quite tricky... (the joys of working with Asynchronous connections...)
Hmmm, interesting solution he has but we need more explanation.
Hi,
I just saw this is another thread... that may work for you...
Dim thisUser As MembershipUser = Membership.GetUser("Guest")
            If thisUser.IsOnline Then
                ' Show Error Message to user attempting to login
            end if

 
i need to see the whole thing to understand this.
That's basically all there was...
It just looked as though as he logged the user in that he checks to see if that user is already online...
  If thisUser.IsOnline Then
If the user is, then he "does something"... else he logs the user on...