Ways to verify the existence of a user in the browser's local storage

I have a project task to create a user registration and login form that utilizes local storage to store data. The functionality is working correctly when a new user registers by saving their email address and password in localStorage.

However, I am facing a challenge in comparing data when an unregistered user attempts to log in compared to a registered user trying to log in.

When a registered user logs in, the input values should be compared with the stored data in localStorage, and if they match, it should display "login Successful"; otherwise, it should prompt "Not a registered user."

My implementation involves using JavaScript for this purpose. Any assistance on this matter would be greatly appreciated.

Below is the code snippet:

var userData;
var usersr;
var loginData;
var usersl;

// 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);
}

// 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();
}

Answer №1

Within the code block, there is a significant amount of unnecessary code. To streamline and improve functionality, consider utilizing the following functions:

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

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

When using the login function, it is crucial to first verify the existence of the UsersLogin property within the localStorage. If present, compare the input values with those stored in the UsersLogin property. If they match, display "Login Successful"; otherwise, indicate "Wrong credentials". In cases where the UsersLogin property does not exist at all in the localStorage, notify the user as "Not a registered user".

REQUESTED UPDATE:

To maintain previously registered users in the localStorage while updating the UsersLogin property with new registrations, follow these steps:

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 authenticateUser() {
    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 => loginEmail === user.email && loginPass === user.password);

        if (matchedUser.length) {
            console.log('Login successful');
        } else {
            console.log('Incorrect credentials');
        }
    } else {
        console.log('Incorrect credentials');
    }
}

NOTE: It may be necessary to clear the localStorage for the updated functions to operate smoothly. Previous errors could arise due to converting localStorage.UsersLogin into an array from an object. Simply execute localStorage.clear() in the console.

As mentioned earlier, refrain from disclosing the presence or absence of user profiles in the database (Avoid logging "Not a registered user"). Such information can be utilized by potential threats. Instead, consistently inform users of "Incorrect credentials" without revealing specific details. 😌

Answer №2

Congratulations on completing the registration code! It's now time to develop the login functionality and I've ensured that duplicate users are handled.

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

Answer №3

Here's a possible solution that might meet your needs

// Handling user registration 
const registerButton = document.getElementById('register-button')

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

// Managing user login 
const loginButton = document.getElementById('login-button')

function handleLogin() {
  var loggedInUsers = JSON.parse(localStorage.getItem('LoggedInUsers')) || [];
  var registeredUsers = JSON.parse(localStorage.getItem('RegisteredUsers')) || [];
  var loginData = {
    email: document.getElementById('login-email').value,
    password: document.getElementById('login-password').value
  };
  var currentUser = registeredUsers.filter(user => user.email === loginData.email);
  if(currentUser.length > 0) {
    //current email is registered
    if(currentUser[0].password === loginData.password) {
      //passwords do not match 
      return;
    }
    if(!loggedInUsers.some(user => user.email === loginData.email)) {
      //not logged in yet, so log in now
      loggedInUsers.push(loginData);
      localStorage.setItem('LoggedInUsers', JSON.stringify(loggedInUsers))
      console.log(loggedInUsers)
      location.reload()
    }
    else {
      //already logged in
    }
  }
  else {
    //email not registered
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Dashboard Framework with a personalized editing menu option

I am currently using the Angular Dashboard Framework (sdorra) and I would like to customize the edit menu. https://i.sstatic.net/I9jDI.png By default, clicking on the menu allows me to add a widget, edit the dashboard, save, and discard changes as shown ...

Executing asynchronous functions that invoke other asynchronous functions

I'm facing an issue with executing a sequence of asynchronous functions inside an array. When I call the functions individually, it works perfectly as shown in the example below: function executeAll(string) { return new Promise(function (resolv ...

When a specific condition is fulfilled, I must retrieve a random response from a designated array

I'm looking for a way to create a system where users can select multiple items and then generate a random answer from those selected options. Currently, I have a setup that requires manual input of options in a comma-separated format, but I want to st ...

Matching wildcard paths using Express

Seeking help with routing in Express. I am trying to have both /m/objectID and /m/someslug/ObjectID directed to the same function. My current setup is as follows: app.get("/m/:id", ...); app.get("/m/(.*)/:id", ...); The first route is working properly, b ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

When running tests in Jest, the error "TypeError: _enzymeAdapterReact.default is not a constructor

I'm encountering an issue while testing a react-native component with jest and enzyme TypeError: _enzymeAdapterReact.default is not a constructor Below are my development dependencies: "@babel/core": "^7.12.10", "@ba ...

How can I effectively set up and utilize distinct npm modules on my local environment?

A React Native component I have created lives in a separate folder with its own package.json file, and now I want to use it in another project. The component named MyComponent is located in Workspace/MyComponent and has specific dependencies listed in its ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...

Having trouble with WordPress jQuery Click function. Would greatly appreciate some assistance :)

There seems to be a mix of working and non-working jQuery code. Specifically, the click function is not functioning properly in this case. Here is an example of the code that works: $j=jQuery.noConflict(); // Using jQuery with $j(...) $j(document ...

Should objects passed as props be modified in Vue.js components?

I've observed that in Vue, object fields passed as Props can be changed, and these changes reflect in the parent component. Is this considered a bad practice? Should it be avoided, or is it acceptable to use? What are the potential pitfalls of this a ...

Using Ajax to dynamically load Wordpress post details and content into a designated div element

I have saved the post-id information in a data-* attribute, and I want to display this content within a div using the &.ajax() function. Below is the code I am currently working on: A list item displaying the post thumbnail <li class="homus-par ...

Using $.when with an Array of Promises

After searching for similar questions, I came across one that was almost exactly what I needed. However, it lacked error handling, which led me to encounter some issues while trying to implement it. My objective is to create a function that takes an array ...

Leveraging React's State Values and Props

Can you help me with a React component challenge? I have two components that I need to work with: <select> <mytable> I want to build a new component called <myInterface>. The state of <myInterface>, let's call it S, needs to ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

Tips for making a range slider in react-native

Check out my range slider I'm having trouble with changing values by clicking on them. Is there a way to enable sliding the range slider instead? Thanks for any help. ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Issues with WordPress forms are causing frustration

Looking for some assistance here. I am in the process of creating a one-page WordPress theme and I am struggling with getting the contact form to submit without reloading the page. All my code is in the index.php file. The PHP code for form submission is ...

Using Object.create to establish multiple prototypes in JavaScript

I am trying to have my child object inherit the prototypes of multiple parents, but the following methods do not seem to work: child.prototype = Object.create(parent1.prototype, parent2.prototype); and also this: child.prototype = Object.create(parent1 ...

Sleek transition-ready zoom functionality for THREE JS with clickable controls

Hey there, I've been attempting to animate a transition between scenes in THREE js for quite some time now. I have successfully cleared the scene and recreated the next one, but the transition between them is proving to be quite challenging. I have cr ...

Verifying the invocation of a callback function through the use of $rootScope.$broadcast and $scope.$on

I have been testing to see if a callback was called in my controller. Controller (function () { 'use strict'; angular .module('GeoDashboard') .controller('CiudadCtrl', CiudadCtrl); CiudadCtrl.$i ...