简体   繁体   English

如何检查用户是否存在于本地存储中

[英]How to check if user exist in local storage

I have this class project to build a user registration and login form that stores data using local storage.我有这个 class 项目来构建一个使用本地存储存储数据的用户注册和登录表单。 If a new user registers it stores their email address and password in localStorage which is working as expected.如果新用户注册,它会将他们的 email 地址和密码存储在 localStorage 中,这将按预期工作。

But I am finding it difficult to compare data when a user that is not registered tries to login and when a user that is registered tries to login.但是,当未注册的用户尝试登录和已注册的用户尝试登录时,我发现很难比较数据。

If a user is registered and tries to login it should compare the input value with the stored data in localStorage and alert "login Successful" else "Not a registered user".如果用户已注册并尝试登录,则应将输入值与 localStorage 中存储的数据进行比较,并警告“登录成功”,否则“不是注册用户”。

I am using JavaScript to do this.我正在使用 JavaScript 来执行此操作。 Any help is highly appreciated.非常感谢任何帮助。

Here is the code:这是代码:

var userData;
var usersr;
var loginData;
var usersl;
// For user registration 
const registerBtn = document.getElementById('register-btn')

function UserRegistration() {
  userData = [{
    email: document.getElementById('register-email').value
  }, {
    password: document.getElementById('register-pass').value
  }];
  usersr = JSON.parse(localStorage.getItem('Users')) || [];
  usersr.push(userData);
  localStorage.setItem('Users', JSON.stringify(usersr));
  location.reload()
  console.log(userData)
}
// For user login 
const loginBtn = document.getElementById('login-btn')

function loginUser() {
  usersl = JSON.parse(localStorage.getItem('UsersLogin')) || [];
  loginData = [{
    loginEmail: document.getElementById('login-email').value
  }, {
    loginPass: document.getElementById('login-pass').value
  }];
  usersl.push(loginData)
  localStorage.setItem('UsersLogin', JSON.stringify(usersl))
  console.log(usersl)
  location.reload()
}

Ok I have made this code to register, now you can write your code to login, I took care of user duplication好的,我已经制作了这个代码来注册,现在你可以编写你的代码来登录,我负责用户复制

<!DOCTYPE html>
<html lang="en-us"></html>
<head>
  <meta charset="utf-8">
  <title>Register</title>
  <style>
  </style>
</head>
<body>

  <form onsubmit="return false">
    <input type="email" placeholder="email"><br>
    <input type="password"><br>
    <input type="submit" value="register">
  </form>

  <script>
    var emailElement = document.querySelector("[type='email']"),
      passwordElement = document.querySelector("[type='password']");

    if(!localStorage["UsersAuth"]) {
      localStorage["UsersAuth"] = "{}";
    }

    document.querySelector("[type='submit']").onclick = function() {
      var registeredUsers = JSON.parse(localStorage["UsersAuth"]);
      if(emailElement.value in registeredUsers) {
        alert("This email is already registered!");
      }else {
        registeredUsers[emailElement.value] = passwordElement.value;
      }
      localStorage["UsersAuth"] = JSON.stringify(registeredUsers);
    }
  </script>
</body>
</html>

There are a lot of unnecessary code in there.里面有很多不必要的代码。 You can use these functions to make it work:您可以使用这些功能使其工作:

function userRegistration() {
    const userData = {
        email: document.getElementById('register-email').value,
        password: document.getElementById('register-pass').value
    };
    localStorage.setItem('UsersLogin', JSON.stringify(userData));
    window.location.reload();
}

function loginUser() {
    const loginEmail = document.getElementById('login-email').value
    const loginPass = document.getElementById('login-pass').value
    if (localStorage.getItem('UsersLogin')) {
        const loginDeets = JSON.parse(localStorage.getItem('UsersLogin'))
        if (loginEmail === loginDeets.email && loginPass === loginDeets.password) {
            console.log('Login successful')
        } else {
            console.log('Wrong credentials')
        }
    } else {
        console.log('Not a registered user')
    }
}

In this login function you first need to check if there even is a UsersLogin property in the localStorage .在此登录 function 中,您首先需要检查localStorage是否UsersLogin属性。 If there is, then check if the inputs match whatever is stored in that UsersLogin property.如果有,则检查输入是否与存储在该UsersLogin属性中的任何内容匹配。 If it matches, then say "Login Successful" if it doesn't match then say "Wrong credentials".如果匹配,则说“登录成功”,如果不匹配,则说“凭据错误”。 If there is no UsersLogin property in the localStorage at all then say "Not a registered user".如果localStorage中根本没有UsersLogin属性,则说“不是注册用户”。

UPDATE AS PER REQUEST:根据要求更新:

If you want to keep the previously registered users in the localStorage and just update the UsersLogin property to include the the newly registered user then you can do it like so:如果您想将以前注册的用户保留在localStorage中,并且只需更新UsersLogin属性以包含新注册的用户,那么您可以这样做:

function UserRegistration() {
    let storedUsers = localStorage.UsersLogin ? JSON.parse(localStorage.UsersLogin) : [];
    const userData = {
        email: document.getElementById('register-email').value,
        password: document.getElementById('register-pass').value
    };
    storedUsers.push(userData);
    localStorage.setItem('UsersLogin', JSON.stringify(storedUsers));
    window.location.reload();
}

function loginUser() {
    const loginEmail = document.getElementById('login-email').value
    const loginPass = document.getElementById('login-pass').value
    if (localStorage.getItem('UsersLogin')) {
        const allStoredUsers = JSON.parse(localStorage.getItem('UsersLogin'));
        const matchedUser = allStoredUsers.filter(user => {
            return loginEmail === user.email && loginPass === user.password;
        })
        if (matchedUser.length) {
            console.log('Login successful')
        } else {
            console.log('Wrong credentials')
        }
    } else {
        console.log('Wrong credentials') // Don't say "Not a registered user"
    }
}

NOTE: You might have to clear the localStorage for the new functions to work, because localStorage.UsersLogin is now an array where it used to be an object , so it might throw an error if you don't clear it first.注意:您可能必须清除localStorage才能使新功能正常工作,因为localStorage.UsersLogin现在是一个array ,它曾经是一个object ,因此如果您不先清除它,它可能会引发错误。 Just run localStorage.clear() in the console.只需在控制台中运行localStorage.clear()

Also, I know I did this in the first block of code, but don't tell the user if a user profile exists or not (Don't log "Not a registered user"), because it's a security flaw.另外,我知道我在第一个代码块中这样做了,但不要告诉用户是否存在用户配置文件(不要记录“非注册用户”),因为这是一个安全漏洞。 It hints to the user about who is in your database and who is not.它向用户提示谁在您的数据库中,谁不在您的数据库中。 This is valuable information to a hacker or malicious actor.这对黑客或恶意行为者来说是有价值的信息。 Instead just say "Wrong credentials" again.而是再次说“错误的凭据”。

I think you are looking for something like this我想你正在寻找这样的东西

// For user registration 
const registerBtn = document.getElementById('register-btn')

function UserRegistration() {
  var userData = {
    email: document.getElementById('register-email').value,
    password: document.getElementById('register-pass').value
  };
  var usersr = JSON.parse(localStorage.getItem('Users')) || [];
  if(!usersr.some(user => user.email === userData.email)) {
   usersr.push(userData);
   localStorage.setItem('Users', JSON.stringify(usersr));
   location.reload()
   console.log(userData)
  }
  else {
    //email already registered
  }
}

// For user login 
const loginBtn = document.getElementById('login-btn')

function loginUser() {
  var usersl = JSON.parse(localStorage.getItem('UsersLogin')) || [];
  var usersr = JSON.parse(localStorage.getItem('Users')) || [];
  var loginData = {
    loginEmail: document.getElementById('login-email').value,
    loginPass: document.getElementById('login-pass').value
  };
  var currentUser = usersr.filter(user => user.email === loginData.loginEmail);
  if(currentUser.length > 0) {
    //current email is registered
    if(currentUser[0].password === loginData.loginPass) {
      //password do not match 
      return;
    }
    if(!usersl.some(user => user.email === loginData.loginEmail)) {
      // currently not logged in, so login
      usersl.push(loginData);
      localStorage.setItem('UsersLogin', JSON.stringify(usersl))
      console.log(usersl)
      location.reload()
    }
    else {
      // currently logged in
    }
  }
  else {
    // not registered email
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM