Question

LogIn-set cookie-Autologin in coldfusion

Asked by: panosms

Hello experts.
I have built a login page with Hash check,session user_id set and cookie set.
I want a help how the Autologin function  works (please write the code for this) and please check out if the code has mistakes or can be better.

<h3>LogInExample with Hash</h3>
<cfparam name="cookie.email" default="">
<cfparam name="cookie.password" default="">
<cfparam name="cookie.rememberme" default="">
<cfparam name="cookie.AutoLogIn" default="">
<!--- Do the following if the form is submitted. --->
<cfif IsDefined("Form.Email")>
   <!--- query the data base. ---> 
   <cfquery name = "CheckPerson" datasource = "#request.dsn#">
      SELECT Password ,email,user_ID
      FROM users
      WHERE email = <cfqueryparam value = "#Form.email#"
         cfsqltype = "CF_SQL_VARCHAR"> 
   </cfquery>
         
   <!--- Compare query PasswordHash field and the hashed form password
         and display the results. --->
   <cfoutput>
      <cfif Hash(Form.password, "SHA") is not checkperson.password>
         <cflocation url = "loginfailed.cfm">
      <cfelse>
         <cfset session.allowin = "True">
         <cfset session.user_id = CheckPerson.user_id>
         <cfif isdefined("Form.rememberme") AND Form.rememberme EQ 1>
         <cfcookie name="email" value="#form.email#" expires="never">
         <cfcookie name="password" value="#form.password#" expires="never">
         <cfcookie name="rememberme" value="#form.rememberme#" expires="never">
         <cfcookie name="AutoLogIn" value="#form.AutoLogIn#" expires="never">
         <cfelse>
         <cfcookie name="email" value='NULL' expires="now">
         <cfcookie name="password" value='NULL' expires="now">
         <cfcookie name="rememberme" value='NULL' expires="now">
         <cfcookie name="AutoLogIn" value='NULL' expires="now">
         </cfif>
         <cflocation url = "welcome.cfm">
      </cfif>
   </cfoutput>
</cfif>
 
<!--- Form for entering ID and password. --->
<form  name="LogIn" action="#CGI.SCRIPT_NAME#" method="post">
   <b>Email: </b>
   <input type = "text" name="email"  value="<cfoutput>#cookie.email#</cfoutput>"><br/><br/>
   <b>Password: </b>
   <input type = "text" name="password" value="<cfoutput>#cookie.password#</cfoutput>"><br/><br/>
   <b>Remember me:</b>
   <input name="rememberme" type="checkbox" value="1"
    <cfif (#cookie.rememberme# EQ 1)> checked="checked" </cfif> /><br /><br />
   <b>AutoLogIn:</b>
   <input name="AutoLogIn" type="checkbox" value="1" 
   <cfif (#cookie.AutoLogIn# EQ 1)> checked="checked" </cfif>/><br /><br />
   <input type = "Submit" value = "LogIn"  id="LogIn">
</form>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-02-12 at 05:13:51ID24136992
Tags

Coldfusion

Topics

ColdFusion Application Server

,

ColdFusion Studio

Participating Experts
2
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. session cookie
    i want to set session cookie, i saw some cookies of 32 bits from other web sites, how can they set them? how to generate a 32bits session cookie? any one can provide me the code and explaination?
  2. Cookie
    I am trying to create a cookie. I have created a staffing system, now i am trying to create a cookie. But just cant get my head round it. When a user log on i want his boatID (below is the code for select) to be stored within a cookie and must expire at the end of the sess...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: js_vaughanPosted on 2009-02-12 at 07:52:23ID: 23623143

First off, you dont need to save your password.  Your correctly have your cookies set only after the password has been confirmed, so you know cookies will only come from someone who already knows it.  For security purposes, do not save the password as a cookie - you dont need to - email is enough.

My second suggestion is to add an additional cookie AND database field to hold a date-time value.  Assign now() to a variable then distribute something like this :
<cfset myTimeVar="#now()#">
<cfcookie name="cookieTime" value="#myTimeVar#" expires="never">
<!--- insert myTimeVar to the database as well --->

This cookieTime will prevent the "remember me" from allowing unlimited access from multiple computers.  This, i believe, is extremely important in case a user accidentally clicks remember me from a public computer.  Example: User logs in at home when they wake up.  COOKIE.cookieTime and the DB timestamp are both set at Jan 1st 10am.  The next day User goes to a public computer, clicks remember me, so now the public COOKIE.cookieTime is set and the DB timestamp is overridden to Jan 2nd 1pm.  When user returns home and tries to login later that day, their COOKIE.cookietime still says Jan 1st 10am, but the database holds Jan 2nd 1pm (created from their time out in public)  Access is denied.  But no worry, user logs in again, clicks the remember me... and now his local cookie will say Jan 2nd 7pm and the DB timestamp is overwritted to hold the new Jan 2nd 7pm as well.  That potential security threat is gone because the public computer's cookie will say Jan 2nd 1pm, but the database will say Jan 2nd 7pm.  The public computer is no longer in sync and will not be able to reconnect.  Meanwhile, the user goes to sleep, wakes up, goes to their computer on Jan 3rd...  and both their cookie and DB timestamp will still be set to Jan 2nd 7pm... access is granted.

The final piece of the puzzle: how to handle the login.  I would recommend your application.cfc/cfm hold code similar to this ....

<!--- check if user is already logged in --->
<cfif NOT isDefined("session.allowin") OR session.allowin NEQ TRUE>
  <!--- if not, lets check for a cookie --->
  <cfif isDefined("COOKIE.AutoLogIn") AND isDefined("COOKIE.email")>
    <!--- check cookie against database --->
  <cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
    SELECT user_id
    FROM users
    WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
    AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">
  </cfquery>
  <!--- if 1 record is found, we have a valid login --->
  <cfif CheckPerson.recordCount EQ 1>
    <cfset session.allowin = "True">
    <cfset session.user_id = CheckPerson.user_id>
    <cflocation url="welcome.cfm" addtoken="no">
  <cfelse>
    <!--- if we didnt find 1 record, something is wrong... remove the autologin --->
    <cfcookie name="AutoLogIn" expires="now">
    <cfinclude template="/login.cfm">
    <cfabort>
  </cfif>
  <cfelse>
    <!--- we didnt find a SESSION or COOKIE value that allows for login;  force login --->
  <cfinclude template="/login.cfm">
  <cfabort>
  </cfif>
</cfif>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

 

by: panosmsPosted on 2009-02-12 at 08:32:50ID: 23623761

hi js_vaughan:
Thank you for your help.
Because  have an area for no registerd users and an area for registerd users i think i cannot use the code in the application cfm.
With your corrections can you please write the new loginpage?(i'm not sure i can do it myself)

 

by: js_vaughanPosted on 2009-02-12 at 09:22:13ID: 23624314

how do you currently handle redirecting users to the login page when non-registered users try to access those restricted pages?

 

by: panosmsPosted on 2009-02-12 at 09:42:49ID: 23624523

For example.
I have insert pages and when session.user_ID is 0 (default value) i use cflocation to login.cfm.If not i allow the page open.
(until now i did use the extension from webassist to handle all the security things but i want now to do this with hand coding)

 

by: duncancummingPosted on 2009-02-12 at 10:16:06ID: 23624890

<!--- Compare query PasswordHash field and the hashed form password
        and display the results. --->
  <cfoutput>

You don't need the cfoutput around normal blocks of CF code, unless you're actually outputting information (or perhaps doing a <cfoutput query="q"> )


<cfif (#cookie.rememberme# EQ 1)>

You don't need the parentheses, but more importantly, you don't need the # # in most cf tags, such as cfif and cfset.  There are exceptions.  The above line could just be written as:
<cfif cookie.rememberme EQ 1>
Removing the unnecessary # #  will make your code easier to read and maintain, and also should be slightly faster to execute

 

by: panosmsPosted on 2009-02-12 at 10:33:53ID: 23625090

Thank you duncancumming
I have correct this now

 

by: panosmsPosted on 2009-02-12 at 11:24:51ID: 23625663

Hi js_vaughan again.
You say "...you dont need to save your password....".
I understand that it is not good for security reasons but does it work when i don't have a cookie for password?
The page will load and the email field will have the cookie value and the password nothing.
So i will not be able to login. or not?
Am i  missing something?....
And is this wrong to check out if the session.user_id is not 0?
In the application.cfm i have :<CFPARAM NAME="session.user_id"  type="numeric" DEFAULT="0">

 

by: js_vaughanPosted on 2009-02-12 at 11:45:47ID: 23625878

You do not need the password.  The cookie is only set AFTER the email+password has been verified.  So the email cookie will inherit with it the understanding that authorization has already been approved.

Since authorization has been approved, lets locate their record
... WHERE Email = "#COOKIE.email#" ...

So long as your business rules enforce that the email address is unique,  you will not have problems...

> Do you tell new users "sorry, someone else has already registered that email" if it already exists in your users table?
> If users can update their email addresses, do you check that someone else does not already have it before commiting the update?

NOW, if your business rules allow for two users to share the same email, then ignore the email all together, and store the UID in a cookie.

I can give you a more complete login.cfm tonight, i have to get to work for now though.

 

by: panosmsPosted on 2009-02-13 at 02:53:40ID: 23631446

Hi js_vaughan again.
While waiting for your login page i have done some corrections to my.
I understand now the autogin function.I can have this code in the top of my insert pages to allow or not the user to use the page(OR NOT???).
I don't know how to use the remember cookie.
Look at the register page ,application and the new login.I have there cfif tags they handle wich cookie will be created.

register.cfm
<cfif IsDefined("Form.Register")>
 <cfquery name="usersemail" datasource="#request.dsn#">
    SELECT Email 
    FROM dbo.users 
    WHERE Email='#FORM.rEmail#'
  </cfquery>
  <cfif usersemail.RecordCount GTE 1>
<cflocation url="userexists.cfm?requsername=#FORM.rEmail#" addtoken="no">
 <cfelse>
<cfquery datasource="#request.dsn#">
INSERT INTO users (email, password,Firstname,Lastname)
VALUES (
<cfqueryparam value="#FORM.rEmail#" cfsqltype="cf_sql_clob" maxlength="255">, 
<cfqueryparam value="#Hash(Form.rPassword,"SHA")#" cfsqltype="cf_sql_clob" maxlength="255">,
<cfqueryparam value="#FORM.rFirstname#" cfsqltype="cf_sql_clob" maxlength="255">,
<cfqueryparam value="#FORM.rLastname#" cfsqltype="cf_sql_clob" maxlength="255">)
</cfquery>
<cflocation url="newuser.cfm">
</cfif>
</cfif>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
<body>
<form action="#CGI.SCRIPT_NAME#" method="post">
<b>Email:</b>
<input name="rEmail" type="text" size="30" maxlength="150" /><br /><br />
<b>Firstname:</b>
<input name="rFirstname" type="text" size="30" maxlength="150" /><br /><br />
<b>Lastname:</b>
<input name="rLastname" type="text" size="30" maxlength="150" /><br /><br />
<b>Password:</b>
<input name="rPassword" type="Password" size="30" maxlength="150" /><br /><br />
<input name="Register" type="submit" /></form>
</body>
</html>
 
login.cfm
<h3>LogInExample with Hash</h3>
<cfset myTimeVar="#now()#">
<cfparam name="cookie.lemail" default="">
<cfparam name="cookie.rememberme" default="">
<cfparam name="cookie.AutoLogIn" default="">
<cfparam name="cookie.cookietime" default="">
<cfparam name="form.rememberme" default="">
<cfparam name="form.AutoLogIn" default="">
<!--- Do the following if the form is submitted. --->
<cfif IsDefined("Form.lEmail")>
   <!--- query the data base. ---> 
   <cfquery name = "CheckPerson" datasource = "#request.dsn#">
      SELECT Password ,email,user_ID
      FROM users
      WHERE email = <cfqueryparam value = "#Form.lemail#" cfsqltype = "CF_SQL_VARCHAR"> 
      <cfif cookie.cookietime NEQ "">
      AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">
      </cfif>
 
   </cfquery>
         
   <!--- Compare query PasswordHash field and the hashed form password
         and display the results. --->
   
      <cfif Hash(Form.lpassword, "SHA") is not checkperson.password>
         <cflocation url = "loginfailed.cfm">
      <cfelse>
         <cfset session.allowin = "True">
         <cfset session.user_id = CheckPerson.user_id>
         
         <cfquery name="LastLogIn" datasource="#request.dsn#">
         Update users
         SET LastLogIn = '#DateFormat(myTimeVar, "yyyy-mm-dd")# #TimeFormat(myTimeVar, "hh:mm:ss")#'
         WHERE user_Id = #session.user_Id#
         </cfquery>
         
         <cfif Form.rememberme EQ "" AND Form.AutoLogIn EQ 1>
         <cfcookie name="lemail" value="#form.lemail#" expires="never">
         <cfcookie name="AutoLogIn" value="#form.AutoLogIn#" expires="never">
         <cfcookie name="rememberme" value='NULL' expires="now">
         <cfcookie name="cookieTime" value="#myTimeVar#" expires="never">
         <cfquery name="q_cookietime" datasource="#request.dsn#">
         Update users
         SET Cookietime = '#DateFormat(myTimeVar, "yyyy-mm-dd")# #TimeFormat(myTimeVar, "hh:mm:ss")#'
         WHERE user_Id = #session.user_Id#
         </cfquery>
         
         <cfelseif Form.rememberme EQ 1 AND Form.AutoLogIn EQ "">
         <cfcookie name="lemail" value="#form.lemail#" expires="never">
         <cfcookie name="rememberme" value="#form.rememberme#" expires="never">
         <cfcookie name="AutoLogin" value='NULL' expires="now">
         <cfcookie name="cookieTime" value="#myTimeVar#" expires="never">
         <cfquery name="q_cookietime" datasource="#request.dsn#">
         Update users
         SET Cookietime = '#DateFormat(myTimeVar, "yyyy-mm-dd")# #TimeFormat(myTimeVar, "hh:mm:ss")#'
         WHERE user_Id = #session.user_Id#
         </cfquery>
         
         <cfelseif Form.rememberme EQ 1 AND Form.AutoLogIn EQ 1>
         <cfcookie name="lemail" value="#form.lemail#" expires="never">
         <cfcookie name="rememberme" value="#form.rememberme#" expires="never">
         <cfcookie name="AutoLogin" value="#form.AutoLogIn#" expires="never">
         <cfcookie name="cookieTime" value="#myTimeVar#" expires="never">
         <cfquery name="q_cookietime" datasource="#request.dsn#">
         Update users
         SET Cookietime = '#DateFormat(myTimeVar, "yyyy-mm-dd")# #TimeFormat(myTimeVar, "hh:mm:ss")#'
         WHERE user_Id = #session.user_Id#
         </cfquery>
         
         <cfelse>
         <cfcookie name="rememberme" value='NULL' expires="now">
         <cfcookie name="lemail" value='NULL' expires="now">
         <cfcookie name="AutoLogin" value='NULL' expires="now">
         <cfcookie name="cookietime" value='NULL' expires="now">
         </cfif>
     
         <cflocation url = "welcome.cfm">
      </cfif>
   
</cfif>
 
<!--- Form for entering ID and password. --->
<form  name="LogIn" action="#CGI.SCRIPT_NAME#" method="post">
   <b>Email: </b>
   <input type = "text" name="lemail"  value="<cfoutput>#cookie.lemail#</cfoutput>"><br/><br/>
   <b>Password: </b>
   <input type = "password" name="lpassword" value=""><br/><br/>
   <b>Remember me:</b>
   <input name="rememberme" type="checkbox" value="1"
    <cfif cookie.rememberme EQ 1> checked="checked" </cfif> /><br /><br />
    <b>AutoLogIn:</b>
    <input name="AutoLogIn" type="checkbox" value="1"
    <cfif cookie.AutoLogIn EQ 1> checked="checked" </cfif> /><br /><br />
   <input type = "Submit" value = "LogIn"  id="LogIn">
</form>
 
Application.cfm
<cfapplication name="market"  clientmanagement="Yes"
                    sessionmanagement="Yes"
                    sessiontimeout="#CreateTimeSpan(0,0,15,0)#"
                    applicationtimeout="#CreateTimeSpan(0,2,0,0)#">
<CFSET request.dsn = "myDB"> 
<CFPARAM NAME="session.allowin" DEFAULT="false">
<CFPARAM NAME="session.user_id"  type="numeric" DEFAULT="0">

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:

Select allOpen in new window

 

by: js_vaughanPosted on 2009-02-13 at 10:03:42ID: 23635359

As for the register.cfm, why are you using cf_sql_clob?  You should be using cl_sql_varchar

For the login.cfm, I have not tested the code, but here is a good mockup:

<cfparam name="VARIABLES.loginPassed" type="boolean" default="FALSE">
 
<!--- Check if user is already logged in --->
<cfif session.allowin EQ TRUE>
 
    <!--- Fake a new login --->
    <cfset CheckPerson = StructNew()>
    <cfset CheckPerson.user_id = session.user_id>    
    <cfset VARIABLES.loginPassed = TRUE>
    
<!--- IF not, lets check for a cookie --->
<cfelseif isDefined("COOKIE.AutoLogIn") AND isDefined("COOKIE.email")>
 
    <!--- check cookie against database --->
    <cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
        SELECT user_id
        FROM users
        WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
        AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">
    </cfquery>
    
    <!--- if 1 record is found, we have a valid login --->
    <cfif CheckPerson.recordCount EQ 1>
        <cfset VARIABLES.loginPassed = TRUE>
        
    <!--- if we didnt find 1 record, our cookie is out of sync... remove the autologin, and proceed to login --->
    <cfelse>
        <cfcookie name="AutoLogIn" expires="now">
    </cfif>
        
<!--- Do the following if the form is submitted. --->
<cfelseif IsDefined("Form.lEmail")>
    <cfset VARIABLES.hashedPass = Hash(Form.lpassword, "SHA")>
    
    <!--- Create our checkboxs if they do not exist --->
    <cfparam name="form.rememberme" default="">
    <cfparam name="form.AutoLogIn" default="">
    
    <!--- query the data base. ---> 
    <cfquery name="CheckPerson" datasource="#request.dsn#">
        SELECT Password, email, user_ID
        FROM users
        WHERE email = <cfqueryparam value="#Form.lemail#" cfsqltype="CF_SQL_VARCHAR">
        AND Password = <cfqueryparam value="#VARIABLES.hashedPass#" cfsqltype="cf_sql_varchar">
    </cfquery>
    
    <!--- User is authorized from the form --->
    <cfif CheckPerson.recordCount EQ 1>
        <cfset VARIABLES.loginPassed = TRUE>
        <cfset VARIABLES.myTimeVar="#now()#">
        
        <!--- Handle cookies in all uppercase --->
        
        <!--- Check if rememberme or AutoLogIn hold positive values --->
        <cfif Form.rememberme OR Form.AutoLogIn>
            <CFCOOKIE name="LEMAIL" value="#Form.lemail#" expires="never">
            <CFCOOKIE name="REMEMBERME" value="1" expires="never">
            
            <!--- if AutoLogIn, add login cookies --->
            <cfif Form.AutoLogIn>
                <CFCOOKIE name="AUTOLOGIN" value="1" expires="never">
                <CFCOOKIE name="COOKIETIME" value="#myTimeVar#" expires="never">
            <cfelse>
                <CFCOOKIE name="AUTOLOGIN" expires="now">
                <CFCOOKIE name="COOKIETIME" expires="now">
            </cfif>
            
        <!--- Otherwise if user wishes to remain anonymous, remove these client cookies --->
        <cfelse>
            <CFCOOKIE name="LEMAIL" expires="now">
            <CFCOOKIE name="REMEMBERME" expires="now">
            <CFCOOKIE name="AUTOLOGIN" expires="now">
            <CFCOOKIE name="COOKIETIME" expires="now">
        </cfif>
        
        <!--- Handle database updates --->
        
        <cfquery name="LastLogIn" datasource="#request.dsn#">
            Update users
            SET <cfif Form.AutoLogIn>Cookietime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#">,</cfif>
            LastLogIn = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#">
            WHERE user_Id = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.user_Id#">
        </cfquery>
    
    <!--- User failed authorization from the form --->
    <cfelse>
        <cflocation url = "loginfailed.cfm" addtoken="no">
    </cfif>
</cfif>
 
<!--- If the user was authorized from any of the above steps, proceed with login --->
<cfif VARIABLES.loginPassed>
    <cfset session.allowin = "True">
    <cfset session.user_id = CheckPerson.user_id>
    <cflocation url="welcome.cfm" addtoken="no">
</cfif>
 
<!--- User is not authorized.  Continue with login form for entering ID and password. --->
<h3>LogInExample with Hash</h3>
<form  name="LogIn" action="#CGI.SCRIPT_NAME#" method="post">
   <b>Email: </b>
   <input type = "text" name="lemail"  value="<cfoutput>#cookie.lemail#</cfoutput>"><br/><br/>
   <b>Password: </b>
   <input type = "password" name="lpassword" value=""><br/><br/>
   <b>Remember me:</b>
   <input name="rememberme" type="checkbox" value="1"
    <cfif cookie.rememberme EQ 1> checked="checked" </cfif> /><br /><br />
    <b>AutoLogIn:</b>
    <input name="AutoLogIn" type="checkbox" value="1"
    <cfif cookie.AutoLogIn EQ 1> checked="checked" </cfif> /><br /><br />
   <input type = "Submit" value = "LogIn"  id="LogIn">
</form>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:

Select allOpen in new window

 

by: panosmsPosted on 2009-02-14 at 04:06:29ID: 23640382

Hi js_vaughan.
The only problem i have is that the query LastLogIn does not work.I can't get the cookietime and LastLogIn  in the DB and so i have  all the problems that have to do with this.The rest of the code is very good and is better than that what i have posted.
Because i had the error ....cannot convert the value "''" to a boolean....i did change your code:
<cfif Form.rememberme  OR Form.AutoLogIn> to <cfif Form.rememberme EQ 1  OR Form.AutoLogIn EQ 1>
<cfif Form.AutoLogIn> to <cfif Form.AutoLogIn EQ 1>

 

by: js_vaughanPosted on 2009-02-14 at 06:39:52ID: 23640813

Is it throwing an error?

 

by: panosmsPosted on 2009-02-14 at 07:57:33ID: 23641112

no
i have no error message now but as i the value don't get in the DB

 

by: js_vaughanPosted on 2009-02-14 at 08:06:13ID: 23641152

My mistake, try fixing this line :

WHERE user_Id = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.user_Id#">

#session.user_Id# should be "CheckPerson.user_Id"

If the cookie value is still not being set, check if the lastlogin is being set atleast...

 

by: panosmsPosted on 2009-02-14 at 08:13:47ID: 23641185

Now it is passing the cookietime but as the two datetime forms are different the autologin cookie will be deleted.
The cookie datetime format is:2009-02-14 18:11:43
  and the DB value is :Feb 14 2009  6:11PM

 

by: js_vaughanPosted on 2009-02-14 at 08:26:42ID: 23641232

Lets mimic the database format into our myTimeVar like so :

<cfset VARIABLES.myTimeVar="#dateformat(now(),'mmm dd yyyy') & '  ' & timeformat(now(),'h:mmtt')#">

 

by: panosmsPosted on 2009-02-14 at 08:29:40ID: 23641256

Now i change the:<cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#"> to:
'#DateFormat(myTimeVar, "yyyy-mm-dd")# #TimeFormat(myTimeVar, "HH:mm:ss")#'
and have the same output but the autologin does not work.

 

by: js_vaughanPosted on 2009-02-14 at 08:35:53ID: 23641311

ok, lets do this... leave myTimeVar = now() like it was...

we will move the check elsewhere to take the database format completly out of the picture.

change these lines :

    <!--- check cookie against database --->
    <cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
        SELECT user_id
        FROM users
        WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
        AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">
    </cfquery>
   
    <!--- if 1 record is found, we have a valid login --->
    <cfif CheckPerson.recordCount EQ 1>

to the lines below :

    <!--- check cookie against database --->
    <cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
        SELECT CookieTime, user_id
        FROM users
        WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
        AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">
    </cfquery>
	
	<!--- Make sure cookieTime's are in the same format --->
	<cfset VARIABLES.DBCookieTime = DateFormat(CheckPerson.CookieTime,"yyyy mm dd") & TimeFormat(CheckPerson.CookieTime,"hh:mm:ss")>
	<cfset VARIABLES.ClientCookieTime = DateFormat(COOKIE.COOKIETIME,"yyyy mm dd") & TimeFormat(COOKIE.COOKIETIME,"hh:mm:ss")>
    
    <!--- if 1 record is found, we have a valid login --->
    <cfif CheckPerson.recordCount EQ 1 AND VARIABLES.DBCookieTime EQ VARIABLES.ClientCookieTime>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: js_vaughanPosted on 2009-02-14 at 08:36:51ID: 23641322

sorry, remove the "AND CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#COOKIE.cookieTime#">" also

    <!--- check cookie against database --->
    <cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
        SELECT CookieTime, user_id
        FROM users
        WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
    </cfquery>
	
	<!--- Make sure cookieTime's are in the same format --->
	<cfset VARIABLES.DBCookieTime = DateFormat(CheckPerson.CookieTime,"yyyy mm dd") & TimeFormat(CheckPerson.CookieTime,"hh:mm:ss")>
	<cfset VARIABLES.ClientCookieTime = DateFormat(COOKIE.COOKIETIME,"yyyy mm dd") & TimeFormat(COOKIE.COOKIETIME,"hh:mm:ss")>
    
    <!--- if 1 record is found, we have a valid login --->
    <cfif CheckPerson.recordCount EQ 1 AND VARIABLES.DBCookieTime EQ VARIABLES.ClientCookieTime>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: js_vaughanPosted on 2009-02-14 at 08:38:43ID: 23641335

Sorry, im getting ahead of myself... give me a moment to test the code...

 

by: panosmsPosted on 2009-02-14 at 08:44:41ID: 31546028

Thank you very much for your help.
It is a very good tutorial!!!!
regards
Panos

 

by: panosmsPosted on 2009-02-14 at 08:46:13ID: 23641387

the <cfset VARIABLES.myTimeVar="#dateformat(now(),'mmm dd yyyy') & '  ' & timeformat(now(),'h:mmtt')#"> was ok.
I did not see this post that s why i did post my dateformat

 

by: js_vaughanPosted on 2009-02-14 at 08:46:22ID: 23641390

Yes, that last correction did test out for me:

<!--- check cookie against database --->
<cfquery name="CheckPerson" datasource="#APPLICATION.datasource#">
	SELECT CookieTime, user_id
	FROM users
	WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.email#">
</cfquery>
 
<!--- Make sure cookieTime's are in the same format --->
<cfset VARIABLES.DBCookieTime = DateFormat(CheckPerson.CookieTime,"yyyy mm dd") & TimeFormat(CheckPerson.CookieTime,"hh:mm:ss")>
<cfset VARIABLES.ClientCookieTime = DateFormat(COOKIE.COOKIETIME,"yyyy mm dd") & TimeFormat(COOKIE.COOKIETIME,"hh:mm:ss")>
 
<!--- if 1 record is found, we have a valid login --->
<cfif CheckPerson.recordCount EQ 1 AND VARIABLES.DBCookieTime EQ VARIABLES.ClientCookieTime>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: js_vaughanPosted on 2009-02-14 at 08:49:19ID: 23641402

Gotcha,

either way you should probably follow this last routine, of leaving myTimeVar just equal to now().  The reason is that by making myTimeVar "mimic" the database, we are linking the two together closer than they should be.  If, for example, you switched to a different database, your cookies code would break.

Both solutions get the job done, but I think this last way does it better =)

Anyways, thanks for the points =)

 

by: panosmsPosted on 2009-02-15 at 02:58:20ID: 23644397

Hi js_vaughan
I had to come back because of this.
I checked the last code of you and it is not working.The reason is that after debbuging i found that the clientcookietime and the dbcookietime are not the same.They have 2-3 seconds difference.
For this output:
<cfif isdefined("CheckPerson.CookieTime")>
<cfoutput>#DateFormat(CheckPerson.CookieTime,"yyyy mm dd") & TimeFormat(CheckPerson.CookieTime,"HH:mm:ss")#</cfoutput></cfif><br />
<cfif isdefined("COOKIE.COOKIETIME")>
<cfoutput>#DateFormat(COOKIE.COOKIETIME,"yyyy mm dd") & TimeFormat(COOKIE.COOKIETIME,"HH:mm:ss")#</cfoutput></cfif><br />

i have this output  for example:
2009 02 1512:02:00
2009 02 1512:02:47


so i had to set again the myTimeVar to:
<cfset VARIABLES.myTimeVar="#dateformat(now(),'mmm dd yyyy') & '  ' & timeformat(now(),'h:mmtt')#">

This way i have the output like:
2009 02 1512:46:00
2009 02 1512:46:00

(What happens when i will login f.e at 12:46:59?will the dbcookietime be 12:47:01?)

I had to do something else too.
After autologin i did not get the new lastlogintime!!
So i had to put one new query for this.

The finally code is here.
Please can you check it?:

<cfparam name="VARIABLES.loginPassed" type="boolean" default="FALSE">
<cfset VARIABLES.myTimeVar="#dateformat(now(),'mmm dd yyyy') & '  ' & timeformat(now(),'h:mmtt')#">
<cfif session.allowin EQ TRUE>
 
    <!--- Fake a new login --->
    <cfset CheckPerson = StructNew()>
    <cfset CheckPerson.user_id = session.user_id>    
    <cfset VARIABLES.loginPassed = TRUE>
    
<!--- IF not, lets check for a cookie --->
<cfelseif isDefined("COOKIE.AutoLogIn") AND isDefined("COOKIE.lemail")>
 
    <!--- check cookie against database --->
    <cfquery name="CheckPerson" datasource="carfree24">
        SELECT user_id,Cookietime
        FROM users
        WHERE Email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#COOKIE.lemail#">
    </cfquery>
    <!--- Make sure cookieTime's are in the same format --->
<cfset VARIABLES.DBCookieTime = DateFormat(CheckPerson.CookieTime,"yyyy mm dd") & TimeFormat(CheckPerson.CookieTime,"HH:mm:ss")>
<cfset VARIABLES.ClientCookieTime = DateFormat(COOKIE.COOKIETIME,"yyyy mm dd") & TimeFormat(COOKIE.COOKIETIME,"HH:mm:ss")>
 
    
    <!--- if 1 record is found, we have a valid login --->
<cfif CheckPerson.recordCount EQ 1 AND VARIABLES.DBCookieTime EQ VARIABLES.ClientCookieTime>
 
        <cfset VARIABLES.loginPassed = TRUE>
        
    <!--- if we didnt find 1 record, our cookie is out of sync... remove the autologin, and proceed to login --->
    <cfelse>
        <cfcookie name="AutoLogIn" expires="now">
    </cfif>
        
<!--- Do the following if the form is submitted. --->
<cfelseif IsDefined("Form.lEmail")>
    <cfset VARIABLES.hashedPass = Hash(Form.luserpassword, "SHA")>
    
    <!--- Create our checkboxs if they do not exist --->
    <cfparam name="form.rememberme" default="">
    <cfparam name="form.AutoLogIn" default="">
    
    <!--- query the data base. ---> 
    <cfquery name="CheckPerson" datasource="#request.dsn#">
        SELECT Password, email, user_ID
        FROM users
        WHERE email = <cfqueryparam value="#Form.lemail#" cfsqltype="CF_SQL_VARCHAR">
        AND Password = <cfqueryparam value="#VARIABLES.hashedPass#" cfsqltype="cf_sql_varchar">
    </cfquery>
    
    <!--- User is authorized from the form --->
    <cfif CheckPerson.recordCount EQ 1>
        <cfset VARIABLES.loginPassed = TRUE>
       <!---  <cfset myTimeVar="#now()#"> --->
        
        <!--- Handle cookies in all uppercase --->
        
        <!--- Check if rememberme or AutoLogIn hold positive values --->
        <cfif Form.rememberme EQ 1  OR Form.AutoLogIn EQ 1>
            <CFCOOKIE name="LEMAIL" value="#Form.lemail#" expires="never">
            <CFCOOKIE name="REMEMBERME" value="1" expires="never">
            
            <!--- if AutoLogIn, add login cookies --->
            <cfif Form.AutoLogIn EQ 1>
                <CFCOOKIE name="AUTOLOGIN" value="1" expires="never">
                <CFCOOKIE name="COOKIETIME" value="#myTimeVar#" expires="never">
            <cfelse>
                <CFCOOKIE name="AUTOLOGIN" expires="now">
                <CFCOOKIE name="COOKIETIME" expires="now">
            </cfif>
            
        <!--- Otherwise if user wishes to remain anonymous, remove these client cookies --->
        <cfelse>
            <CFCOOKIE name="LEMAIL" expires="now">
            <CFCOOKIE name="REMEMBERME" expires="now">
            <CFCOOKIE name="AUTOLOGIN" expires="now">
            <CFCOOKIE name="COOKIETIME" expires="now">
        </cfif>
        
        <!--- Handle database updates --->
        
        <cfquery name="setCookietime" datasource="#request.dsn#">
            Update users
            SET <cfif Form.AutoLogIn EQ 1>
            CookieTime = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#">,</cfif>
			LastLogIn = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#">
			WHERE user_Id = <cfqueryparam cfsqltype="cf_sql_integer" value="#CheckPerson.user_Id#">
        </cfquery>
    
    <!--- User failed authorization from the form --->
    <cfelse>
        <cflocation url = "Login.cfm?Error=30" addtoken="no">
    </cfif>
</cfif>
 
<!--- If the user was authorized from any of the above steps, proceed with login --->
<cfif VARIABLES.loginPassed>
    <cfset session.allowin = "True">
    <cfset session.user_id = CheckPerson.user_id>
    <cfquery name="LastLogIn" datasource="#request.dsn#">
            Update users
            SET 
			LastLogIn = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#myTimeVar#">
			WHERE user_Id = <cfqueryparam cfsqltype="cf_sql_integer" value="#CheckPerson.user_Id#">
        </cfquery>
    <cflocation url="welcome.cfm" addtoken="no">
</cfif>
 
 
<form  name="LogIn" action="#CGI.SCRIPT_NAME#" method="post">
<input type = "text" name="lemail"  value="<cfif isdefined("cookie.lemail")><cfoutput>#cookie.lemail#</cfoutput></cfif>"/><br>
<input name="luserpassword" type="password"  value=""/><br>
<input name="rememberme" type="checkbox" value="1"
    <cfif isdefined("cookie.rememberme") AND cookie.rememberme EQ 1> checked="checked" </cfif>/><br>
<input name="AutoLogIn" type="checkbox" value="1"
    <cfif isdefined("cookie.AutoLogIn") AND cookie.AutoLogIn EQ 1> checked="checked" </cfif> /><br>
<input type = "Submit" value = "LogIn"  id="LogIn">
</form>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...