Creating
a user authentication (Login) area.
by
Pablo Varando.
A
lot of users are always asking me how they can create a way on their web site
that is only allowed to be used by registered users. This is called "User
Authentication (Member's Only)" and can be created easily with
ColdFusion.
The
first thing that you must do is to create a table in your database called
"tblAdmins".
Create the following fields in the database table:
| Field
Name |
Type |
| user_id |
AutoNumber |
| user_name |
text |
| user_pass |
text |
This
is where you will have your users login data be default, this will allow you a
"location" to verify against.
You
will need to create and ODBC connection for this database, to create an ODBC
data source, simply open up your ColdFusion administrator (http://127.0.0.1/cfide/administrator/)
or contact your ISP. Call the ODBC "userLogin".
This tutorial
will require 4 pages to be created.
- Application.cfm
- login.cfm
- login_process.cfm
- members_only.cfm
The first
page that will need to be created is titled "Application.cfm".
One thing you must keep in mind with this file, is that it will always be
execute before any ColdFusion (.cfm) file. Think of this as the page where
you can define things and/or check for things. This will always run before
any page, so this is a great place to check to see if a user is logged in.
So naturally, this is the place we're putting the following code on :)
Within this
page you will create the following code:
<!---
Create the application --->
<cfapplication
name="MyApp"
clientmanagement="Yes"
sessionmanagement="Yes"
sessiontimeout="#CreateTimeSpan(0,0,15,0)#"
applicationtimeout="#CreateTimeSpan(0,2,0,0)#">
<!---
Now define that this user is logged out by default --->
<CFPARAM
NAME="session.allowin"
DEFAULT="false">
<!---
Now define this user id to zero by default, this will be used later on to access specific information about this user. --->
<CFPARAM
NAME="session.user_id"
DEFAULT="0">
<!---
Now if the variable "session.allowin" does not equal true, send
user to the login page --->
<!---
the other thing you must check
for is if the page calling this application.cfm is the "login.cfm"
page
and the "Login_process.cfm"
page since the Application.cfm is always called, if this is not checked
the application will simply Loop
over and over. To check that, you do the following call
--->
<cfif session.allowin neq "true">
<cfif
ListLast(CGI.SCRIPT_NAME, "/") EQ "login.cfm">
<cfelseif ListLast(CGI.SCRIPT_NAME, "/") EQ
"login_process.cfm">
<cfelse>
<!--- this
user is not logged in, alert user and redirect to the login.cfm page --->
<script>
alert("You
must login to access this area!");
self.location="login.cfm";
</script>
<!--- Now abort the page --->
<cfabort />
</cfif>
</cfif>
[NOTE: I updated the code above, because a lot of people were having
problems implementing it because they did not understand how CGI.SCRIPT_NAME
works. This will resolve those issues and should work AS IS in all cases -
Pablo]
That is all
you need in the Application.cfm page. I'll explain
the items as best as possible:
The first
thing you created was the "cfapplication". This command creates
the ability to track users, create session variable and much more. This is
needed to keep order within the application. One crucial section of this tag
is the value you specify on "sessiontimeout". This is the time
that that specifies how long the user will be logged as "Loggedin"
before having to re login. This time is only counted if the user does
nothing. If your pages are small and do not require large amounts of
reading, then 15 minutes should be enough time. However, if your pages
contain a lot of text and require lots of reading, then you might have to
increase the time specified. The CreateTimeSpan values are as follows:
#CreateTimeSpan(days,hours,minutes,seconds)#
The next thing you created was a <cfparam>.
What the <cfparam> does is to define a
value for a variable if (and only if) that variable doesn't already exist.
If that variable does exist, it simply does nothing.
The last thing you created was a way to check on all page to make sure that
the user is correctly logged in. It simply checks for a session variable
called "session.allowin". If this
variable has a value of "TRUE" then that user is logged in, if
that variable has a value other than "TRUE" (i.e.
"FALSE") then this user is not logged in, send them to the login
page.
The next step
in this tutorial is the "login.cfm"
page.
This page is
simply HTML, it doesn't really require any Coldfusion code, here is what it
must have:
<form action="login_process.cfm"
method="post">
Username: <input type="text"
name="user_name"
value=""><BR>
Password: <input type="password"
name="user_pass"
value=""><BR>
<input type="submit"
name="login_user"
value="Log In"><BR>
</form>
The
login page, will submit the form to the "login_process.cfm" page.
That page however, is where the magic takes place. I'll create the entire
page, and then come back and explain it.
<!---
Get all records from the database that match this users credentials --->
<cfquery
name="qVerify"
datasource="userLogin">
SELECT
user_id, user_name,
user_pass
FROM
tblAdmins
WHERE user_name
= '#user_name#'
AND
user_pass = '#user_pass#'
</cfquery>
<cfif
qVerify.RecordCount>
<!--- This user has
logged in correctly, change the value of the session.allowin value --->
<cfset session.allowin = "True">
<cfset session.user_id = qVerify.user_id>
<!--- Now welcome user
and redirect to "members_only.cfm" --->
<script>
alert("Welcome
user, you have been successfully logged in!");
self.location="/members_only.cfm";
</script>
< cfelse>
<!--- this user did not
log in correctly, alert and redirect to the login page --->
<script>
alert("Your
credentials could not be verified, please try again!!!");
self.location="Javascript:history.go(-1)";
</script>
</cfif>
That is all
that I needed on this page. What you're basically doing is as follows:
First you are making a connection to the database with the username/password
the user typed in on the "login.cfm"
page. You are making a call to the database to look in the "tblAdmins"
table for a user with this combination of username/password. if a match is
found, then you have a record, if no matches are found, then there are no
records.
The next step is to do a <cfif> to see if
any records were found. If a record was found, then this user is good, go
ahead and log them in. if there are no matches, then this user is no good,
keep him out of the members only section.
if the user
was good, then you overwrite the existing value of the "session.allowin"
variable to "TRUE". Remember that the "Application.cfm"
is checking for this value to be anything other than true to make the user
log in. Since this now has a value of "TRUE" the user is logged in
and therefore, does not need to login once again.
The last page
you must create is the "members_only.cfm". This can be anything
you want, this is the content that the user is logging in for, so make it
good :)
That's it,
you now know how to make a user authentication system!
Remember that if you have any questions or problems with this tutorial, you
can always contact me directly.
Log out?
Could you add a logout to this? I've figured out a method to do it already but I thought others might like to have the ability as well.. Also the other tutorial for Remembering user and this would be a great merge so we (the pathetic un-coded) can have one shop in sted of hacking together two seperate chunks.
Great Tut Though Thanks very much..
Posted by: Ed Wolf
Posted on: 04/12/2004 06:18 PM
|
Logout Reply
To logout, simply create a page called "logout.cfm" and in that page do this:
<cfscript> StructClear(session); </cfscript> <cflocation url="login.cfm">
Thats it! You now have a logout mechanism on your site! :)
Posted by: Pablo Varando
Posted on: 04/14/2004 10:23 AM
|
Registration?
Hi, How would i make a registration page using CF ? i can do it in ASP but my server dont support it so ive got to use CF to do it Cheers any response
Posted by: Dan P
Posted on: 04/17/2004 10:58 AM
|
How detect IP user ?
Dear all,
how to write script for detect last IP or Last Login client in login.cfm
Posted by: davematt
Posted on: 04/18/2004 05:07 AM
|
error on " Creating a user authentication (Login) area"
Hi, I used the code but found the page just gives me a error page once the name and password match those on the database.
Error Occurred While Processing Request Error Diagnostic Information
An error occurred while evaluating the expression:
session.allowin = "True"
Error near line 11, column 11. --------------------------------------------------------------------------------
Attempt to access a Session variable when session management is not enabled. Use the CFAPPLICATION tag to enable session management.
Note: This feature may have been disabled by the site administrator.
The error occurred while processing an element with a general identifier of (CFSET), occupying document position (11:5) to (11:36).
Date/Time: 05/31/04 00:29:05 Browser: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Remote Address: 127.0.0.1 HTTP Referrer: http://localhost/login/login.cfm
Posted by: Ringo
Posted on: 05/30/2004 12:06 PM
|
Ringo....
You need to enable to Application in your Application.cfm page..
<!--- Create the application ---> <cfapplication name="MyApp" clientmanagement="Yes" sessionmanagement="Yes" sessiontimeout="#CreateTimeSpan(0,0,15,0)#" applicationtimeout="#CreateTimeSpan(0,2,0,0)#">
If you need further help, please start a thread on the <a href="http://www.easycfm.com/forums/">forums</a>
Posted by: Pablo Varando
Posted on: 05/31/2004 01:25 PM
|
auth page
hi,
how to prevent somebody directly type the member_only.cfm page?
Posted by: hymns
Posted on: 06/17/2004 09:58 PM
|
Re: auth page
That is what the Application.cfm page does. if the user is NOT logged in, then the member_only.cfm page will not load and the user will be redirected to log in. Please follow the tutorial for more details.
Posted by: Pablo Varando
Posted on: 06/17/2004 11:19 PM
|
SessionTimeOut
Does anybody know how to code an error message after timeout is expired on the application.cfm
Currently, under my application.cfm I have set the cfapplication tag to include the sessiontimeout variable.
<cfapplication name="EV_Application" sessionmanagement="yes" sessiontimeout="#CreateTimeSpan(0, 0, 20, 0)#">
Thanks, Samantha
Posted by: Samantha
Posted on: 06/22/2004 01:56 PM
|
WOW
That was a great tutorial. I am creating a text based game and was wondering how you would suggest creating the members only page. Like, having another table and using the cfquery/output or just adding on to the current table, but i would image that would get to be quite a large table. :-p
Posted by: Mysti
Posted on: 06/23/2004 02:18 PM
|
Want to send the user to a different page?
If you have a need of differentiating users that log in (like an end-user or an administrator) pease read this forum thread:
http://www.easycfm.com/forums/viewmessages.cfm?Forum=12&Topic=4264
Posted by: Pablo Varando
Posted on: 07/03/2004 11:02 PM
|
How to Place Ad
I have a problem of placing Advertisement on my main page.Any other can place Ad and I can Put a Count button on how many time it has been clicked, Tell me Soon.
Regards..
Posted by: Gavy
Posted on: 08/04/2004 11:21 PM
|
please help
Thanx for the script; i have been working on it but came up with errors when i tried to run the process_login.cfm it came up with the follwoing errors:
Variable USERNAME is undefined. The Error Occurred in C:\CFusionMX\wwwroot\login_process.cfm: line 5 3 : SELECT Username, Password 4 : FROM tblStudents 5 : WHERE Username = '#Username#' 6 : AND Password = '#Password#' 7 : </cfquery>
I have just the basic: Username and Password fields
Posted by: Nsabasi
Posted on: 08/06/2004 04:31 PM
|
Check your form
your form's text/password objects should have the same name as what's being using in the above script... also note that some backends have "password" as a reserved word and cannot be used as a variable.. i had this issue with Coldfusion.
Posted by: Izzy
Posted on: 08/12/2004 10:12 AM
|
Doh!!!!
Thanks Izzy, i changed my form name and it worked. Sometimes you one doesn't check these minor issues b4 asking questions
Posted by: Nsabasi
Posted on: 08/13/2004 11:19 AM
|
multiple logins
Hello I am currently using this login authentication as a testing in our application. But can anybody help me how can i prevent the same username or same user to login into the application from different browser or diff machine. I want to prevent the same username to get logged in from different place when the username is already loggedin and i want to give the msg as this username is already loogedin or in use, please try a different username. hope you got what i mean thanks and regards Tan
Posted by: tan
Posted on: 08/17/2004 04:57 AM
|
Little Error
</script> < cfelse> <!--- this user did not log in correctly, alert and redirect to the login page ---> <script> Hi, im sure most of you have found this but there is an error where cfelse is spaced before writing. Get rid of the space just in case
Posted by: daniel
Posted on: 09/01/2004 09:01 AM
|
Great Tutorial
Hi
Got the login working great and the logout addon as well. Can you explain how the sessiontimeout works. I changed mine to 20 sec to see what happens but after about 2minutes I could still happy onen the members_only page
Posted by: Todd
Posted on: 09/19/2004 05:26 AM
|
I get an endless loop...?
I placed the login in a directory with its own Application.cfm and if i try to go to any page in the directory it gives the message box that i need to login and i click OK and it goes to the login page and shows nothing, but it gives the same message box, over and over and over and over again.
The Application.cfm, login.cfm, login_process.cfm, members_only.cfm are all in the Admin directory.
Posted by: Stick
Posted on: 10/11/2004 08:49 PM
|
problems with logout
Hi all, I'm having problem implementing the logout function. i haved used <cfscript> StructClear(session); </cfscript> <cflocation url="login.cfm">
It bring me to the "login.cfm", but when I click the "back" button I can still view the pages that i have accessed while i was loggedIn.
Also, i haved two type of users, Admin and Guess. Which I used session to defined who has loggedIN and what pages are accessible to them. The problem is that when a Admin loggedIN, then loggedOUt. Guess login, it can view the pages that was onlymeant for Admin.cfm, look like the session has not yet clear..
can anyone gives me some ideas..thanks a miliions.. Michael.
Posted by: Michael
Posted on: 10/26/2004 01:47 AM
|
Reply about IP logging
Hi, If you wanted to track IP's all you need to use is the variable #REMOTE_ADDR# So when they login in the database set the value of last login ip as #REMOTE_ADDR#. Simple as that
Posted by: Daniel
Posted on: 11/19/2004 04:42 PM
|
logout.cfm how?
As a newb, i have no idea how to even approach this?
Any tips?
Posted by: Tristan
Posted on: 11/26/2004 02:47 PM
|
i'm getting an error
An error occurred while evaluating the expression:
qVerify.RecordCount
Error near line 8, column 6.
any ideas?
Posted by: matt
Posted on: 12/04/2004 12:14 PM
|
Two sections of site - one protected one public
Is there any way to have a certain section of the site available without login while still protecting others.
I am currently using Application.cfm at site root for centralisation of config data (datasourse etc) but I want to have a certain pages only requiring a login.
Is is possible to have two Application.cfm pages - one at site root and one in sub directory housing protected pages?
Would application variables from the file at site root be available to pages in sub directory?
Thanks Matt
Posted by: Matt
Posted on: 12/07/2004 05:42 AM
|
cannot display login_process.cfm
i get the following error after i submit the form from login.cfm to login_process.cfm.
The page cannot be displayed There is a problem with the page you are trying to reach and it cannot be displayed.
plz somebody help me out thx
Posted by: manoj
Posted on: 12/17/2004 10:13 PM
|
Application.cfm
when i remove the application.cfm, the login was able to work.. i copy and paste the entire coding from the tutorial pls help me..
----------------------------------------------------------- Attempt to access a Session variable when session management is not enabled. Use the CFAPPLICATION tag to enable session management.
Note: This feature may have been disabled by the site administrator.
The error occurred while processing an element with a general identifier of (CFPARAM), occupying document position (10:1) to (10:48).
Posted by: Wayne
Posted on: 01/22/2005 05:37 AM
|
Problem authentication
It's articl is Great but i have some problem some body type directly member_area.cfm and he can access memberes area and he can see all information but he can't update any information when he click the any link or button than alret box is appear "u must login access this area! " but i want he can't see this information .
Posted by: Babar
Posted on: 01/24/2005 01:47 AM
|
Could be better...
This site offers some good tutorials. However, and I'm not here to diss anyone, but the English could be better in this guys' tutorials (you'll see what I'm talking about in his other tutorials). Also, let's face it, most of the users here are amateur coders (like me) and we need our "hands held" as we walk through the code, even the advanced tutorials. Given that us newbies/amateures are the "bread -n- butter" of this and most other programming tutorial sites, you'd think they'd include everything in the "full applications". In other words, just put all the damn freakin' code in these full apps. You'll still get plenty of hits on your site. Oh yeah, much of this site's tutorials are full of errors and while everyone makes mistakes, us visitors are amateurs while many of the people submitting tutorials are claiming to be pros. Hmmm! You'd think they'd catch more of their own mistakes.
Posted by: Miles O'Toole
Posted on: 03/21/2005 06:51 AM
|
What?
For a newbie you sure complain alot. RTFM this site isn't here for cut n' paste websites.
Posted by: CF
Posted on: 03/23/2005 11:39 PM
|
Oh Yeah...
EasyCFM...keep up the good work!
Posted by: CF
Posted on: 03/23/2005 11:40 PM
|
Members & admin module
I this tutorial how do I clearly make adifference b/w members and admin, and not to use admin storing passwords in the database
Please Help me and tell how to use hash() Function to encrypt passwords.
Posted by: Gavy
Posted on: 04/07/2005 11:26 AM
|
close browser...end session?
Is there a way to make it so when someone closes the browser, it automatically ends the session (or logs them out)?
Posted by: JR
Posted on: 04/09/2005 02:21 AM
|
close browser...end session?
There is something on this here:
http://www.easycfm.com/blog/index.cfm?commentID=230
Posted by: Pablo Varando
Posted on: 06/20/2005 09:21 PM
|
members_only.cfm
This code looks great and I plan to implement it in my DB. However I already have a large website/database established and I want to lay this over top of it as a secure/login/logout.
How can I set it to redirect back to application.cfm if a user goes to ANY of the files in my directory not only the ones included in this tutorial ?( for example my DBquery page and my DBaddrecord page ?) Thanks
Posted by: JohnyBoy
Posted on: 07/07/2005 08:37 AM
|
Concerning Two sections of site - one protected one public
This seems to be just what I am looking for, although I have not tried it yet. But I also need to have two separate sections to my website. Are there any pointers you can give me or point me to, on how to accomplish this?
Posted by: Mike
Posted on: 07/07/2005 04:59 PM
|
Members_only.cfm
Hi How members_only.cfm works. Also what should I have to write in it. Thanks -----Manan
Posted by: Manan
Posted on: 11/09/2005 02:40 PM
|
control content based on credentials
Is it possible to change the content of a site based on the users credendials? I am not looking to authenticate a seperate area, just what the user who is logged in (or not) can see. I would also like to implement several several sequrity tiers: guest, user, poweruser, or admin. Kinda like cf_nuke but a little less rubbish and more dynamic. If anyone can point me to a tutorial or open source system that would be great. I work for a non-profit so cost is very importaint.
Thanks!
Posted by: George
Posted on: 01/26/2006 08:44 PM
|
CFPOP Error
When I log into my admin section I am able to see that I am logged in, but at the bottom of the admin page I receive the following error?
Error Diagnostic Information Connection Failure
The error occurred while processing an element with a general identifier of (CFPOP), occupying document position (1:1) to (5:32).
Date/Time: 03/16/06 11:33:39 Browser: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) Remote Address: 10.1.3.3
Posted by: Allan
Posted on: 03/16/2006 11:35 AM
|
HELP DATABASE
hi well i have always done html website, never dinamic. anyway that is what i have and what i need to do with my website... ok i need to be able to have a registration page, where new members can register, and a log in page where after register they can download pdf documents... i have a website done with dreamwear in Html, now i am creating a database that will aquire my members info, name, lastname, userid (as primary key), password, address, phone number, email, date of birth and i think is all they need. after i do that how i can create the form to add date on the database?? please
Posted by: dario
Posted on: 03/28/2006 08:12 PM
|
Problem with login
Hello
I followed the tutorial, which by hte way is great. But when I login I get the message of successfull login and when the members_only page loads I get the message to login to see the information and redirects me to the login page.
I have checked the code and I do not see anything different, can anyone help?
Posted by: Richard
Posted on: 05/30/2006 05:42 PM
|
Member_page.cfm
is there spcieal code that needs to be included in the member.cfm page so that it requireds the user to login, or can they skip the whole login proccess if they know the url?
Posted by: Jason
Posted on: 06/20/2006 10:50 AM
|
PDF tutorial
i need pdf tutorial foeHTML
Posted by: Nuwan Chathuranga
Posted on: 07/30/2006 02:56 AM
|
Excellent Article
I don't understand what 99% of you are talking about. The author of this article did a wonderful job of breaking it down so every piece is easy to understand. If you are having real trouble it's because you are not reading. I tried out this code and it worked perfectly. Feel free to contact me if there are things u do not understand
Posted by: Downpour
Posted on: 10/25/2006 03:53 AM
|
What about md5?
What about hashes? On the way this is working the server admin can look at all the passwords if he likes. At least in the Netherlands thats even illigal!
Posted by: Jim
Posted on: 11/30/2006 04:46 AM
|
re: What about md5?
Jim,
Encryption of a password is suggested in most cases; however not necessarily required or illegal.
It depends on what type of service/system you have in place. If you are a bank then yes it is a required step to ensure financial records; however if your applicaiton is a simple admin area for your site or something like that the encryption is NOT required or necessary for legality.
Truth be told; this is a beginners/intermediate tutorial to show you how to do it... It is not (as none of the tutorials on this site) meant to be a final working copy that you can use in all instances and all applications. Tutorials as just that; tutorials. Use them to learn from and then do your own thing...
Posted by: Pablo Varando
Posted on: 11/30/2006 12:31 PM
|
Need Hel[p for Writing a Code for checking Type of User Logged In
I am a Newbie to ColdFusion.I am now asked to write a Program to check the User Authentication Based on the Value entered on the User ID on the Login Page.
If the First Letter of the User ID is a Number then it has to Perform a Set of Function or else if the first Letter is a Character then it has to perdorm another set of Function.
How to write a Program to Check whether the First Character of the User ID is a Character or Number.
Help of any sort ASAP is Greatly Thankful.
Thanks in Advance.
With Regards, Bala.
Posted by: N.V.Balasubramaniam
Posted on: 01/25/2007 04:48 AM
|
User Online/Offline
Hi,
I've implemented this tutorial and it works great though I've made some changes to it to suit my app. Please please somebody help me on this!!! I have a flag in my DB to set user online or offline. Basically when a user logges in I set it to 1(online) and when user logges out I set it back to 0(offline). It's all great but can't set it if the session times out. The DB is still showing 1(online) even thought the session ended so user should be offline. Is there a way of executing an update query on session timeout? Or any other suggestions? Please please help!!! Thanks
Posted by: Akos
Posted on: 04/26/2007 09:01 AM
|
Thx.
Thanks for this tutorial, it worked for me.
Posted by: JP
Posted on: 05/11/2007 02:42 PM
|
How to secure the members_only.cfm page
How would I secrue the member_only.cfm page? doesn't there need to be coldfusion code on that page so that when someone types in the address ie. www.galaxy.com/members_only.cfm it goes to the log in page? Sorry if this is answered somewhere but I read through this a couple times and couldn't find it. If you would email me any help that would be much appreciated! Thanks in advance.
Posted by: Ali
Posted on: 06/18/2007 05:09 AM
|
this will secure your members only page
Just an fyi. To secure the members only page, you need to include the Application.cfm on that page like this: Copy and paste this at the top. <cfinclude template="Application.cfm">
BTW -Thanks for the great tutorial. Just what I needed!
Posted by: mike
Posted on: 08/25/2007 10:06 PM
|
Using a static instead of a database
How can I change this section here:
<cfquery name="qVerify" datasource="userLogin"> SELECT user_id, user_name, user_pass FROM tblAdmins WHERE user_name = '#user_name#' AND user_pass = '#user_pass#' </cfquery>
...from checking a database to using only a static user ID and password? I know the concept is easy but it is evading me at this time. PLEASE HELP!!!
Posted by: D Williams
Posted on: 09/18/2007 11:50 AM
|
MULTIPLE USER
cant dis be used 4 multiple users login...so dat wen they login..each user gets his own profile page with his own information(fetched frm d database)...i guess here thrs smthin 2 do wid tokens...m really confused plz can sm1 help me out...
Posted by: kartik
Posted on: 10/13/2007 06:54 AM
|
login scripts for domain when user logged in and loggedout
all clients are connected to domain i want login scripts when clients are logged in and logged out from domain pc
Posted by: dkm
Posted on: 12/18/2007 07:11 AM
|
THanks
Thanks for this and other tutorials. We used them and they are greatness!!!
Jerritt
Posted by: Jerritt Pace
Posted on: 03/26/2008 01:04 AM
|
FLASH
hi,
i am building a web site in flash, where members can log in to their profile pages which will be coded with coldfusion. how can i adopt the code in this tutorial for my web site. to log in user selects login.swf, which uses login.ASP for logging in!
Posted by: rafal
Posted on: 04/08/2008 10:37 PM
|