【发布时间】:2018-02-11 00:55:57
【问题描述】:
我正在使用 WebStorage 制作一个带有用户名/密码的简单登录系统。 (我不知道这是否是最好的方法。) 它可以工作,但问题是,它只能使用一个用户名和密码。我如何使它可以存储多个用户名/密码?或者也许我应该使用不同的系统来做到这一点? 代码:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps:如果乱七八糟的话,抱歉:p
【问题讨论】:
-
您应该使用服务器端来存储和验证用户名和密码。让用户在用户端注册和验证,只会在他现有的浏览器会话中工作(所以如果用户移动电脑或清除缓存,它将需要再次注册)而且前端中的这个逻辑非常不安全,因为我可以更改代码并授予我的自我访问权限。
-
其中风险更大的部分是,在您的页面中运行的任何脚本也可以访问这些值(例如广告),不幸的是,我们知道互联网用户经常重复使用相同的凭据,从而使您的网站成为容易泄漏的来源。
标签: javascript html web-storage