简体   繁体   中英

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. If a new user registers it stores their email address and password in localStorage which is working as expected.

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".

I am using JavaScript to do this. 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 . If there is, then check if the inputs match whatever is stored in that UsersLogin property. 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".

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:

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. Just run localStorage.clear() in the console.

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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