- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 JSON 做一个登录表单,我有 3 个不同的用户在一个登录页面中登录,他们是 1. 用户 2. 管理员 3. vendor 这是 my code .我这样做是作为测试用例,稍后我会将身份验证详细信息更改为服务器端。
<html>
<head>
<title> Login Form</title>
<script>
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var loginlist = { "User": {
"userlist":[{"username":"usr1", "password":"a123"},{"username":"usr2", "password":"a123"},{"username":"usr3", "password":"a123"}],
"ID":1
},
"Admin": {
"adminlist":[{"username":"admin1", "password":"b123"},{"username":"admin2", "password":"b123"},{"username":"admin3", "password":"b123"}],
"ID":2
},
"Supplier": {
"supplierlist":[{"username":"sup1", "password":"c123"},{"username":"sup2", "password":"c123"},{"username":"sup3", "password":"c123"}],
"ID":1
}
};
var logged = false;
if(loginlist[0].User.ID === 1){
for(var i =0; i < loginlist[0].User.userlist.length; i++){
if(username == loginlist[0].User.userlist[i].username && password == loginlist[0].User.userlist[i].password){
logged= true;
}
}
if(logged)
alert("User login");
else
alert("User login fail");
}
else if(loginlist[0].Admin.ID === 2){
for(var j =0; j < loginlist[0].Admin.adminlist.length; j++){
if(username == loginlist[0].Admin.adminlist[j].username && password == loginlist[0].Admin.adminlist[j].password){
logged= true;
}
}
if(logged)
alert("Admin login");
else
alert("admin login fail");
}
else{
for(var k =0; k < loginlist[0].Supplier.supplierlist.length; k++){
if(username == loginlist[0].Supplier.supplierlist[k].username && password == loginlist[0].Supplier.supplierlist[k].password){
logged= true;
}
}
if(logged)
alert("Supplier login");
else
alert("supplier login fail");
}
}
</script>
</head>
<body>
<div class="container">
<div class="main">
<h2>Login Form</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" placeholder="Enter username" name="username" id="username"/>
<label>Password :</label>
<input type="password" placeholder="Enter Password" name="password" id="password"/>
<input type="button" value="Login" id="submit" onclick="validate()"/>
</form>
</body>
</html>
我试过了。我的问题是,当我在用户名和密码中输入一些内容时,没有任何显示,我已经完成了这种程序,但使用的是单用户操作。我无法在单个登录页面中实现多个用户
最佳答案
我不太确定将每个单独的用户类型作为单独的数组的原因是什么,这可能对某些特定用例有好处,但将所有用户放在一个集合中肯定会更直接。
将所有内容都放在一个数组中,然后提供一些用于获取特定用户类型的函数将是一种更好的方法,因为这样您就不必从一开始就过分担心结果。此外,您应该始终使用尽可能多的原 Material ;尽管人们可能会觉得这有争议。
通常最好不要在 <head>
中触发 JavaScript 代码HTML 的标记,除非需要,因为代码是在加载所有文档之前执行的。将所有 JavaScript 代码放在关闭 <body>
之前通常更安全。标签。
我还注意到您触发了 validate
按钮 click 上的功能。如果您通过除此之外的任何其他方法提交表单(例如,在聚焦的输入字段上按 enter),则会出现问题。我向表单本身添加了一个事件监听器,这应该可以处理所有常见的提交案例。
我让用户数组只有一层,其中包含所有用户。每个用户都有一个类型,用于确定用户的类型(普通用户、管理员用户、 vendor 等)
我已经对下面的每一行代码进行了注释。
此脚本不得用于任何类型的制作。这是危险的,因为所有检查都是在客户端和客户端完成的。始终使用服务器端检查,最好也在测试脚本中使用!
点击下面的Run Snippet按钮在此处测试脚本。
您可以从 JavaScript 脚本开头的数组中找到用户名和密码。
// store the IDs of all logged in users in here
var loggedusers = [];
// server should handle everything below...
// users array, which contains all users in the system
// on the server-side this could be an array returned by a MySQL database table, for example
var users = [{
// ID of the user
id: 1,
// username of the user
username: 'user1',
// password of the user, note that this should obviously be hashed on the server-side
// for PHP back-end: preferably hashed with 'password_hash' and compared using 'password_verify' if using PHP version 5.5 or newer
password: 'a',
// type of the user, currently using 'user', 'admin' and 'supplier', but technically it could be _anything_
type: 'user'
}, {
id: 2,
username: 'admin1',
password: 'b',
type: 'admin'
}, {
id: 3,
username: 'supplier1',
password: 'c',
type: 'supplier'
}];
// ... up to this point, never store this data on the client-side (especially highly sensitive information like hashes, salts, or even worse like plain text passwords like above).
/**
* null|Object getUserByProperty ( mixed key, mixed value [ , boolean strict = false, boolean multiple = false, boolean case_insensitive = false ] )
*
* Gets a user by a property key, value and various settings.
*
* @param mixed key Property key to look for.
* @param mixed value Property value to look for.
* @param boolean strict (optional) Should the comparison be type strict?
* @param boolean multiple (optional) Should it return all results, rather than the first result?
* @param boolean case_insensitive (optional) Should it ignore character case?
*
* @return null|Object Returns the user object, or null, if not found.
*/
function getUserByProperty(key, value, strict, multiple, case_insensitive) {
// prepare a result array
var result = [];
// loop through all of our users
for (var index in users) {
// get the user we are iterating through now
var user = users[index];
// check if the user has the specified property
if (typeof user[key] != 'undefined') {
// get the property value
var compare = user[key];
// doing something case insensitive
if (case_insensitive) {
// if the property value is a string
if (typeof compare == 'string')
// we want to turn it to lower case
compare = compare.toLowerCase();
// if the specified value is a string
if (typeof value == 'string')
// we want to turn it to lower case
value = value.toLowerCase();
}
// if specified value is not defined, or values match
if (typeof value == 'undefined' || ((strict && compare === value) || (!strict && compare == value))) {
// if we want multiple results
if (multiple) {
// the result will be appended to the result array
result.push(user);
} else {
// otherwise we just return it
return user;
}
}
}
}
// return the results or null, if nothing was found (for single match search)
return multiple ? result : null;
}
/**
* null|Object getUserById ( number id )
*
* Gets a user with the specified ID.
*
* @param number id ID of user to get.
*
* @return null|Object Returns the user object, or null, if not found.
*/
function getUserById(id) {
return getUserByProperty('id', id);
}
/**
* null|Object getUserByUsername ( string username [ , boolean case_insensitive = false ] )
*
* Gets a user with the specified username.
*
* @param string username Username of user to get.
* @param boolean case_insensitive Should character case be ignored?
*
* @return null|Object Returns the user object, or null, if not found.
*/
function getUserByUsername(username, case_insensitive) {
return getUserByProperty('username', username, false, false, case_insensitive);
}
/**
* boolean|array getUsersByType ( string type [ , boolean case_insensitive = false ] )
*
* Gets all users with the specified type.
*
* @param string type Type of user to look for.
* @param boolean case_insensitive Should character case be ignored?
*
* @return array Returns the an array of user objects.
*/
function getUsersByType(type, case_insensitive) {
return getUserByProperty('type', type, false, true, case_insensitive);
}
/**
* boolean|Object login ( string username, string password )
*
* Provides the functionality to be able to log in on a user.
*
* @param string username Username of the user to log in on.
* @param string password Password of the user to log in on.
*
* @return boolean|Object Returns the user object, or false, if login was not successful.
*/
function login(username, password) {
// checks whether username and password have been filled in
if (typeof username == 'string' && typeof password == 'string' && username.length > 0 && password.length > 0) {
// prepare a variable to store the user object, if any is received
var loggeduser;
// server should handle everything below...
// iterate through all users in the 'users' array (or database table perhaps, on server-side)
for (var index in users) {
// grab the property value with the property
var user = users[index];
// check if username and password match
if (username === user.username && password === user.password)
// set value of 'loggeduser' to the property value (user)
loggeduser = user;
}
// ... up to this point, and the user returned from the server should be set in to 'loggeduser'
// make sure highly sensitive information is not returned, such as hash, salt or anything
// check whether the user is set
if (typeof loggeduser != 'undefined') {
// save the ID of the user to the 'loggedusers' array
loggedusers[loggeduser.id] = true;
// update the logged in list
updatelist();
// return the received user object
return loggeduser;
}
}
return false;
}
/**
* boolean logout ( number userid )
*
* Provides the functionality to be able to log out from a user.
*
* @param number userid ID of the user to log out of.
*
* @return boolean Returns a boolean representing whether the log out was successful or not.
*/
function logout(userid) {
// check whether the ID is actually logged in
if (loggedusers[userid]) {
// temporary array, which we will be filling
var temporary = [];
// let's loop through logged users
for (var id in loggedusers)
// ignore our user
if (id != userid)
// let's put this user to the array
temporary[id] = true;
// we replace the 'loggedusers' array with our new array
loggedusers = temporary;
// update the logged in list
updatelist();
// we have successfully logged out
return true;
}
// we have not successfully logged out
return false;
}
/**
* boolean updatelist ( void )
*
* Provides the functionality to update the #logged-in-list element
* with the logged in users names and logout links.
*
* @return boolean Returns a boolean representing whether the update was successful or not.
*/
function updatelist() {
// get the #logged-in-list element
var list_element = document.getElementById('logged-in-list');
// check the element exists
if (list_element) {
// get the #logged-in element
var list_container_element = document.getElementById('logged-in');
// check the element exists and that we should be changing the styles
if (list_container_element)
// if there are no logged in users, "hide" the element, otherwise "show" it
list_container_element.style.visibility = loggedusers.length === 0 ? 'hidden' : 'visible';
// we take the first child with a while loop
while (list_element.firstChild)
// remove the child, and it will repeat doing so until there is no firstChild left for the list_element
list_element.removeChild(list_element.firstChild);
// we loop through every logged in user
for (var id in loggedusers) {
// get the user by ID
var user = getUserById(id);
// check if that user is a user
if (user) {
// we create necessary elements to cover our logout functionality
var p = document.createElement('P');
p.innerText = user.username;
var a = document.createElement('A');
a.userid = id;
a.href = '#';
a.innerHTML = '(logout)';
// we bind an onclick event listener to the link
a.addEventListener('click', function(e) {
e.preventDefault();
// we will now execute the logout function for this user ID
logout(e.srcElement.userid);
});
// we append the link to the paragraph element
p.appendChild(a);
// we append the paragraph to the list element
list_element.appendChild(p);
}
}
return true;
}
return false;
}
// add a new 'onsubmit' event listener to the '#login-form' node
// this will be triggered each time the form is submitted via any method
document.getElementById('login-form').addEventListener('submit', function(e) {
// prevent default browser behavior
e.preventDefault();
// find the username and password nodes
var username_element = e.srcElement.elements.username;
var password_element = e.srcElement.elements.password;
// check whether these elements return right stuff
if (username_element && password_element) {
// get the values of username and password
username = username_element.value;
password = password_element.value;
// execute the 'login' function with the username and password filled in on the client
var user = login(username, password);
// check whether the login was successful
if (user !== false) {
// reset the username input field
username_element.value = '';
// reset the password input field
password_element.value = '';
// alert the client that login was successful
alert('Logged in as ' + user.username + '.');
} else {
// reset the password input field
password_element.value = '';
// alert the client that login was not successful
alert('Invalid username and/or password.');
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login Form</title>
</head>
<body>
<div style="visibility: hidden;" id="logged-in">
<p><strong>Logged in as:</strong>
</p>
<div id="logged-in-list"></div>
</div>
<form id="login-form">
<h2>Login Form</h2>
<label for="username">Username:</label>
<input type="text" placeholder="Enter username..." id="username" />
<label for="password">Password:</label>
<input type="password" placeholder="Enter password..." id="password" />
<input type="submit" value="Login" />
</form>
<!-- the JavaScript code should go as contents of this tag -->
<script></script>
</body>
</html>
对于使用此代码的任何人,请在任何情况下都不要在生产中使用它。 始终在服务器端执行验证和比较,并在服务器端检查之前执行客户端检查,以减少服务器上任何不必要的处理。
希望对你有帮助!
关于javascript - 在单个登录页面中使用多个用户登录的 Json 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763800/
在为 Web 应用程序用例图建模时,为用户可以拥有的每个角色创建一个角色是否更好?或拥有一个角色、用户和一个具有特权的矩阵? guest < 用户 < 版主 < 管理员 1: guest 、用户、版主
我无法使用 Elixir 连接到 Postgres: ** (Mix) The database for PhoenixChat.Repo couldn't be created: FATAL 28P
这个问题已经有答案了: Group by field name in Java (7 个回答) 已关闭 7 年前。 我必须编写一个需要 List 的方法并返回 Map> . User包含 Person
感谢您的帮助,首先我将显示代码: $dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESS
我只想向所有用户中的一个用户显示一个按钮。我尝试了 orderByKey() 但没有成功! 用户模型有 id 成员,我尝试使用 orderByChild("id") 但结果相同! 我什至尝试了以下技巧
我们在工作中从 MongoDB 切换到 Postgres,我正在建立一个 BDR 组。 在这一步,我正在考虑安全性并尽可能锁定。因此,我希望设置一个 replication 用户(角色)并让 BDR
export class UserListComponent implements OnInit{ users; constructor(private userService: UserS
我可以使用 Sonata User Bundle 将 FOS 包集成到 sonata Admin 包中。我的登录功能正常。现在我想添加 FOSUserBundle 中的更改密码等功能到 sonata
在 LinkedIn 中创建新应用程序时,我得到 4 个单独的代码: API key 秘钥 OAuth 用户 token OAuth 用户密码 我在 OAuth 流程中使用前两个。 的目的是什么?最后
所以..我几乎解决了所有问题。但现在我要处理另一个问题。我使用了这个连接字符串: SqlConnection con = new SqlConnection(@"Data Source=.\SQLEX
我有一组“用户”和一组“订单”。我想列出每个 user_id 的所有 order_id。 var users = { 0: { user_id: 111, us
我已经为我的Django应用创建了一个用户模型 class User(Model): """ The Authentication model. This contains the u
我被这个问题困住了,找不到解决方案。寻找一些方向。我正在用 laravel 开发一个新的项目,目前正致力于用户认证。我正在使用 Laravels 5.8 身份验证模块。 对密码恢复 View 做了一些
安装后我正在使用ansible配置几台计算机。 为此,我在机器上本地运行 ansible。安装中的“主要”用户通常具有不同的名称。我想将该用户用于诸如 become_user 之类的变量. “主要”用
我正在尝试制作一个运行 syncdb 的批处理文件来创建一个数据库文件,然后使用用户名“admin”和密码“admin”创建一个 super 用户。 到目前为止我的代码: python manage.
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 6 年前。 Improv
我已在 Azure 数据库服务器上设置异地复制。 服务器上运行的数据库之一具有我通过 SSMS 创建的登录名和用户: https://learn.microsoft.com/en-us/azure/s
我有一个 ionic 2 应用程序,正在使用 native FB Login 来检索名称/图片并将其保存到 NativeStorage。流程是我打开WelcomePage、登录并保存数据。从那里,na
这是我的用户身份验证方法: def user_login(request): if request.method == 'POST': username = request.P
我试图获取来自特定用户的所有推文,但是当我迭代在模板中抛出推文时,我得到“User”对象不可迭代 观看次数 tweets = User.objects.get(username__iexact='us
我是一名优秀的程序员,十分优秀!