Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New to the CF scene
    Join Date
    Jan 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation help with a login program!

    Hi everyone
    i'm new to webdesign and i thought coldfusion is very easy to learn but i did not know that i was just learning the basics. i'm trying to build a login program (page) that will enable users to login with their account information already stored in a database using microsoft access database platform, but i'm stuck and confused, i know that these have to do with session management, cookies and so on. i do not even know how to start, please help.
    thanks in advance

  • #2
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Hey Hollywood. Ok, what you need are a few files. These should get you started. Put them all in the root directory of your website.

    I tried to give explanations for all of them, and you'll have to eventually tailor them to your needs, but try putting them up and see how it goes to start. After putting them all up, trying them out, and looking at the code a little, then the explanations might make more sense. The most complex file is probably Application.cfc, but fear not, even that one is short.

    If you just go straight to copying and pasting, the username / password are both 'test'.


    1) Application.cfc - Has the settings that enable session management, and takes care of redirecting any "non logged-in" users back to the login page. Session management is needed because we need to keep track of the user's visit to the website. In this case, we want to keep track of if the user is logged in or not.
    Code:
    <cfcomponent output="false">
    
        <cfset this.name = "MyApplication">
        <cfset this.applicationTimeout = createTimeSpan( 2, 0, 0, 0 )>    <!--- 2 Days --->
        <cfset this.sessionManagement = true>
        <cfset this.sessionTimeout = createTimeSpan( 0, 0, 20, 0 )>    <!--- 20 min --->
        <cfset this.setClientCookies = true>
    
        
        <cffunction name="onSessionStart">
            <cfset session.loggedIn = false>
        </cffunction>
        
        
        <cffunction name="onRequestStart">
            <cfargument name="targetPage" type="string" required="true">
            
            <!--- If the user is not logged in, and they are not on the login or login processing page, 
                        then redirect them back to login.cfm --->
            <cfif NOT session.loggedIn AND targetPage neq "/login.cfm" AND targetPage neq "/login_process.cfm">
                <cflocation url="/login.cfm">
            </cfif>
        </cffunction>
        
    </cfcomponent>
    This component has two functions: onSessionStart, and onRequestStart. These are two special "event handler" functions that are recognized by ColdFusion, and are run when those events occur.

    onSessionStart runs when a user first visits any page on your website. It won't be run again for that given user until the user's session expires (in 20 minutes), and they re-visit your site. Here, we simply initialize a session variable of loggedIn to false. This will be set to true once the user has entered valid credentials.

    onRequestStart runs right before every request for a web page on your site. This is the best place to put any "security" code. The security code simply checks if the user is logged in or not, and redirects them back to the login page if they are not. (Note that it must also make sure that the user is not already on the login.cfm page. If it doesn't do that, the <cflocation> tag will keep redirecting to login.cfm, and cause a redirect loop.)


    2) login.cfm - Has the form for the user to enter their username and password. If the user tries to access any other page when they are not logged in, they will be redirected back here (as you wouldn't want the user accessing any "protected" pages until they are logged in).

    I also included a little code on this page for if login_process.cfm finds that the username/password is invalid and redirects the user back here, it will give the user a message.
    Code:
    <html>
    <head>
        <title>Login</title>
    </head>
    
    <body>
        <cfif isDefined( 'url.invalidLogin' )>
            <font color="red">You have entered an invalid username/password. Please try again.</font>
        <cfelse>
            Please Log-in:
        </cfif>
        <br><br>
        
        <form action="login_process.cfm" method="post">
            Username: <input type="text" name="username"><br>
            Password: <input type="password" name="password"><br>
            <input type="submit" value="Login">
        </form>
    </body>
    </html>
    3) login_process.cfm - This is the target of the form submission in login.cfm. This file checks the entered username and password against the database, and determines if the user should be let in. For now, I just put in a simple if statement that checks for username 'test' and password 'test'. This is where you would query the database, and determine if the user is in your users table.

    If the username and password are invalid, the user is redirected back to login.cfm, with a variable in the url specifying just that.
    Code:
    <cfif form.username eq 'test' AND form.password eq 'test'>
        <cfset session.loggedIn = true>
        <cflocation url="memberWelcome.cfm">
    <cfelse>
        <cflocation url="login.cfm?invalidLogin=true">
    </cfif>
    4) memberWelcome.cfm - The page that the user comes to if they have successfully been logged in. This page will not be accessible until the user is logged in. This is enforced by the onRequestStart function in Application.cfc.
    Code:
    <html>
    
    <head>
        <title>Welcome</title>
    </head>
    
    <body>
        Welcome Member!  You would not be able to access this page if you were not logged in.<br><br>
        
        To test this, try logging out, and typing the URL for this page into the address bar. You should
        be automatically redirected back to login.cfm in this case.<br><br>
        
        <a href="logout.cfm">[Logout]</a>
    </body>
    
    </html>
    5) logout.cfm (Optional) - Simply sets session.loggedIn back to false to log the user out, and redirects him/her back to login.cfm.
    Code:
    <cfset session.loggedIn = false>
    
    <cflocation url="login.cfm">
    Note that you may need an index.cfm file in your webroot directory too for the initial redirect to work. It can just be blank for now.


    Let me know how it goes, and if you need any more help / explanation of how something is working.

    -Greg

  • #3
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    By the way, that code will only work with ColdFusion 7 or higher. If you're using 6 or below, let me know. We'll have to replace Application.cfc with an older Application.cfm file.

  • #4
    New to the CF scene
    Join Date
    Jan 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    thanks alot!!!!!!!

    thanks for the help.what would i have done. it sure gave me the idea that i needed to start off. i know i'm suppose to atleast work out something on my own before requesting for help but i'm sorry i just do not know how to. but if you can go further i want to be able to use records from a Microsoft Acess database. thanks

  • #5
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Hey, implementing a check against an access database for users is pretty easy. First thing is first though, do you have access to the ColdFusion administrator? If you don't, you need to figure out how to set up a Data Source with whatever host you are using.

    If you do have Administrator access, then you first need to set up a Data Source for the Access database. ColdFusion needs to have all of the details for connecting to the database first, before you can query it in code. All of that information (file location, connection credentials, etc) is stored under a single "Data Source Name", so that it can all be used in multiple places in your code, and if you ever need to change that information, you only have to change it in one place.

    So go into the ColdFusion Administrator, and go under "Data & Services" -> "Data Sources" (on the left menu). Enter a Data Source Name for your Access database, and select the Microsoft Access driver. If this Access database only holds users, you can name the Data Source something like "userDB". If it holds all of your website's data, you'll want to name it something more general, such as "siteDB" or even just "db". Once you click "Add", you'll be asked to locate the database file on the server, and for any credentials that ColdFusion will need to open it. I don't believe that you need to specify a "System Database File" by the way, and all of the "Advanced Settings" are probably fine by default.

    Once that's all set up, you can query the database (using the Data Source) to check user credentials. Here's an example login_process.cfm with a query. This example assumes that you have a table named 'users' inside of the database, and that the users table has fields: 'username' and 'password'. It will check for a record with a matching username and password sent from the login form, and if it finds one, will let the user in.
    Code:
    <cfquery name="checkUser" datasource="userDB">
        SELECT * FROM users
        WHERE username = '#form.username#'
            AND password = '#form.password#'
    </cfquery>
    
    <cfif checkUser.recordCount eq 1>
        <!--- A user record was found for the username/password, log them in --->
        <cfset session.loggedIn = true>
        <cflocation url="memberWelcome.cfm">
    <cfelse>
        <!--- A user record was not found for the username/password, send them back to the login page --->
        <cflocation url="login.cfm?invalidLogin=true">
    </cfif>
    I highlighted the data source name in red. That will be whatever you named it in the Administrator.

    Hope that helps, and let me know how it goes!

    -Greg

  • #6
    New Coder
    Join Date
    Mar 2010
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts
    hey Gjslick, I am using CFMX. can you pls post the older version of application.cfm
    Last edited by code L; 04-07-2010 at 03:16 PM.

  • #7
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Hey code L, no problem. Try this out as your Application.cfm file:
    Code:
    <cfapplication 
        name="MyApplication" 
        applicationTimeout="#createTimeSpan( 2, 0, 0, 0 )#"
        sessionManagement="true"
        sessionTimeout="#createTimeSpan( 0, 0, 20, 0 )#" 
        setClientCookies="true">
        
    
    <!--- Set session loggedIn key --->
    <cfif NOT structKeyExists( session, "loggedIn" )>
        <cflock scope="session" type="exclusive" timeout="10">
            <cfif NOT structKeyExists( session, "loggedIn" )>    <!--- Test again inside lock --->
                <cfset session.loggedIn = false>
            </cfif>
        </cflock>
    </cfif>
    
    
    <!--- If the user is not logged in, and they are not on the login or login processing page, 
                then redirect them back to login.cfm --->
    <cfset targetPage = cgi.SCRIPT_NAME>
    <cflock scope="session" type="readonly" timeout="10">
        <cfset loggedIn = session.loggedIn>
    </cflock>
    <cfif NOT loggedIn AND targetPage neq "/login.cfm" AND targetPage neq "/login_process.cfm">
        <cflocation url="/login.cfm">
    </cfif>
    The complex looking locking code that sets the session.loggedIn variable is only needed for the rare chance that two threads will be updating the key at the same time for the same user (i.e. the user opened two browser windows, your site is in frames, etc), but better safe than sorry. Can't remember if CFMX suffers from the possibility of memory corruption when multiple threads are accessing shared memory at the same time, or if they had fixed that issue by then. I'm pretty sure versions up to CF5 did have the possibility of that problem tho.

    That outer <cfif> around the exclusive lock is for performance reasons, as there is a little overhead involved in creating a lock, but the lock is only needed on the user's first request for a page to your site. After that, session.loggedIn will have been created, and there is no reason to create an extra lock each time a page is requested from then on. The readonly lock is still needed though.

    Speaking of which, the other pages should change slightly too to incorporate shared memory locks as well. I think I just wanted to make the code be simple originally, but they should have had them all along

    login_process.cfm:
    Code:
    <cfif form.username eq 'test' AND form.password eq 'test'>
        <cflock scope="session" type="exclusive" timeout="10">
            <cfset session.loggedIn = true>
        </cflock>
        <cflocation url="memberWelcome.cfm">
    <cfelse>
        <cflocation url="login.cfm?invalidLogin=true">
    </cfif>
    logout.cfm:
    Code:
    <cflock scope="session" type="exclusive" timeout="10">
        <cfset session.loggedIn = false>
    </cflock>
    
    
    <cflocation url="login.cfm">
    Let me know how that goes.

    -Greg

  • #8
    New Coder
    Join Date
    Mar 2010
    Posts
    22
    Thanks
    3
    Thanked 0 Times in 0 Posts
    thanks =)

  • #9
    New Coder
    Join Date
    Jul 2008
    Posts
    31
    Thanks
    3
    Thanked 0 Times in 0 Posts
    This is so useful, whoever has written this is amazing and I would be SO happy if you could help me understand why it just won't work for me!

    I'm totally stuck. You can access memberwelcome.cfm even if you're not logged in and logging in doesn't even seem to do anything.

    What am I doing wrong?!

    application.cfm

    Code:
    <cfcomponent output="false">
    
        <cfset this.name = "MyApplication">
        <cfset this.applicationTimeout = createTimeSpan( 2, 0, 0, 0 )>    <!--- 2 Days --->
        <cfset this.sessionManagement = true>
        <cfset this.sessionTimeout = createTimeSpan( 0, 0, 20, 0 )>    <!--- 20 min --->
        <cfset this.setClientCookies = true>
    
        
        <cffunction name="onSessionStart">
            <cfset session.loggedIn = false>
        </cffunction>
        
        
        <cffunction name="onRequestStart">
            <cfargument name="targetPage" type="string" required="true">
            
            <!--- If the user is not logged in, and they are not on the login or login processing page, 
                        then redirect them back to login.cfm --->
            <cfif NOT session.loggedIn AND targetPage neq "http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/cfhome.cfm" AND targetPage neq "http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/login_process.cfm">
                <cflocation url="http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/cfhome.cfm">
            </cfif>
        </cffunction>
        
    </cfcomponent>

  • #10
    New Coder
    Join Date
    Jul 2008
    Posts
    31
    Thanks
    3
    Thanked 0 Times in 0 Posts
    my login form:

    Code:
    <cfif isDefined( 'url.invalidLogin' )>
            <font color="red">You have entered an invalid username/password. Please try again.</font>
    		
      
          <cfform name="login" action="http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/login_process.cfm" method="post">
    <table width="130" border="0" align="right" cellpadding="0" cellspacing="0">
      <tr>
        <td width="130"><div align="right">
          <cfinput type="text" class="loginform" name="username" value="Username" onFocus="this.value=''">
        </div></td>
      </tr>
      <tr>
        <td>        <div align="right">
              <cfinput type="password" class="loginform" name="password" value="password" onFocus="this.value=''">        
              <cfinput name="submit" type="submit" class="loginformbutton" value="Log In">    
            </div></td>
      </tr>
    </table>
    <br>
    </cfform>
    
     <cfelse>You're logged in as <cfoutput>#getauthuser()#</cfoutput> 
     <a href="logout.cfm">logout</a>
    
     </cfif>
    my login_process
    Code:
    <cfquery name="checkUser" datasource="062105cs06sr">
        SELECT * FROM users
        WHERE username = '#form.username#'
            AND password = '#form.password#'
    </cfquery>
    
    <cfif checkUser.recordCount eq 1>
        <!--- A user record was found for the username/password, log them in --->
        <cfset session.loggedIn = true>
        <cflocation url="memberWelcome.cfm">
    <cfelse>
        <!--- A user record was not found for the username/password, send them back to the login page --->
        <cflocation url="cfhome.cfm?invalidLogin=true">
    </cfif>
    my logout
    Code:
    <cflock scope="session" type="exclusive" timeout="10">
        <cfset session.loggedIn = false>
    </cflock>
    
    
    <cflocation url="cfhome.cfm">

    I have been trying to get my head around this for AGES and it's not happening!

  • #11
    Regular Coder
    Join Date
    Feb 2009
    Location
    NJ, USA
    Posts
    476
    Thanks
    2
    Thanked 70 Times in 69 Posts
    Quote Originally Posted by suzierthanyou View Post
    What am I doing wrong?!

    application.cfm

    Code:
    <cfcomponent output="false">
    
        <cfset this.name = "MyApplication">
        <cfset this.applicationTimeout = createTimeSpan( 2, 0, 0, 0 )>    <!--- 2 Days --->
        <cfset this.sessionManagement = true>
        <cfset this.sessionTimeout = createTimeSpan( 0, 0, 20, 0 )>    <!--- 20 min --->
        <cfset this.setClientCookies = true>
    
        
        <cffunction name="onSessionStart">
            <cfset session.loggedIn = false>
        </cffunction>
        
        
        <cffunction name="onRequestStart">
            <cfargument name="targetPage" type="string" required="true">
            
            <!--- If the user is not logged in, and they are not on the login or login processing page, 
                        then redirect them back to login.cfm --->
            <cfif NOT session.loggedIn AND targetPage neq "http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/cfhome.cfm" AND targetPage neq "http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/login_process.cfm">
                <cflocation url="http://newmedia.leeds.ac.uk/ug06/cs06sr/cf/cfhome.cfm">
            </cfif>
        </cffunction>
        
    </cfcomponent>
    Ok, a few things:

    1) Is that file named Application.cfm or Application.cfc? It should be Application.cfc. (Requires CF7 or higher btw. Otherwise use the Application.cfm file earlier in this thread.)


    2) In your <cfif> for the target page, the targetPage variable is going to be a relative URL, not a full http:// URL. Your code should probably be something along the lines of:
    Code:
    <cfif NOT session.loggedIn AND targetPage neq "/ug06/cs06sr/cf/cfhome.cfm" AND targetPage neq "/ug06/cs06sr/cf/login_process.cfm">
        <cflocation url="/ug06/cs06sr/cf/cfhome.cfm">
    </cfif>
    However, if that is not exactly it, then you need to determine what targetPage is giving you when you access your pages. Try throwing an error with targetPage's value so you that you can see it:
    Code:
    <cffunction name="onRequestStart">
        <cfargument name="targetPage" type="string" required="true">
        
        <!--- Show me the value of targetPage when I request a file --->
        <cfthrow message="TargetPage: '#targetPage#'">
        
        <!--- If the user is not logged in, and they are not on the login or login processing page,
                    then redirect them back to login.cfm --->
        <cfif NOT session.loggedIn AND targetPage neq "/ug06/cs06sr/cf/cfhome.cfm" AND targetPage neq "/ug06/cs06sr/cf/login_process.cfm">
            <cflocation url="/ug06/cs06sr/cf/cfhome.cfm">
        </cfif>
    </cffunction>
    Then you can build your <cfif> around that value. But unless you have some different server configuration, my guess is that targetPage will be "/ug06/cs06sr/cf/cfhome.cfm" when you request the cfhome.cfm page.


    3) This was a very simple login example, and doesn't make use of the <cflogin> tag (which isn't actually necessary btw; I don't personally use it on my production site). So therefore you won't have access to the #getAuthUser()# function on your login form. You can implement this with the <cflogin> tag if you want though. Just look up the documentation for it.

    However if you just want to store and display the user's name and such, you can create session variables for those values, and then populate them when you run your database query.



    Hope that helps, and let me know if you get it working or are still having trouble.

    -Greg

  • Users who have thanked Gjslick for this post:

    suzierthanyou (04-11-2010)

  • #12
    New Coder
    Join Date
    Jul 2008
    Posts
    31
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thank you!! It's working now!

  • #13
    New to the CF scene
    Join Date
    Jul 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    A simple login, put this in your application.cfm or application.cfc page. At the top of each page set <cfif Session.LogInKeyword eq "George123"> Make up your own check pattern.

    <cfapplication sessionmanagement="Yes" sessiontimeout="#createtimespan(0,0,15,0)#">

    <cfparam name="LoggingOut" default="No">
    <cfparam name="Session.LogInKeyword" default="none">
    <cfparam name="Attempting" default="No">

    <cfif LogginOut eq "Yes">
    <cfset Session.LogInKeyword = "none">
    <!--- This LoggingOut comes from any "Log Out" link or form --->
    </cfif>

    <cfinclude template="includes/PageHeader.htm">

    <cfif Session.LogInKeyword eq "none">
    <cfif Attempting eq "Yes"> <!--- Sent "Yes" as hidden field from Login form --->
    <cfquery name="GetLogIn" datasource="[Your DSN">
    select UserPwd from Users where UserID = '#UserID#'
    </cfquery>

    <cfif Form.UserPwd eq GetLogin.UserPwd>
    <cfset Session.LogInKeyword eq "George123">
    <cfelse>
    <h2>Sorry, Your Login is Incorrect</h2>
    </cfif>
    </cfif>
    <h2>You Must Login<h2>
    <cfinclude template="includes/LoginForm.htm">
    </cfif>

    The PageHeader.htm would contain your DOCTYPE, HEAD, the LINK to your stylesheet, the BODY tag, and the banner, but NOT the navigation. That comes next:

    <cfif Session.LogInKeyword eq "George">
    <cfinclude template/Navigation.htm">
    ... (Page content etc)
    </cfif>

    Okay, you caught me, I save my includes as .htm (I like the color coding in HTMLkit). But ColdFusion (unlike PHP) MERGES the include first, THEN parses the code. so you includes can contain CFML and be saved as .htm and they'll work fine.

    Good Luck.

    ~Bob in Texas
    Last edited by TexasLegacy; 07-13-2010 at 09:54 PM. Reason: Added the logout sequence


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •