我正在尝试使用JavaScript密码保护网页



我正在尝试密码保护我的网页(http://mywebsite.com/例如(,使得用户每次会话只需要输入一次密码。我的问题是:如果用户取消了最初的提示或输入了错误的密码,然后被重定向到google.com,然后重新访问http://mywebsite.com/它允许他们在不提示输入密码的情况下查看页面

不确定我做错了什么来解决这个小后门的问题。

以下是我试图实现的JavaScript:

//Protect only once per browser session? (0=no, 1=yes)
//Specifying 0 will cause protect to load every time page is loaded
var once_per_session=1
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1)
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function passwordProtect(){
var password;
var pass1 = "thePassword";
password = prompt('Enter password to view page',' ');
if(password == pass1){
alert('Correct password, click ok to enter');
window.location="http://mywebsite.com";
}
else {
window.location="http://google.com";
}
}
function loadornot(){
if (get_cookie('protect')==''){
passwordProtect()
document.cookie="protect=yes"
}
}
if (once_per_session==0)
passwordProtect()
else
loadornot()

如果protectcookie为空字符串,则loadornot()仅加载passwordProtect()。它还将cookie的值设置为"yes"。因此,下次调用它时,cookie不再为空,并且永远不会调用"passwordProtect(("。

您似乎相信,如果passwordProtect()因用户未能提供正确的密码而将其发送到谷歌页面,则loadornot()函数将在不执行最后一行的情况下结束。事实并非如此。请记住,javascript有一个异步执行模型,这意味着loadornot()在执行对passwordProtect()的调用时不会停止执行。当用户输入密码时,将cookie值设置为"yes"的行已经执行。

如果您希望函数A根据函数B中的决策结果有条件地执行,您必须告诉函数A等待,直到函数B告诉您决策已经做出。实现这一点的主要方法是回调和承诺。

有关如何进行回调的简单示例,请参阅w3schools.com上的此示例。有关使用回调和承诺自定义确认框的更多示例,请参见此。

我通过从passwordProtect((返回一个bool来修复这个问题,然后在将cookie更新为"yes"之前检查bool是否为true。我知道这是密码保护的基本实现,但所有的帮助都很棒。

我以前做的改变:

//Protect only once per browser session? (0=no, 1=yes)
//Specifying 0 will cause protect to load every time page is loaded
var once_per_session=1
var bool
function get_cookie(Name) {
[see post]
}
function passwordProtect(){
var password;
var pass1 = "thepassword";
password = prompt('Enter password to view page',' ');
if(password === pass1){
alert('Correct password, click ok to enter');
window.location="http://example.com";
return true;
}
else {
window.location="http://google.com";
return false;
}
}
function loadornot(){
if (get_cookie('protect')===''){
bool = passwordProtect();
if(bool === true)
document.cookie="protect=yes";
}
}
if (once_per_session===0)
passwordProtect()
else
loadornot()

最新更新