Password protect html page - javascript

I need to tack some simple password protection onto arbitrary html files. It does need need to be secure, but just keep out the random roff-raff. I tried using the below JS:
var password;
var thePassword="secretpassword";
password=prompt('Enter Password',' ');
if (password==thePassword) { alert('Correct Password! Click OK to Enter!'); }
else { window.location="http://www.google.com/"; }
This works fine in Firefox, but seems that the prompt function fails in IE and so we always redirect to google...
Any suggestions on how to do a simple password protection using straight HTML pages?
EDIT: to be clear, it works fine in Firefox, and in IE does not even prompt with a popup asking to "Enter Password"

Works fine for me in IE. Demo: http://jsfiddle.net/U2n3P/
One possible reason it may not be working is that you're populating the prompt with an empty space, by using ' ', so when you start typing there may be a space at the end. Change the prompt to:
password=prompt('Enter Password', '');
FYI, I know you said you didn't need this to be super secure, but you might as well add some security. Get an MD5 library and do, instead:
var thePassword = "md5encodedpassword";
password=prompt('Enter Password',' ');
if(md5(password) != thePassword){

Name the secure page or directory the md5 hashed password.
function isThere(url) {
var req= new AJ(); // XMLHttpRequest object
try {
req.open("HEAD", url, false);
req.send(null);
return req.status== 200 ? true : false;
}
catch (er) {
return false;
}
}
password=prompt('Enter Password',' ');
password=md5(password);
if (isThere(md5 + "/") { window.location = password + "/"; }
else { alert("incorrect"); }

Related

Inputting different passwords always redirects to the HTML page of the first password

I am trying to make a password system, in which for specific password, it redirects to a custom web-page, Like a support-type system
But whenever I type the password: tanishq1e01, or tanishq1e02, it always returns the webpage for
tanishq1e02 webpage. Why?
I expected that it would output a different webpage for each password, but it doesn't work!
var ff;
let tanishq1e01 = "tanishq1e01";
let tanishq1e02 = "tanishq1e02"
ff = prompt("Enter Given Password By Prattay: ");
if (ff == tanishq1e01) {
window.location.href = "suppstsasd/tanishq1e01suppasd.html";
} else if (ff = tanishq1e02) {
window.location.href = "suppstsasd/tanishq1e02suppasd.html";
} else {
confirm("Not Right Password! Refreshing...");
window.location.reload();
}
You have a = assignment instead of == or === compare in the second test.
Here is a more elegant way, where it is easier to add locations
This is assuming you want to use such insecure way to load pages.
const locations = {
"tanishq1e01": "suppstsasd/tanishq1e01suppasd.html",
"tanishq1e02": "suppstsasd/tanishq1e02suppasd.html"
}
let ff = prompt("Enter Given Password By Prattay: ");
let loc = locations[ff];
if (!loc) {
alert("Not Right Password! Refreshing...");
window.location.reload();
}
else {
console.log("Going to", loc);
window.location.href = loc;
}

JavaScript Form Validation Still Submits Form on 'False'

Question as stated above. I am using older browsers (IE8 and FF8) due to corporate policy. I can't fix this but my research says this isn't the issue...(yeah right;)
I'm using PHP 5.5.12 on Apache 2.4.9 with a MySQL (5.6.17) back end. The site is a CMS that has grown organically over several years.
I have a user admin page that adds, updates, and deletes accounts. However, no matter what I have done the form submits. The worst example is if the admin chooses to delete an account and when asked 'Do you really wish to DELETE...?' and cancels, it is still deleted! I've copied my JavaScript and an excerpt from the PHP/HTML below.
I have tried a few changes to my JavaScript like returning after setting the window.event.returnValue but I've always gotten the same results. I've been reading for several days now and keep coming up blank! I've tried onSubmit instead of onClick but it really doesn't suit the site, besides it didn't work either.
I'm beginning to think the age of the browsers is the issue. I run this with Safari on my home development box fine. Any help would be appreciated.
JavaScript
<script language="JavaScript">
function frmVerify(check, loginid, login) {
if (check == 'add') {
Uname=add_user.login_name.value;
Pass1=add_user.password.value;
Pass2=add_user.password2.value;
if(Uname=='') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Uname == login) {
alert('You cannot create an account with your own username (' + login + ')');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords are not the same! Make sure the password and verification fields match.');
window.event.returnValue=false;
}
if(Pass == '') {
alert('Assigning a password is required when creating an account!');
window.even.returnValue=false;
}
} else if(check == 'update') {
Uname=eval('edU_'+loginid+'.login_name.value');
Pass1=eval('edU_'+loginid+'.password.value');
Pass2=eval('edU_'+loginid+'.password2.value');
if(Uname == '') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords do not match! Make sure the passowrd and verification fields match.');
window.event.returnValue=false;
}
} else if(check == 'del') {
Uname=eval('edU_'+loginid+'.login_name.value');
if(Uname == '') {
request = 'Do you really wish to DELETE this user account?';
} else {
request = 'Do you really wish to DELETE user: ' + Uname + '?';
}
var answer = confirm(request);
if(answer) {
window.event.returnValue=true;
} else {
window.event.returnValu=false;
}
}
}
</script>
In the PHP/HTML I have
echo "<form name=\"delU_$login_id\" id=\"delU_$login_id\" mehtod=\"POST\">";
echo "<input type=\"image\" src=\"./images/delete.png\" value=\"Delete\" onClick=\"return frmVerify('del', '$login_id', '$username');\">";
echo "</form>";
window.event.returnValue (which you don't always spell correctly anyway) is non-standard and shouldn't be used.
You're using 1990s style intrinsic event attributes instead of addEventListener, so just:
return false;
If you were using addEventListener then you would:
event_object.preventDefault();
where event_object is the first argument to your event handler function.

Chrome Offering To Save Password on Registration Form - Ajax

I have a registration form and when everything checks out and the registration button (submit button for the form) is clicked, it runs all of the following code. the /xhrCreateUser method in my PHP controller further validates, sanitizes, and inserts the POST data into a database. For simple error checking for now, if the echo from the /xhrCreateUser method is true, then it alerts the user that the account has been created and it redirects the page. However, when the redirect method is called, the browser offers to save the password when the user is redirected. I would like this behavior to happen on something like a login form, but not a registration form. If the redirect is not called, the Offer to save the password does not trigger, so obviously it is that that is triggering chrome to offer to save the password. I don't get why this is happening, it does not do employ this behavior in Firefox. Is it something to do with me posting the value of a password input element or something?
I imagine chrome does this to support ajax login forms, but its also doing this on my registration form, which is not ideal.
register.addEventListener('click', function(e){
if(validateName(0)){
if(validateName(1)){
if(validateUsername(2)){
if(validateEmail(3)){
if(validatePassword(4)){
//Start XML HTTP Account Insertion
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function register(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
if(result.indexOf('true') > -1){
alert("Account has been created, you will be redirected");
redirect();
//redirect
} else {
alert("Something went wrong, that's all we know. Please refresh the page and try again.");
}
}
}
xmlhttp.open("POST", "user/xhrCreateUser", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSON.stringify({firstname:firstname.value, lastname:lastname.value, username:username.value, email:email.value, password:password.value}));
} else {
//password is bad
//toggle error classes for CSS here
forceError(4);
password.focus();
}
} else {
//email is bad
//toggle error classes for CSS here
forceError(3);
email.focus();
}
} else {
//username is bad
//toggle error classes for CSS here
forceError(2);
username.focus();
}
} else {
//lastname is bad
//toggle error classes for CSS here
forceError(1);
lastname.focus();
}
} else {
//firstname is bad
//toggle error classes for CSS here
forceError(0);
firstname.focus();
}
});
Solved
Making the POST synchronous and not asynchronous worked by changing true to false in the xmlhttp.open line worked.

Password Protect Page

I took the following code from another webpage "http://www.javascriptkit.com/script/cut10.shtml".
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1) history.go(-1);
if (pass1.toLowerCase() == "letmein") {
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV+=1;
var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
Your code appears to work when visiting the link.
I know you're learning. Still, you shouldn't be doing authentication like this though as you're not really protecting anything. Anyone can read the source code by using the "View Page Code" option in any browser (typically right click on the page). This means anyone can easily get your password.
For true authentication you should be using either a server side language (like PHP), or HTTP Digest authentication configured by your web server. Digest is a bit out of date as it uses MD5, but it's a million times better than what you're doing.
For more information about setting up HTTP Digest with Apache web server see:
http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html
For doing the same with Nginx:
http://wiki.nginx.org/HttpAuthDigestModule
The HTTP Basic authentication works too, but it transmits the password from the user's browser in plain text. With HTTP digest the password is hashed.
Knowing that you're learning JavaScript, your best bet is to configure the web server you're using. Since most web hosting services use Apache, you can most likely use an .htaccess file. You can search ".htaccess http digest" for tutorials on how to set this up.
Some web hosting services have control panels that have a feature to protect directories using Digest/Basic auth. In cPanel, which is quite common, it's called "Password Protect Directories".
If you were more advanced I would suggest doing it in PHP, but thats a rather complicated subject.
//Add this to you script
function run(){
var password = prompt("Password Please");
//Change to your own Password
if(password != 'Sameer'){
document.body.innerHTML = '';
document.body.innerHTML = 'Password Failed! Reload to Renter Password';
}else{
alert('Success');
}
}
run();
Try this.. Just add access denied prompt inside the false case...
function passWord()
{
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3)
{
if (!pass1)
{
history.go(-1);
var pass1 = prompt('Access Denied - Password Incorrect, Please Try
Again.','Password');
}
else if (pass1.toLowerCase() == "letmein")
{
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV+=1;
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
I used the same exact code that you have and the problem is the the first time for don't know what reason it added one space in front of the input. Just make sure that you don't have that and it will be fine.
If you use a library to render the UI, you can use this function:
export function setPasswordToEnter({
password,
localStorageKey,
errorMessage,
}) {
if (
!password ||
(localStorageKey && localStorage.getItem(localStorageKey) === password)
) {
return;
}
const input = prompt('Enter the password to continue:');
if (input !== password) {
alert(errorMessage || 'Incorrect password');
throw new Error(errorMessage || 'Incorrect password');
}
if (localStorageKey) {
localStorage.setItem(localStorageKey, input);
}
}
Run before the render function:
setPasswordToEnter({
password: 'password',
localStorageKey: '[myapp] password to enter'
});
React Example: https://stackblitz.com/edit/password-to-enter-react?file=src/index.js
P.S. You should definitely get your password from env variable if possible.

Simple Password Javascript Code?

I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again.
I'm planning on loading this script onto my cell phone, which doesn't have a password-protected keylock feature.
Don't know if this works on your cell phone, but it does with my browser:
<head>
<script language="JavaScript">
var pass_entered;
var password="cool";
while (pass_entered!=password) {
pass_entered=prompt('Please enter the password:','');
}
self.close();
</script>
</head>
Javascript "keylock" on a cell phone will probably be trivial to work around.
Anyway, if you really want to check password in Javascript, you can at least avoid putting it in plain text in page source.
Get MD5 JS implementation, and compare (salted!) password hashes instead.
Ok, we can have two approuches.
We can all read javascript, so if the person actually open your code he will see the password.
By ajax, check the password in a specific page.
function passWrdAPI() {
this.getHX = function() {
var hx;
try {
hx = new XMLHttpRequest();
}
catch(e) {
try {
hx = new ActiveXObject("Microsoft.XMLHttp");
}
catch(ex) {
hx = new ActiveXObject("Msxml2.XMLHttp");
}
}
return hx;
}
this.password = "mypass";
this.checkPwd = function(pass) {
if (pass != this.password) {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
this.checkPwdPage(page, pass) {
var hx = this.getHX();
if (hx != null) {
hx.open('GET',page + "?mypwd=" + pass);
hx.onreadystatechange = function() {
if (hx.readyState == 4) {
if (hx.responseText == 'false') {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
}
hx.send(null);
}
else {
alert('error!');
}
}
}
Usage:
for the first approach:
var check = new passWrdAPI();
check.checkPwd(THEPASSENTERED);
for the second:
var check = new passWrdAPI();
check.checkPwdPage(YOURPAGE, THEPASS);
I don't know if it will work on your cell phone =/
Sorry if I don't help.. bye bye!

Categories