Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1041
  • Last Modified:

Using cookies for a login function

This case that I'm working involves making a login page for an online shop which remembers a user through the use of cookies.  After logging in, the valUser() function validates the login and creates two cookies that remember the user.  If the user has already provided login information the deterUser() function determines this and does not display the login section but displays an 'enter' button in its stead.  I'm having trouble debugging my javascript functions for the file; the script is below.  If you need any more clarification or additional code please let me know.
/*	
	New Perspectives on JavaScript
	Tutorial 9
	Tutorial Case 3
	
	Mollie's Barn Boutique
 
	
	Filename:		mollietxt.js
    Supporting Files:	mollietxt.htm, molie_prodtxt.htm
	
	Function List:
	findCookie()
		Used to extract the value of a cookie based on the name of the
		cookie.
	deterUser()
		Determines if the user has already provided log in information. If
		so, then the login window is not visible; instead, the
		"Enter" button is visible.
	valUser()
		It validates user log in data and then creates two cookies.
*/
 
function findCookie(val){
	   var cookie = null;
	   var findVal = val + "=";
	   var dc = document.cookie;
       if (dc.length > 0)
	{
          var start = dc.indexOf(findVal);
          if (start >= 0)
		{
             		start += findVal.length;
             		lastVal = dc.indexOf(";", start);
             		if (lastVal == -1)
				{
                			lastVal = dc.length;
			 	}
             		cookie = (dc.substring(start, lastVal));
          	}
	  else
	  	{
			return cookie;
	  	}
       	}
       return cookie;
}
 
 
var u 
document.cookie = u
 
var p
document.cookie = p
 
 
function deterUser() {
if (u != null && p != null) {
objectl = parent.document.getElementById("login");
   objectl.style.visibility="hidden";
objectf = parent.document.getElementById("first");
   objectf.style.visibility="hidden";
objectb = parent.document.getElementById("button");
   objectb.style.visibility="visible";
}
}
 
function valUser() {
if ((u != null) && (p != null)) { window.location ="mollie_prod.htm" };
objectu = parent.enter.document.getElementById("user");
var user = objectu;
objectp = parent.enter.document.getElementById("pwd");
var pwd = objectp;
if (user == "" && pwd == "") { return false );
else ( 
var today = new Date();
var expdate = today + 90;
document.cookie = "u = user; expires = expdate";
document.cookie = "p = pwd; expires = expdate";);
}
}
 
 
Filename:		mollie.htm
   Supporting files:	mollie_prod.htm, mollie.js, mollie.css,
   			mollie_1.jpg, mollie_bb.jpg
 
-->
 
<script language="JavaScript" src="mollie.js" ></script>
<link rel="stylesheet" type="text/css" href="mollie.css" />
<title>Mollie's Boutique</title>
</head>
<body onLoad="deterUser()">
 
<div align="center">
<img src="mollie_bb.jpg" />
<br />
 
<div id="login">
<form name="enter" action="#"  onSubmit="return valUser()" method="post">
Please Log In:
<table>
	<tr>
		<td class="login">Username:</td>
	</tr>
	<tr>
		<td class="login"><input name="user" size="8" /></td>
	</tr>
	<tr>
		<td class="login">Password:</td>
	</tr>
	<tr>
		<td class="login"><input name="pwd" type="password" size="8" /></td>
	</tr>
	<tr>
		<td class="login">Confirm Password:</td>
	</tr>
	<tr>
		<td class="login"><input name="pwd2" type="password" size="8" /></td>
	</tr>
	<tr>
		<td class="login"><input type="submit" value="Log-In" /></td>
	</tr>
</table>
</div>
 
<img src="mollie_1.jpg" border="0" /><br />
<div id="intro_text">
Looking for that special novelty?<br>
Come on in and see what's waiting inside!
<br />
<div id="first">
To enter, complete the form above and then click on the Log-In button.
</div> 
<input type="submit" id="button" value="Enter Here" />
</form>
 
</div>
</div>
 
</body>
</html>

Open in new window

0
inisrael
Asked:
inisrael
  • 10
  • 6
  • 2
5 Solutions
 
HonorGodCommented:
What are these statements supposed to be doing?

When you declare a variable (e.g., u) and don't specify a value, the value is "undefined" (not a string, just an undefined value).

So each of these assignments to document.cookie wipes out any pre-existing value.
var u 
document.cookie = u
 
var p
document.cookie = p

Open in new window

0
 
HonorGodCommented:
In your deterUser function, do you realize that undefined does not equal null?

So if u is undefined, and p is undefined, then the "then" clause for this statement will be executed...

if (u != null && p != null) {
 ...
0
 
HonorGodCommented:
btw, don't you mean "detectUser"?  "deterUser" has totally different implications... :-)
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
HonorGodCommented:
How do "u" and "p" ever get assigned?

And, don't include blanks around the equal sign in the cookie text.

Your indentation fluctuates from too much (findCookie) to too little (valUser).
Pick a nice readable indentation value (e.g., 2 spaces - I refuse to use tabs), and stick with it.

Which do you find more readable?  This?



//--------------------------------------------------
// No indentation
//--------------------------------------------------
function valUser() {
if ((u != null) && (p != null)) { window.location ="mollie_prod.htm" };
objectu = parent.enter.document.getElementById("user");
var user = objectu;
objectp = parent.enter.document.getElementById("pwd");
var pwd = objectp;
if (user == "" && pwd == "") { return false );
else ( 
var today = new Date();
var expdate = today + 90;
document.cookie = "u = user; expires = expdate";
document.cookie = "p = pwd; expires = expdate";);
}
}
 
//--------------------------------------------------
// Indentation using 2 spaces
//--------------------------------------------------
function valUser() {
  if ((u != null) && (p != null)) {
    window.location ="mollie_prod.htm"
  };
  objectu = parent.enter.document.getElementById("user");
  var user = objectu;
  objectp = parent.enter.document.getElementById("pwd");
  var pwd = objectp;
  if (user == "" && pwd == "") {
    return false
  );                  // <-- close parenthesis & semi-colon are wrong
    else (            // <-- open parenthesis is wrong
      var today = new Date();
      var expdate = today + 90;
      document.cookie = "u = user; expires = expdate";
      document.cookie = "p = pwd; expires = expdate";
    );                // <-- close parenthesis is wrong
}                     // What is this closing curly brace for?
}

Open in new window

0
 
HonorGodCommented:
Does this help?
0
 
inisraelAuthor Commented:
Yeah!  I thought that about the deter user function too.  I definitely didn't come up with the name, but I changed it anyway.

The curly brace was supposed to be for the end of the commands from the If statement.  I changed the syntax there.  

Also, I am trying to make the u and p variables equal to the value of cookies by the same name.  I included an explanation of a few things within the code that I am attaching below.  I changed how I was treating those variables but I'm not sure on how to get the variables equal to just the value of the cookies of the same name.  (I'm not sure if what I changed it to will work).  
/*	
	New Perspectives on JavaScript
	Tutorial 9
	Tutorial Case 3
	
	Mollie's Barn Boutique
 
	
	Filename:		mollietxt.js
    Supporting Files:	mollietxt.htm, molie_prodtxt.htm
	
	Function List:
	findCookie()
		Used to extract the value of a cookie based on the name of the
		cookie.
	detectUser()
		Determines if the user has already provided log in information. If
		so, then the login window is not visible; instead, the
		"Enter" button is visible.
	valUser()
		It validates user log in data and then creates two cookies.
*/
 
function findCookie(val){
	   var cookie = null;
	   var findVal = val + "=";
	   var dc = document.cookie;
       if (dc.length > 0)
	{
          var start = dc.indexOf(findVal);
          if (start >= 0)
		{
             		start += findVal.length;
             		lastVal = dc.indexOf(";", start);
             		if (lastVal == -1)
				{
                			lastVal = dc.length;
			 	}
             		cookie = (dc.substring(start, lastVal));
          	}
	  else
	  	{
			return cookie;
	  	}
       	}
       return cookie;
}
 
 
/* create a variable named "u" and assign it the value of the cookie by the same name.  Create a second variable named "p" and assign it the value of the cookie by the same name. */
var u = document.cookie = "u=u"
var p = document.cookie = "p=p"
 
/* use and if statement to check if teh variables "u" and "p" are both equal to null.  If so, then set the visibility of the objects with the ids "login" and "first" to "hidden". I addition, set the visibility of the object with the id "button" to "visible" */
 
 
function detectUser() {
if ((u != null) && (p != null)) {
objectl = parent.document.getElementById("login");
   objectl.style.visibility="hidden";
objectf = parent.document.getElementById("first");
   objectf.style.visibility="hidden";
objectb = parent.document.getElementById("button");
   objectb.style.visibility="visible";};
}
 
/* check if "u" and"p" = null, if so then redirect users to a page named mollie_prod.htm  From the form with id "enter", pass the value of the "user" field to a variable of the same name; do the same for the "pwd" field.
 
Use an If statement to check if the variables "user" and "pwd" are both empty, if so then the function should return false; otherwise create a variable named "today" containing the current date and avariable named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "u" with value equal to the value of the "user" variable and an expiration date equal to the variable "expdate"  In addition, it should create a cookie named "p" with a value equal to the value of the "pwd" variable and an expiration date equal to the variable "expdate".    */
 
function valUser() {
if ((u != null) && (p != null)) { window.location ="mollie_prod.htm" };
var user = parent.enter.document.getElementById("user");
var pwd = parent.enter.document.getElementById("pwd");
if ((user == "") && (pwd == "")) { return false };
else { 
var today = new Date();
var expdate = today + 90;
document.cookie = "u=user; expires=expdate";
document.cookie = "p=pwd; expires=expdate";};
}

Open in new window

0
 
inisraelAuthor Commented:
Looking at it again, I should probably be using the findCookie(val) function to set up the values of the "u" and "p" variables.

var u = findCookie(u)
var p = findCookie(p)

Does that make sense?
0
 
HonorGodCommented:
Remember though, what kind of value needs to be passed to findCookie?

What kind of value are you using?
0
 
inisraelAuthor Commented:
So, you're saying that I need to specify that the u and p being sent to the findCookie() function are the cookies u and p rather than the variables?  As in:
var u = findCookie("u");
var p = findCookie("p");
This is what I'm getting suggested to me from my text.  Below is an updated file with some corrected syntax.
/*	
	New Perspectives on JavaScript
	Tutorial 9
	Tutorial Case 3
	
	Mollie's Barn Boutique
 
	
	Filename:		mollietxt.js
    Supporting Files:	mollietxt.htm, molie_prodtxt.htm
	
	Function List:
	findCookie()
		Used to extract the value of a cookie based on the name of the
		cookie.
	detectUser()
		Determines if the user has already provided log in information. If
		so, then the login window is not visible; instead, the
		"Enter" button is visible.
	valUser()
		It validates user log in data and then creates two cookies.
*/
 
function findCookie(val){
	   var cookie = null;
	   var findVal = val + "=";
	   var dc = document.cookie;
       if (dc.length > 0)
	{
          var start = dc.indexOf(findVal);
          if (start >= 0)
		{
             		start += findVal.length;
             		lastVal = dc.indexOf(";", start);
             		if (lastVal == -1)
				{
                			lastVal = dc.length;
			 	}
             		cookie = (dc.substring(start, lastVal));
          	}
	  else
	  	{
			return cookie;
	  	}
       	}
       return cookie;
}
 
 
/* create a variable named "u" and assign it the value of the cookie by the same name.  Create a second variable named "p" and assign it the value of the cookie by the same name. */
 
 
var u = findCookie("u");
var p = findCookie("p");
 
 
/* use and if statement to check if teh variables "u" and "p" are both equal to null.  If so, then set the visibility of the objects with the ids "login" and "first" to "hidden". I addition, set the visibility of the object with the id "button" to "visible" */
 
 
function detectUser() {
if ((u !== null) && (p !== null)) {
  objectl = parent.document.getElementById("login");
   objectl.style.visibility="hidden";
  objectf = parent.document.getElementById("first");
   objectf.style.visibility="hidden";
  objectb = parent.document.getElementById("button");
   objectb.style.visibility="visible";}
}
 
 
/* check if "u" and"p" = null, if so then redirect users to a page named mollie_prod.htm  From the form with id "enter", pass the value of the "user" field to a variable of the same name; do the same for the "pwd" field.
 
Use an If statement to check if the variables "user" and "pwd" are both empty, if so then the function should return false; otherwise create a variable named "today" containing the current date and avariable named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "u" with value equal to the value of the "user" variable and an expiration date equal to the variable "expdate"  In addition, it should create a cookie named "p" with a value equal to the value of the "pwd" variable and an expiration date equal to the variable "expdate".    */
 
 
function valUser() {
if ((u !== null) && (p !== null)) {
  window.location ="mollie_prod.htm";}
var user = parent.enter.document.getElementById("user");
var pwd = parent.enter.document.getElementById("pwd");
if ((user === "") && (pwd === "")) {
  return false;}
    else { 
      var today = new Date();
      var expdate = today + 90;
      document.cookie = "u=user; expires=expdate";
      document.cookie = "p=pwd; expires=expdate";}
}

Open in new window

0
 
HonorGodCommented:
no, I'm saying that if we look at the function definition, we can find how the parameter is being used.

In this specific case, the expected parameter is actually the name of the cookie whose value you are trying to retrieve.

So, what you really want is:

var u = findCookie( 'u' )

in order to have the routine return any existing cookie having the name 'u'.
Does that make sense?
0
 
inisraelAuthor Commented:
That makes perfect sense to me.  I've working on trying to suss out this coordination between the javascript function and the html page and haven't had much luck.  I've been working on it for a while and I'm going to paste the new javascript below.  Let me know what you think.  
function findCookie(val){
	   var cookie = null;
	   var findVal = val + "=";
	   var dc = document.cookie;
       if (dc.length > 0)
	{
          var start = dc.indexOf(findVal);
          if (start >= 0)
		{
             		start += findVal.length;
             		lastVal = dc.indexOf(";", start);
             		if (lastVal == -1)
				{
                			lastVal = dc.length;
			 	}
             		cookie = (dc.substring(start, lastVal));
          	}
	  else
	  	{
			return cookie;
	  	}
       	}
       return cookie;
}
 
 
/* create a variable named "u" and assign it the value of the cookie by the same name.  Create a second variable named "p" and assign it the value of the cookie by the same name. */
 
 
var u = findCookie( 'u' );
var p = findCookie( 'p' );
 
 
/* use and if statement to check if teh variables "u" and "p" are both equal to null.  If so, then set the visibility of the objects with the ids "login" and "first" to "hidden". I addition, set the visibility of the object with the id "button" to "visible" */
 
 
function deterUser() {
if ((u !== null) && (p !== null)) {
  objectl = parent.document.getElementById("login");
   objectl.style.visibility="hidden";
  objectf = parent.document.getElementById("first");
   objectf.style.visibility="hidden";
  objectb = parent.document.getElementById("button");
   objectb.style.visibility="visible";}
}
 
/* check if "u" and"p" = null, if so then redirect users to a page named mollie_prod.htm  From the form with id "enter", pass the value of the "user" field to a variable of the same name; do the same for the "pwd" field.
 
Use an If statement to check if the variables "user" and "pwd" are both empty, if so then the function should return false; otherwise create a variable named "today" containing the current date and avariable named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "expdate" equal to teh current date plus ninety days.  It should also create a cookie named "u" with value equal to the value of the "user" variable and an expiration date equal to the variable "expdate"  In addition, it should create a cookie named "p" with a value equal to the value of the "pwd" variable and an expiration date equal to the variable "expdate".    */
 
 
function valUser() {
if ((u !== null) && (p !== null)) {
  window.location ="mollie_prod.htm";}
var user = document.getElementsByName("user").item(0).value;
var pwd = document.getElementsByName("pwd").item(0).value;
if ((user === "") && (pwd === "")) {alert('empty');
  return false;}
    else { alert('not empty');
      var expdate = new Date();
      expdate.setDate(expdate.getDate()+90);
      document.cookie = "u="+user+"; expires="+expdate.toGMTString();
      document.cookie = "p="+pwd+"; expires="+expdate.toGMTString();
}

Open in new window

0
 
HonorGodCommented:
Here is a decent tutorial about using cookies with JavaScript.

http://blazonry.com/javascript/cookies.php

The code that you have is similar in places, but your code has some problems.

For example, in your valUser() function, you kind of have some code to create a cookie, but it has a number of problems.  Specifics:

The expiration value are wrong.

You can use this statement to obtain the current date & time in a date object named "today":

var today = new Date()

However, you can't add 90 days using the syntax that you have:

var expdate = today + 90

The code on "Part 2" of that tutorial shows one (of many) ways to do it...

You aren't specifying the variable values for "user" and "pwd", you are using those actual strings.  So, the only user you have defined has a value of "user"
Then, you overwrite the user value with the "password" value, which happens to be a constant value of "pwd"...

So, as I said you have some problems.
0
 
inisraelAuthor Commented:
Everybody's got problems.  

      var expdate = new Date();
      expdate.setDate(expdate.getDate()+90);


Is the new code.  As I said, take a look.
0
 
inisraelAuthor Commented:
Ok I've got it figured out.  It's up and running now.  Many thanks.
0
 
HonorGodCommented:
ok, let's take a close look at the code, one function at a time.
----------------------------------------------------------------------
function findCookie(val){                                // 1 parameter/argument
         var cookie = null;                                 // default value/result
         var findVal = val + "=";                        // val is really a cookie "name"
         var dc = document.cookie;                  // dc is an alias for ...
       if (dc.length > 0)                                     // Do any cookies exist?
      {
          var start = dc.indexOf(findVal);           // index of name=
          if (start >= 0)                                      // does it exist in the string?
            {                                                   //   if so
                         start += findVal.length;        //   start == starting index of value
                         lastVal = dc.indexOf(";", start);  // a better name would be stop
                         if (lastVal == -1)                   // if no ';' exists, use the end of string
                        {
                                  lastVal = dc.length;
                         }
                         cookie = (dc.substring(start, lastVal));  // extract cookie value
                }
        else
              {
                  return cookie;
              }
             }
       return cookie;
}
----------------------------------------------------------------------
  Using an indentation of 2, instead 8, and "stop" instead of "lastVal), we get:
----------------------------------------------------------------------
function findCookie(val){
  var cookie = null;
  var findVal = val + "=";
  var dc = document.cookie;
  if (dc.length > 0)
  {
    var start = dc.indexOf(findVal);
    if (start >= 0)
    {
      start += findVal.length;
      stop = dc.indexOf(";", start);
      if (stop == -1)
      {
        stop = dc.length;
      }
      cookie = (dc.substring(start, stop));
    }
    else
    {
      return cookie;
    }
  }
  return cookie;
}
----------------------------------------------------------------------
  Is this the best we can do?  Not quite.  For example, we don't want "stop" to be a global variable, so we need to add "var" ahead of it.  Also, we can note that the "else" with the "return" is extraneous, and can be removed.  This leaves us with the code below.
----------------------------------------------------------------------
/* create a variable named "u" and assign it the value of the cookie by the same name.  Create a second variable named "p" and assign it the value of the cookie by the same name. */
 
var u = findCookie( 'u' );
var p = findCookie( 'p' );
----------------------------------------------------------------------
This is ok, as long as the findCookie routine works.

Next, we find "deterUser()"
----------------------------------------------------------------------
/* use and if statement to check if teh variables "u" and "p" are both equal to null.  If so, then set the visibility of the objects with the ids "login" and "first" to "hidden". I addition, set the visibility of the object with the id "button" to "visible" */
 
function deterUser() {
if ((u !== null) && (p !== null)) {
  objectl = parent.document.getElementById("login");
   objectl.style.visibility="hidden";
  objectf = parent.document.getElementById("first");
   objectf.style.visibility="hidden";
  objectb = parent.document.getElementById("button");
   objectb.style.visibility="visible";}
}
----------------------------------------------------------------------
One of the common JavaScript idioms makes use of the fact that should we need to test a variable for a non-null value, we can simply use the variable name.

  A test of ( u != null ) is identical to ( u ).

Also, as noted in  http://www.experts-exchange.com/Q_24375437.html#a24290820, it is always a good idea to check to see if a document element exists before using it.  This routine could make really good use of this kind of test.  Let's create a routine called setVis(), and use it like shown below.

Lastly, we have valUser(), which appears to do multiple things.

1. You need to realize that a test like
    ( u != null )
    will return true if the value of u is anything other than null (or undefined).
    This really isn't any authentication.  So a user "name" of . would suffice, as would a "password" of "?"

2. Granted, the result of document.getElementsByName("user") will be an array of values, even if it is only a length of 1.  But the syntax to retrieve the first element is not item(0), it is [ 0 ], so to retrieve the 1st element should be done using something like this:

  document.getElementsByName("user")[ 0 ]

  But again, remember that should no document element exist, the result of

document.getElementsByName("user")

  will be null, and

document.getElementsByName("user")[ 0 ]

  will be invalid.

3. The rest of the code (i.e., to compute a date 90 days in the future, and set two cookie values) should work ok.
function findCookie(val){
  var cookie = null;
  var findVal = val + "=";
  var dc = document.cookie;
  if (dc.length > 0)
  {
    var start = dc.indexOf(findVal);
    if (start >= 0)
    {
      start += findVal.length;
      var stop = dc.indexOf(";", start);
      if (stop == -1)
      {
        stop = dc.length;
      }
      cookie = (dc.substring(start, stop));
    }
  }
  return cookie;
}
 
function setVis( id, vis ) {
  var ele = document.getElementById( id )
  if ( ele ) {
    ele.style.visibility = vis
  }
}
 
/* use and if statement to check if teh variables "u" and "p" are both equal to null.  If so, then set the visibility of the objects with the ids "login" and "first" to "hidden". I addition, set the visibility of the object with the id "button" to "visible" */
 
function deterUser() {
if ( u && p ) {
  setVis( "login", "hidden" )
  setVis( "first", "hidden" )
  setVis( "button", "visible" )
}

Open in new window

0
 
HonorGodCommented:
Thanks for the grade & points...

Hopefully this has helped you.

Good luck & have a great day
0
 
Black-ScoutCommented:
I am attempting the same problem and I did find your post very useful. I am however stuck with the valUser() function.

I will paste it below. I'm always looking to learn how to do something better, but in this case I'm simply trying to follow instructions. Here goes:

 
function valUser() {
/* use an if statment to check if the variable "u" and "p" are both equivalent to null. If so, redirect users to a page named mollie_prod.html. Close the if statement */
	if ((u !== null) && (p !== null)) {
		window.location ="mollie_prod.htm";
		}
		
/* From the form with the id "enter", pass the value of the "user" field to a var of the same name. Repeat for the "pwd" field */  
	var user = document.getElementsByName("user")[0].value;
	var pwd = document.getElementsByName("pwd")[0].value;
	
/* Use an if statement to check if the variables "user" and "pwd" are both empty. If so the function should return "false" */
		if ((user == "") && (pwd == "")) {alert('empty');
 		 return false;
		 }
		 
/* else it should create a var named "today" containing the current date and a variable named "expdate" = to the current date plus ninety days. It should also create a cookie named "u" with a value = to the value of the "user" variable and an expiration date = to the var "expdate" In addition it should create a cookie named "p" with a value equal to the value of the "pwd" var and an expiration date = to the var "excpdate"*/

    else { alert('not empty');
      var expdate = new Date();
      expdate.setDate(expdate.getDate()+90);
      document.cookie = "u="+user+"; expires="+expdate.toGMTString();
      document.cookie = "p="+pwd+"; expires="+expdate.toGMTString();
	  }
}

Open in new window

0
 
Black-ScoutCommented:
I should confirm something. The code is working in I.E and Firefox, but not Chrome.  I know it could be a lot cleaner but I'm at the mercy of my dated textbook.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 10
  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now