Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Password protecting web pages?

Status
Not open for further replies.

markdmac

MIS
Dec 20, 2003
12,340
US
I found the following sample script code:

Code:
	<script type="text/javascript">
		var pw =prompt('Please Enter a Password to View Protected Content: ','');
 			if (pw != 'XYZ') top.location = 'index.html';</script>

I have a need to password protect some pages and would like to have support for both username and password. Tight security is not a real issue, we just want to use this to encourage people to register on the site.

Is there a way to edit the above sample so it will accept input for both a user name and a password?

Next step is I would like the user to only be prompted once for a group of pages. So I assume I require the use of a cookie.

I know how to do this easily with ASP code, but my customer is not using a Windows Web Server.

Many thanks for any assistance, JavaScript is not my area of expertise, vbscript is and the customers server prevents me from leveraging my vbscript knowledge.
 
You do realise anyone can just look at your source code and read what the password is?

To answer your question:
Code:
<script type="text/javascript">
var un = prompt('Please Enter a Username to View Protected Content: ','');
var pw =prompt('Greetings ' + un +'. Please Enter a Password to continue: ','');
if (un != "banned_dude" && pw != 'XYZ') top.location = 'index.html';</script>

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
markdmac,

Unfortunately, there are a number of other factors to
consider, but I'll list three possible solutions from a
conceptual standpoint. If you really want the code,
I'll provide it later, but I think you might reconsider
after reading further.

A) You could just do two prompts. One for the userid and
second for the password.

B) Or just one prompt with instructions to enter the userid
and password like thus: John/password. The problem with the
first is, the dual prompts may confuse the user. The
problem; although trivial, requires parsing the entered
value.

C) Finally, you could pop-up a window with a form that you
keep a reference to which you can then access the entered
information.

But as you'll see below, there are other issues involved


1) If this is an open page to the internet in general,
you can never be sure the user even has JavaScript
enabled. So, you need to compensate for that.

2) Performing uid/pwd authentication at the client is
generally a bad idea. It's just too easy to circumvent.

3) If JavaScript is enabled, you have to make sure that
the functionality you desire actually will work in that
particular browser implementation of JavaScript.

4) It would probably be easier; and safer in the long
run, to figure out how to implement the functionality
at the server end. Or… display the required fields
in a form on the page itself.

5) You never know what the popup setting is on the user's
browser and JavaScript's prompt command will be seen
as a popup by many popup detectors and browsers to boot.

6) Just restructure the page so authentication is done on
the first page via a form, send that to the server and
then send back the proprietary content if the user is
authenticated. Otherwise, you'll just send users
elsewhere. I can pretty much guarantee it.

Use JavaScript where it really does some good.

Whew! Oh the vagaries of transitioning to the web!

Darrell

 
To expand on dwarfthrower's post, not only will the person viewing the source code see the password, they'll see the URL being redirected to. You'll have to use server-side scripting for any kind of authentication that validates beyond the login page, so you might as well use it for the initial validation.

However, if you want an idea for validation, I recommend encrypting the password using one-way encryption, like MD5 or something along those lines. That way the password itself is never transmitted or seen, and a matching the encrypted password entered to the encrypted password stored will validate fine.

Lee
 
Thanks for all the input folks.

As I stated above I am not really concerned with the security. All users get the same password and the need to login is just to encourage people to register on the site. If someone does not then that is not that big if a deal.

Dwarfthrower, looks like your suggestion will handle much f what I am looking for but it appears it does not utilize a cookie.

darrellblackhawk, I agree with you I would prefer to use a server side solution. There are limitations to what I can do however because I am working with a site I did not design. I need to do as little changing as possible while correcting a navigation error.

Currently there is a link to a login page. This has all the code to register on the site or allows the user to login. When the user logs in they are directed to the content page.

What I would like to do is change the link on all pages to point to the content page instead of the login page. I then want the login page itself to validate if the user has already logged in and if not direct the user to the login page. I want to be able to use the same code edition on each of the linked pages under the content page to perform the same validation (I presume by reading a cookie).

It is OK that a user can view the source to get the ID & password. We are not concerned about that.

Hopefully I've explained my need better. Can anyone assist with that?

Many thanks for everyone's efforts.

Mark
 
Well, there is a way to do it without any server-side scripting. I would of curse prefer PHP/ASP scripts to manage this..

First crate a script file in the same directory as the index file and name it with the username (ie joe.js). Then write the following code in it.

Code:
[navy]url = 'page_path.html';  [green]//  Page to redirect to[/green]
pwd = 'mypass';  [green]//  Or whatever password for the user[/green][/navy]

Then add this HTML to the index file.

Code:
<html>

<head>
<script id="js" type="text/javascript" src=""></script>
<script type="text/javascript">
<!--
[navy]var url,pwd;
function chkLogin()
{
var t_usr,t_pwd,jso;
url = false;
pwd = false;
t_usr = document.forms[0].usr.value;  [green]//  Passed username[/green]
t_usr = (/^[a-z0-9_]+$/i.test(t_usr)?t_usr:false);  [green]//  Check if valid[/green]
t_pwd = document.forms[0].pwd.value;  [green]//  Passed password[/green]
t_pwd = (/^[a-z0-9_]+$/i.test(t_pwd)?t_pwd:false);  [green]//  Check if valid[/green]
jso = document.getElementById('js');
jso.src = '';
   if (t_usr && t_pwd) {
   jso.src = t_usr+'.js';  [green]//  Load script file[/green]
      if (!url) {alert('User does not exist!');}
      else if (pwd != document.forms[0].pwd.value) {alert('Wrong password!');}
      else {location = url;}
   return true;
   }
   else {
   alert('Invalid username or password!');
   return false;
   }
}[/navy]
</script>
</head>

<body>
<form action="#" onsubmit="[navy]return false;[/navy]">
Username:<br>
<input type="text" name="usr" value=""><br>
Password:<br>
<input type="password" name="pwd" value=""><br>
<input type="button" value="OK" onclick="[navy]chkLogin();[/navy]">
</form>
</body>

</html>

And then create the page which you linked to in the script file (ie joe.js).


- Lowet

[gray]Why can't all browsers parse pages the same way? It should be the Web designer who decides how to display the content, not the browser![/gray]
 
Glen and Lowet, many thanks for your additions. I'm getting a much better understanding now for the limitations that JavaScript has.

From what I can decipher neither new suggestion stores data in a cookie to verify if the user has already logged in. Is there and easy way to add that?
 
markdmac, yes, there are many extremely simple ways of using cookies... simply searching for [tt]setCookie[/tt] and [tt]getCookie[/tt] will tell you everything you need to know about using cookies.

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
You folks have been really great, thank you for all your assistance.

I think I have found sample code to do most of what I need here:
I am wondering if there is a way to alter this section of code:

Code:
<script type="text/javascript" src="session.js"></script> 
<script type="text/javascript"> 
checkSession(); 
passwordValidated(); 
window.top.location.href="zv45x2wy_home_gv8.html"; 
</script>

The above is for an "interim page" that checks the session and if valid it forwards on to the designated page.

I'd like to be able to include this on all the pages to be secured and have it forward if the session is NOT valid. That way I can direct to the login page.

In vbscript/asp this would be

If Session <> True Then
Response.Redirect URL
End If

So for a javascript version would it just be?:

Code:
If !checkSession(); 
   passwordValidated();{
   window.top.location.href="login.html"; 
}



I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Too many semicolons, Mark:
Code:
if !checkSession()
  {
  window.top.location.href="login.html"; 
  }

Lee
 
Thanks Lee, for some reason it is not directing me to the login script. I rebooted my PC to ensure the session would clear.

I have the code added in the header section of my web page. Does it need to go above that to be detected?
 
Hey Lee,
The parentheses are missplased.

[tt]if !checkSession[red]([/red])
{
window.top.location.href="login.html";
}[/tt]

Use:

Code:
if (!checkSession)
  {
  window.top.location.href="login.html"; 
  }


- Lowet

[gray]Why can't all browsers parse pages the same way? It should be the Web designer who decides how to display the content, not the browser![/gray]
 
checkSession() appears to be a function name from an earlier post, and so does passwordValidated(). So, to modify Lowet's code, try this:

Code:
if (!checkSession() || !passwordValidated())
  {
  window.top.location.href="login.html";
  }

If that doesn't do the trick, show us the code for those 2 functions so we know what kind of values they're returning.

Lee
 
Lowet said:
Hey Lee,
The parentheses are missplased.

[tt]checkSession()[/tt] is a function that (presumably) returns a boolean value or at least either something or null.

[tt]if !checkSession()[/tt] is met where [tt]checkSession()[/tt] returns [tt]false[/tt]. ie Do something here if the function [tt]checkSession()[/tt] returns false.

[tt]if(!checkSession)[/tt] is met if the function [tt]checkSession()[/tt] is not actually defined... usually used if you want to test for the existence of a function before attempting to call it.

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
hehe :p I saw it as a variable since the parantheses where missing :p nevermind..

- Lowet

[gray]Why can't all browsers parse pages the same way? It should be the Web designer who decides how to display the content, not the browser![/gray]
 
You guys are all troopers for sticking with me so long.

I tried using:
if (!checkSession() || !passwordValidated())
{
window.top.location.href="login.html";
}

But same result. It just lets me into the page without validation.

Here is the code used in login.html

Code:
<html> 
<head> 
<title>Login</title> 
<script type="text/javascript"> 
// Disable context menu (right click) 
document.oncontextmenu = new Function("return false"); 
</script> 
<script type="text/javascript" src="session.js"></script> 
<script type="text/javascript"> 
var passwd = ""; 

// This function is called when the image cannot be 
// successfully loaded 
function errorHandler (evt) { 
alert("You have entered an invalid password."); 
} 

function loadHandler (evt) { 
top.location.href = passwd + ".html"; 
} 

function logon(passw) { 
passwd = passw.value; 
var img = new Image(); 
img.onload = loadHandler; 
img.onerror = errorHandler; 
img.src = passwd + ".gif"; 

passw.value=""; 

return false; 
} 

function startSession() { 
if (isCookiesEnabled() == 0) { 
newSession(); 
} else { 
top.document.location.href="enablecookies.html"; 
} 
} 
</script> 
</head> 
<body onload="startSession();"> 
<form onsubmit="logon(pwd);"> 
<p>Please enter your password:<br/> 
<input type="password" id="pwd" name="pwd"/><br/></p> 
</form> 
<noscript> 
<p>Your browser does not support, or is not enabled to run Javascript.</p> 
</noscript> 
</body> 
</html>

And here is the code from session.js

Code:
// Set a cookie 
function setCookie(name, value, expires, path, domain, secure) { 
// set time, it's in milliseconds 
var today = new Date(); 
today.setTime(today.getTime()); 

if (expires) { 
expires = expires * 1000 * 60; 
} 
var expires_date = new Date(today.getTime() + (expires)); 
document.cookie = name + "=" + escape(value) + 
((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
((path) ? ";path=" + path : "") + 
((domain) ? ";domain=" + domain : "") + 
((secure) ? ";secure" : ""); 
} 

// Get the specified cookie 
function getCookie(name) { 

var dc = document.cookie; 
var start = dc.indexOf(name + "="); 
var len = start + name.length + 1; 

if ((!start) && 
(name != dc.substring(0, name.length))) { 
return null; 
} 

if (start == -1) return null; 
var end = dc.indexOf( ";", len ); 
if (end == -1) end = dc.length; 
return unescape(dc.substring(len, end)); 
} 

// Indicate that user visited the logon page. 
function newSession() { 
setCookie("visitedloginscreen", "yes", "", "/", "", ""); 
} 

// Indicate that the password entered is valid. 
function passwordValidated() { 
setCookie("passwordisvalid", "yes", "", "/", "", ""); 
} 

// Check whether user visited logon page. 
function checkSession() { 
if (getCookie("visitedloginscreen") != "yes") { 
top.location.href="illegalaccess.html"; 
} 
} 

// Check whether user entered valid password. 
function checkValidation() { 
if (getCookie("passwordisvalid") != "yes") { 
top.location.href="illegalaccess.html"; 
} 
} 

// Check if cookies are enabled on client browser. 
function isCookiesEnabled() { 
setCookie("cookiesenabled", "yes", "", "/", "", ""); 
if (getCookie("cookiesenabled") != "yes") { 
return -1; 
} else { 
return 0; 
} 
}

Hope this helps isolate things.
 
Neither checkSession nor passwordValidated are currently returning a specified value... in the absence of a specified return value, a function will return [tt]null[/tt] to the calling code.

Interesting Javascript factoid is that boolean logic doesn't just discriminate between [tt]true[/tt] and [tt]false[/tt], but also between [tt]null[/tt] and "anything that is not [tt]null[/tt]".

[tt]!null[/tt] is the same as [tt]true[/tt];

So:
[tt]checkSession()[/tt] is the same as [tt]null[/tt]. And,
[tt]passwordValidated()[/tt] is the same as [tt]null[/tt]. So,
[tt]!checkSession()[/tt] is the same as [tt]true[/tt]. And,
[tt]!passwordValidated()[/tt] is the same as [tt]true[/tt]. So ultimately,
[tt]if (!checkSession() || !passwordValidated())[/tt] is the same as [tt]if (true || true)[/tt]. Which boils down to [tt]if(true)[/tt] which will always return [tt]true[/tt].


Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
Uhhhhh my head hurts!

So with that all in mind dwarfthrower, is there another way to do the logic so it will properly detect the user was not logged in and allow me to redirect them to the login?
 
Um yes.... that would be to include return values in your functions so that they're not returning [tt]null[/tt] all the time. :)

Code:
function passwordValidated() {
 setCookie("passwordisvalid", "yes", "", "/", "", "");
 return true;
}

Code:
function checkSession() {
 if (getCookie("visitedloginscreen") != "yes") {
  top.location.href="illegalaccess.html";
  return false;
 }
 else{
  return true;
 }
}

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Webflo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top