When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML Info
Information:
Advertise
Feedback
Author an Article
Technology Jobs

















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, February 16, 2000

Creating a Database-Driven Login Page
By Corin Martens


  • For more articles on the topic of authentication, be sure to check out: User Authentication!

    - continued -

    This script lets a user login, then it tracks that user and controls the areas they can access. When the user runs across an area they don't have proper permission to access they are forwarded to a page to register. It works well if you want to embed a login into a page and track and identify a specific user throughout the site. This code covers the login and tracking portion for my visitor. You can also read up on how I implemented the registration section.

    There are two parts to the login page, which does a recursive call. The asp code is ignored unless data is entered into the userID and password text boxes and the login button is pushed. This is so you can embed this login within your home page or any other page. Once a user logs in their entry is compared to a database. If there is a match their user level is logged into a session variable and checked on every page. If their isn't a match they are redirected to a page that allows them to register or upgrade their membership.

    The first part sets your database path. You may want to put that is a separate data.asp file and then just include data.asp at the beginning of your code (if you are unfamiliar with using include files, be sure to read: The low-down on Includes). You can also use a System DSN. Which every you choose will work. I like the include file so I can avoid relying on web hosting companies to set-up the DSN and I'm able to refer to the Database Path to save the hassle of changing it on multiple pages when I publish the site to another location.

    Anyway, here's the dataconnection and variable declaration section

    
    <% Response.Buffer = true %>
    <%
      Session("DatabasePath") = "Path to your database"
      If Request.Form("btnLogin") = "Login" AND Request.Form("txtName") <> "" _
           AND Request.Form("txtPassword") <> "" Then
    
        '-- Declare your variables
        Dim DataConnection, cmdDC, RecordSet
        Dim RecordToEdit, Updated, strUserName, strPassword
    
        strUserName = Request.Form("txtName")
        strPassword = Request.Form("txtPassword")
    
        '-- Create object and open database
        Set DataConnection = Server.CreateObject("ADODB.Connection")
        DataConnection.Open "DRIVER={Microsoft Access Driver (*.mdb)};" & _
                            "DBQ=" & Session("DatabasePath") & ";"
    
        Set cmdDC = Server.CreateObject("ADODB.Command")
        cmdDC.ActiveConnection = DataConnection
        ...
    %>
    

    Next, you want to establish a default SQL statement and then modify it when your user has entered their userName. Your trying to find a match in the database with the users entry. A record set is created to store any matching records. If there is a match you want that the data you'll need stored in the recordset. My record in this table has very few columns so I store the entire record.

    
        '-- default SQL
        SQL = "SELECT * FROM tblSecurity"
    
        If Request.Form("txtName") <> "" Then	
    		SQL = "SELECT tblSecurity.* FROM tblSecurity " & _
    		      "WHERE tblSecurity.userID='" & strUserName& _
    		      "' AND tblSecurity.password ='" & strPassword & "'"
        End If
    
        cmdDC.CommandText = SQL
        Set RecordSet = Server.CreateObject("ADODB.Recordset")
    
        '-- Cursor Type, Lock Type
        '-- ForwardOnly 0 - ReadOnly 1
        '-- KeySet 1 - Pessimistic 2
        '-- Dynamic 2 - Optimistic 3
        '-- Static 3 - BatchOptimistic 4
        RecordSet.Open cmdDC, , 0, 2
        ...
    

    Once your recordset is created and the SQL statement executed you test for a match by checking if their are any records in the recordset. If there are you had a match and the Session("userLevel") is set to match the database record field userLevel. If not the user is forwarded to a registration page.

    
        If Not RecordSet.EOF Then
    	  Dim struserLevel
          struserLevel = RecordSet.Fields("userLevel")
          Session("userLevel") = struserLevel
    	Else
          'The user was not validated...
          'Take them to a page which tells them they were not validated...
          Response.Redirect "register.asp"
        End If
      End If
    %>
    

    This next part is your user interface. It checks if they have logged in. If they have it gives their login name and access level. Neat way to let a user know your site cares about them as individuals or as part of a group. It also contains the form for them to enter their userID and password.

    
    <form action="index2.asp" method="post">
      <% If Session("userLevel") > 0 AND Request.Form("btnLogin") = "Login" _
             AND Request.Form("txtName") <> "" AND _
             Request.Form("txtPassword") <> "" Then 
           Response.write("<b>" & Request.Form("txtName"))
           Response.write("</b> is logged on.<BR>")
           Response.write("User Access Level is: ")
           Response.write(RecordSet.Fields("userLevel") & "<BR>")
         End If 
      %>
    
    <table border="1" cellpadding="5" cellspacing="0">
     <tr>
      <td>User Name:</td>
      <td><input type="text" name="txtName" size="40" ></td>
     </tr>
     <tr>
      <td>Password:</td>
      <td><input type="password" name="txtPassword" size="40" value=""></td>
     </tr>
    </table>
    <p>
    <input type="submit" name="btnLogin" value="Login"> 
    </form>
    

    The last part covers the code placed at the beginning of each page that requires an access level. It checks their level from the Session("userLevel"), allows them to access the page unless they lack the proper access level. If not they are forwarded to a registration page then redirected back to the page they came from. If you have several access levels you'll want to pass the level required in the Response.Redirect as well.

    
    <%
    If Session("userLevel") < 'desired access level' Then
       Response.Redirect "upgrade.asp?" & Request.ServerVariables("SCRIPT_NAME")
    End If 
    %> 
    

    The registration section can be read here. Also I'd like to thank other authors of articles on this site as I rely on their direction for some of the coding I do.

    Happy Programming!


    Related Articles

  • Implementing User Registration


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES