pull out data from array in localStorage - javascript

I have a function that takes data from an input and saves it as data in an array during registration. Now I want another function to check during login if the data exists and if it matches. How can I do this using javascript only?
In short, I need a function that checks if the data entered by the user exists and if so, logs him in.
function saveData() {
let name, email, password;
name = document.getElementById("username").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
let user_records = new Array();
user_records = JSON.parse(localStorage.getItem("users"))
? JSON.parse(localStorage.getItem("users"))
: [];
if (
user_records.some((v) => {
return v.email == email;
})
) {
alert("Email wykorzystany");
} else {
user_records.push({
name: name,
email: email,
password: password,
});
localStorage.setItem("users", JSON.stringify(user_records));
}
}
I know that this is not how registration should be done. I am just doing it to learn new things.

this is a basic login, when you verify that the emmail and password are right, you can do wathever you want
function checkData() {
const name = document.getElementById('username').value;
const password = document.getElementById('password').value;
let user_records = JSON.parse(localStorage.getItem('users')) || [];
if (
user_records.find((user) => {
return user.name == name && user.password == password;
})
) {
alert('Logged in');
// do your things here
} else {
alert('wrong email or password');
// do your things here
}
}
<input id="username" />
<input id="password" />
<input type="submit" value="submit" onClick="checkData()" />
Extra:
This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world

function saveAndTestUser() {
// here use const as they are not updated
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Get all the records of the users
// prefer camelcase : not a rule though but it's better this way
const storedUsers = localStorage.getItem('users')
// if there are no stored users then assign empty array
// so that we don't get unexpected errors
const userRecords = storedUsers ? JSON.parse(storedUsers): []
// Checking if email already exists
if(userRecords.some(user => user.email === email)){
alert("user already exists")
return false; // stops the function execution
}
// If email doesn't exists then the code below will be executed
// Similar to if-else
// Add current record to existing records
const newRecords = [...storedUsers, {name, email, password}]
// Set the new record to storage
localStorage.setItem("users", JSON.stringify(newRecords));
}

Related

How do I create a user with a name?

I've already tried several tutorials, but I still couldn't create a user with a name to, for example, send the email in the tag %DISPLAY_NAME%
Here is the code I use to register users if it helps to solve the problem, if you have more doubts please send them in the comments
function register () {
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value
auth = document.getElementById('auth').value
favourite_song = document.getElementById('favourite_song').value
milk_before_cereal = document.getElementById('milk_before_cereal').value
// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
alert('Email or Password is Outta Line!!')
return
// Don't continue running the code
}
if (validate_field(auth) == false || validate_field(favourite_song) == false || validate_field(milk_before_cereal) == false) {
alert('One or More Extra Fields is Outta Line!!')
return
}
// Move on with Auth
auth.createUserWithEmailAndPassword(email,auth, password)
.then(function() {
// Declare user variable
var user = auth.currentUser
// Add this user to Firebase Database
var database_ref = database.ref()
// Create User data
var user_data = {
email : email,
full_name : full_name,
favourite_song : favourite_song,
milk_before_cereal : milk_before_cereal,
last_login : Date.now()
}
// Push to Firebase Database
database_ref.child('users/' + user.uid).set(user_data)
// DOne
alert('User Created!!')
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}

Check if user is already existed in localStorage

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
const btnSignup = document.getElementById("btn-signup");
btnSignup.onclick = function () { // when mouse click "signup" button
const first_name = firstName.value; // getting the value of firstName and so on..
const last_name = lastName.value;
const e_mail = newEmail.value;
const pass_word = newPassword.value;
if (first_name && last_name && e_mail && pass_word) {
//set user input into JSON
let user_data = {
firstName: first_name,
lastName: last_name,
email: e_mail,
password: pass_word
}
//get to localstorage if there is existing user ||or make empty array[]
let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
//ipush ang new user sa array
clientsArr.push(user_data);
//save to localstorage
localStorage.setItem('users', JSON.stringify(clientsArr));
}
// location.reload();
else if (user_data === localStorage.getItem('users')) { // THIS IS THE CODE THAT I AM TRYING
alert("User already existed");
}
};
i am trying to put an error message something on the screen or alert thingy on the browser, this code actually works, the problem is how to identify if there is existing user inside the local storage. what i'm trying to say is, your "login" will not accept if there is existing user inside the memory. thank you! I put a comment to the code that i'm trying to run.
A few points:
JavaScript compares objects by memory reference (location on RAM).
let variables are bound to the lexical scope {}. Hence, user_data will not be available in the second else if statement.
Bonus: use the early exiting to keep the code clean.
Use a unique identifier such as an id. In the example, I am converting the objects to a string and compare them.
// Fields
const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
// Button
const btnSignup = document.getElementById("btn-signup");
function signUp() {
const first_name = firstName.value;
const last_name = lastName.value;
const e_mail = newEmail.value;
const pass_word = newPassword.value;
// If either of the values is empty
if (!first_name || !last_name || !e_mail || !pass_word) {
return;
}
//set user input into JSON
let user_data = {
firstName: first_name,
lastName: last_name,
email: e_mail,
password: pass_word
}
// convert to string
let user_data_str = JSON.stringify(user_data)
//get to localstorage if there is existing user ||or make empty array[]
let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
// Convert to string
// Search the list if
const userExists = clientsArr.find(user => JSON.stringify(user) === user_data_str);
if (userExists) {
return alert('User already exists')
}
//ipush ang new user sa array
clientsArr.push(user_data);
//save to localstorage
localStorage.setItem('users', JSON.stringify(clientsArr));
}
// Attach listener
btnSignup.addEventListener('click', signUp);
<input id="firstName" />
<input id="lastName" />
<input id="newEmail" />
<input id="newPassword" />
<button id="btn-signup">Sign up</button>
If you are trying to check if user already exists before adding to the "users" in the localStorage, you could do something like:
const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
const btnSignup = document.getElementById("btn-signup");
btnSignup.onclick = function () {
const first_name = firstName.value;
const last_name = lastName.value;
const e_mail = newEmail.value;
const pass_word = newPassword.value;
// Only get localstorage item once
let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
// Only execute those lines if we have the data that we need
if (first_name && last_name && e_mail && pass_word) {
let user_data = {
firstName: first_name,
lastName: last_name,
email: e_mail,
password: pass_word
}
// Check if the user already exists to show an alert or add it to the list
if(clientsArr.includes(user_data)) {
alert("User already existed");
} else {
clientsArr.push(user_data);
localStorage.setItem('users', JSON.stringify(clientsArr));
}
}
};

Display user's data in an html tag after reading them from firebase for webapps

This is the structure of my database, every user is in a child with value as that of their user-id
This is the code i am using
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).child("userName").once('value').then(function(snapshot) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
$("#name-tag").append(username);
});
I want the userName value and have to display it
First change the way you authenticate the user then create a proper reference to the database.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var userDBRef = firebase.database().ref().child("User Database").child(user.uid);
userDBRef.on("value", function(userDB){
$("#para-id").append(userDB.child("userName").val());
});
} else {
// No user is signed in.
console.log("no user!!!");
}
});
Try this code :
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' +
userId).child("userName").once('value').then(function(snapshot) {
var username = snapshot.val() ? snapshot.val().username) : 'Anonymous';
$("#name-tag").append(username);
});
If snapshot.val() return null then usename will be 'Anonymus'

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

How to get just the first name when a user logs in using social media with firebase?

Here is the code that I am using to get the details of the user when they log in using google, facebook or twitter.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var uid = user.uid;
var phoneNumber = user.phoneNumber;
var providerData = user.providerData;
user.getToken().then(function(accessToken) {
console.debug('user', user);
document.getElementById('name').textContent = displayName;
document.getElementById("avatar").src = photoURL;
});
} else {
console.log('not logged in');
}
});
Then in the html by writing <p id="name"></p> the entire name of the user is displayed.
How do I display just the first name of the user?
You can do it like this;
document.getElementById('name').textContent = (displayName.split(' '))[0];
First and last name are available from most social providers just after you log in, but you will need to save them to your database as Firebase does not. What each provider calls first and last name varies, though.
Documentation at https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signinwithpopup
firebase.auth
.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then((user) => {
const firstName = user.additionalUserInfo.profile.given_name;
const lastName = user.additionalUserInfo.profile.family_name;
});
firebase.auth
.signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
.then((user) => {
const firstName = user.additionalUserInfo.profile.givenName;
const lastName = user.additionalUserInfo.profile.surname;
});

Categories

Resources