Sign Up problem in react native (about concurrency) - javascript

Hey I am doing a sign up form, where every time the username textinput is changed, I look at my DB if it is available or not (to change the icon color of the text input to red or green).
const checkUsername = async () => {
// Get username from input
const username = usernameInput.current.props.value;
let isUsernameAvailable = false;
if (!isEmpty(username)) {
const { firebase } = props;
// Check if the username is available on the database and valid
isUsernameAvailable =
(await firebase.checkUsername(username)) && validateUsername(username);
}
setIsUsernameAvailable(isUsernameAvailable);
};
I have my own firebase rules to create a username only if not exists, but sometimes, when I write really fast the input and click on the submit button, a user with a not available username is created.
This is the submit function:
const signUp = async () => {
// Do not try to sign up again if the user is currently signing up
if (isLoading) return;
const { firebase, toast } = props;
const username = usernameInput.current.props.value;
const email = emailInput.current.props.value;
const password = passwordInput.current.props.value;
const repeatPassword = repeatPasswordInput.current.props.value;
// It is too important to check that the username is not taken
await checkUsername(username);
const formError = validateForm(username, email, password, repeatPassword);
// Do not sign up if the form is incorrect
if (formError) {
// Show error message
toast.current.show(formError, 3500);
return;
}
// Start loading
setIsLoading(true);
// Try to create the user with the email and password
firebase
.createUserWithEmailAndPassword(email, password)
.then((currentUser) => {
// Get the username from the input
const username = usernameInput.current.props.value;
// Create a user with this username and the current user uid in the db
firebase.createUserWithUsername(username, currentUser.user.uid);
})
.catch((err) => {
if (err.code !== "auth/too-many-request") {
// Convert error code to message
const message = firebase.parseError(err.code);
// Show error message
toast.current.show(message, 3500);
// Finish loading
setIsLoading(false);
}
});
/*
Pd: It has no sense to make a query if the username, email and password
are not valid. We avoid making extra queries.
*/
};
Any ideas?

Related

Firebase Web Read from Real-Time Database

I'm trying to display the user's price that they entered in the database, but I'm getting "undefined' back instead of the value that was entered. I didn't get any errors in the console either. How can I fix this? I am using HTML, JavaScript, and CSS. I have provided a screenshot and my code.
Studio Dashboard JavaScript code:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const database = firebase.database();
const auth = firebase.auth();
//const auth = getAuth();
firebase.auth().onAuthStateChanged((user) => {
if (user) {
readData();
// ...
} else {
window.location.href = "login.html?error";
alert("No active user please sign or sign up.");
}
});
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => {
// Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
// Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}).catch(e => { console.log(e) })
}
function updatePrice() {
// Get data
numberInput = document.getElementById("numberInput").value;
const user = firebase.auth().currentUser;
// Enter database location
firebase
.database()
.ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne")
.update({
//studioName : studioName,
numberInput: numberInput,
});
}
You should use the on method instead of get
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).on('value', (snapshot) => {
//Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
//Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}, (e) => { console.log(e) })
}

checking browser local storage for item in array

I have created a login button that is supposed to take the Array stored in the browser local storage, read each item and check if the username and password written in the input boxes are inside the Array).
The Array is successfuly taken from storage, but when the code is supposed to read it and compare the items to the input for some reason it always says the input isn't in the Array. How could I fix that? Code follows:
const loginForm = document.getElementById("loginForm");
const loginButton = document.getElementById("loginButton");
const loginError = document.getElementById("loginError");
const registerForm = document.getElementById("registerForm");
const registerButton = document.getElementById( "registerButton");
const registerError = document.getElementById("registerError");
/*HERE IS THE PROBLEMATIC LOGIN BUTTON*/
loginButton.addEventListener("click", (e)=> {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
const user ={ username, password};
let checkUser =[];
checkUser = JSON.parse(localStorage.getItem("registred users"));
let checkUserInfo = checkUser.includes(user, 0);
if( checkUserInfo == true){
alert("Login sucessful!");
location.reload();
} else {
loginError.style.opacity = 2;
}
})
registerButton.addEventListener("click", (e)=> {
e.preventDefault();
const registerUsername = registerForm.registerUsername.value;
const registerPassword = registerForm.registerPassword.value;
const confirmPassword = registerForm.confirmPassword.value;
const registerEmail = registerForm.registerEmail.value;
const userData = {registerUsername, registerPassword};
let registredUserData = [];
if(registerPassword.length > 8 && registerPassword.match(/[a-z]+/) && registerPassword.match(/[A-Z]+/) && registerPassword.match(/[0-9]+/) && registerPassword.match(/[$##&!]+/) && registerPassword === confirmPassword && registerEmail.match(/[#/]+/ ) ){
registredUserData = JSON.parse(localStorage.getItem("registred users"));
registredUserData.push(userData);
localStorage.setItem("registred users",JSON.stringify(registredUserData));
location.reload();
} else {
registerError.style.opacity = 2;
}
})
You are comparing two objects for equality. Even though you use includes, it still checks if the value you put in is equal to an element in the array.
If you need to check for both username and password, loop through the array with some and see if the properties of one of the objects are equal to the provided input.
let checkUserInfo = checkUser.some(u => u.username === user.username && u.password === user.password);
Also keep in mind that this type of client side authentication is dummy auth for demonstration purposes only; it will not function as real authentication for any service.
You shouldn't use the includes to search for a similar object in an array of objects. You have to search one by one. You should use a filter type method like find() or some().
Your code would be something like:
/*HERE IS THE PROBLEMATIC LOGIN BUTTON*/
loginButton.addEventListener("click", (e)=> {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
const user ={ username, password};
let checkUser =[];
checkUser = JSON.parse(localStorage.getItem("registred users"));
let checkUserInfo = checkUser.some(item => item.username === user.username && item.password === user.password);
if( checkUserInfo == true){
alert("Login sucessful!");
location.reload();
} else {
loginError.style.opacity = 2;
}
})
Obs.: This is a extremely bad way to store password data. You should use some library that uses hash like bcryptjs.

Check for duplicates before saving them on database

I'm pretty new to coding and to Velo from Wix, therefore I need help.
I created a member's page, the page gets the pricing plan that the member subscribed to, and it shows a specific form to be submitted in order to set a dashboard according to the region he/she selects.
When the user submits the form, my code checks for duplicates like email and field values. If the user has already submitted it an error will appear telling the user that the form was already submitted, if the value is "" or equal to another one, another message will appear and tells the user to check the selection and make 3 different selections.
Well for the Free Plan where only one dropdown is shown, everything runs smoothly, for the Basic where I have 3 dropdowns nothing works. So... let' go to the code:
import wixData from 'wix-data';
import wixUsers from 'wix-users';
$w.onReady(function () {
console.log("Ready")
let user = wixUsers.currentUser
user.getPricingPlans()
.then ((pricingPlans) => {
let firstPlan = pricingPlans[0];
let planName = firstPlan.name;
if (planName == '7 DAY FREE TRIAL $0'){
$w('#text30').show();
$w("#text31").show();
$w('#dropdown1').show();
$w('#emailInput').show();
$w('#button1').show();
searchForDuplicityFreePlan();
}
if(planName == 'BASIC'){
$w('#text30').show();
$w("#text31").show();
$w('#dropdown2').show();
$w('#dropdown3').show();
$w('#dropdown4').show();
$w('#emailInput2').show();
$w('#button2').show();
searchForDuplicityBasicPlan();
}
});
});
async function searchForDuplicityFreePlan(){
$w("#dataset1").onBeforeSave(async() => {
let checkEmailFreeOk = await checkEmailFree();
let fieldCheck = $w("#dropdown1").value;
if(checkEmailFreeOk === false){
$w("#text32").text = "An error occurred. You have already submitted this form";
return false
}
if(fieldCheck === ""){
$w("#text32").text = "An error occurred. Please select your region of interest";
return false
}
})
}
async function checkEmailFree(){
let flagFree = true
await wixData.query('RegionSelectionQuizFree')
.eq('email', $w("#emailInput").value)
.find()
.then((result)=>{
if(result.items.length > 0)
flagFree = false
})
return await flagFree
}
async function searchForDuplicityBasicPlan(){
$w("#dataset2").onBeforeSave(async() => {
let checkEmailBasicOk = await checkEmailBasic();
let region1 = $w("#dropdown2").value;
let region2 = $w("#dropdown3").value;
let region3 = $w("#dropdown4").value;
const regions = new Set();
regions.add(region1);
regions.add(region2);
regions.add(region3);
regions.delete("");
if(checkEmailBasicOk === false){
$w("#text34").text = "An error occurred. You have already submitted this form";
return false
}
if (regions.size !== 3) {
$w("#text34").text = "An error occurred. Please select 3 different regions of interest";
return false
}
})
}
async function checkEmailBasic(){
let flagBasic = true
await wixData.query('RegionSelectionQuizBasic')
.eq('email', $w("#emailInput2").value)
.find()
.then((result)=>{
if(result.items.length > 0)
flagBasic = false
})
return await flagBasic
}

Receing null on activeuser after signing is done

I am using local storage to store username and password
I am getting null on active user after this line of code, I dont know why
console.log("I am the Active user: " + activeUser);
const menuChannelIcon = $(".menu-channel-icon");
const bellIcon = $(".bell-btn");
const uploadButtonIcon = $(".upload-btn");
const signInMainPageIcon = $(".signInMainPage");
const signUpMainPageIcon = $(".signUpMainPage");
const signOutMainPageIcon = $(".signOutMainPage");
const videoSectionMainPage = $(".video-section");
const signin = () => {
console.log("signin button clicked")
if (localStorage.getItem("formData")) {
// as long as you are getting items from the local storage... do..
JSON.parse(localStorage.getItem("formData")).forEach((data) => {
let x = $("#signEmail").val();
let z = $("#signinPassword").val();
if (data.email == x && data.pwd == z) {
isLogged = true;
activeUser = localStorage.getItem(email);
console.log("I am the Active user: " + activeUser);
menuChannelIcon.show();
bellIcon.show();
uploadButtonIcon.show();
signInMainPageIcon.hide();
signUpMainPageIcon.hide();
signOutMainPageIcon.show();
singIn_formContainer.hide();
videoSectionMainPage.show();
console.log("You are LOGGED");
}
});
}
};
Edit: email and pwd are set during signup
Answer posted by Barmar in the comments:
localStorage.getItem("email")
Alternative answer:
Shouldn't the active user be x when the email and password match something from formData? Why are you getting the active user from local storage?

Sign in user if is register (Firebase facebook/google auth)

i´m want to check if the user who want to sign in using the facebook or google auth in to my web app is register on the real time database of firebase, so the idea is after the user press the button of sign in with facebook/google, first check in to the real time database if the uid is already on the real time database before redirect the user to another URL, for this i´m using the next function:
app.auth = function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var users_ref = firebase.database().ref('dream_wedding_users');
var register_user;
var register = false;
users_ref.on('value', function(snapshot) {
register_user = snapshot.val();
});
$.each(register_user, function(index, val){
if(user.uid === index){
register = true;
}
})
if(!register){
firebase.auth().signOut();
$('#login').modal('hide');
$('#modal_register').modal('show');
return false;
}else{
$(window).attr('location', 'http://localhost/wedding/en/gallery_en.php');
}
}
});
}
and for the auth function just the regular auth function for facebook and google that attach to a button.
app.facebook_login = function(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
console.log(error)
});
}
app.google_login = function(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
firebase.auth().signInWithRedirect(provider);
}).catch(function(error) {
console.log(error);
});
}
my problem is the next one, when i click sign in facebook or google, first login the user, then redirect the user, then check is the user is register on the real time data base and then logout the user if is not register and then show the modal. i don´t want that redirect the user i want that check if the user is register and then show the modal of "register" if the user is not register without redirect, and redirect if the user is register.
You want to add a unique user , if it is already not registered right ?
here is the valid way:
var usernew = result.additionalUserInfo.isNewUser
console.log('Is this a new user ? => ' + usernew );
complete code is as follows:
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var usernew = result.additionalUserInfo.isNewUser;
console.log('Is this a new user ? => ' + usernew );
if (usernew == true) {
NewUser();
}
var token = result.credential.accessToken;
user = result.user;
// alert(JSON.stringify(user.photoURL))
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
add user if it is not registered:
function NewUser(){
firebase.database().ref('/users').push({
Name : 'Johnson'
Age : '22'
})
}

Categories