How do I create a user with a name? - javascript

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

Related

pull out data from array in localStorage

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

snapshot.val().users.filter is not a function

database()
.ref('/')
.once('value')
.then(snapshot => {
var user = snapshot.val().users.filter(x => x.mail == mail)[0];
if (user != undefined && user != null)
{
ToastAndroid.show("User is there !", ToastAndroid.SHORT);
}
else
{
//Add user
}
I want to search this user with mail address and if the user is not there i will add it.But I get this error.
TypeError: snapshot.val().users.filter is not a function. (In 'snapshot.val().users.filter(function (x) { return x.mail == mail; })', 'snapshot.val().users.filter' is undefined)
As mentioned in the comments NEVER try to load all data to filter it on the client side. You can use orderByChild query to filter on the database to a specific reference in users to get only the one with the email you search for. The code would look something like this:
database()
.ref('/users')
.orderByChild('email')
.equalTo(email)
.limitToLast(1)
.once('value')
.then(snapshot => {
var user = snapshot.val()
if (user != undefined && user != null)
{
ToastAndroid.show("User is there !", ToastAndroid.SHORT);
}
else
{
//Add user
}

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

When creating a user with email, how to add elements in DB in Firebase in Javascript

So i'm new to using Firebase and I have been looking at the Firebase documentation but I haven't found how to do the following:
The user puts the following inputs: username, email, password, confirm password.
When I call the "createUserWithEmailAndPassword", if it works, I want at the same time to create entries in the DB in Firebase. I tried writing the following line:
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).then(function(){
//do what I want
}).catch(function (error) {})
But it doesn't work. What am I doing wrong?
Or do you have any suggestions as to how to add additional elements in the entry User using the uid that is created by the authentication method?
function createUser() {
//instance of database Firebase
var database = firebase.database();
//Get inputs from user
var userUsername = document.getElementById("usernameCreation_Field").value;
var userEmailCreate = document.getElementById("emailCreation_field").value;
var userPasswordCreate = document.getElementById("passwordCreation_field").value;
var userPassword2Create = document.getElementById("passwordCreation2_field").value;
if (userPasswordCreate == userPassword2Create && userUsername.length > 0) {
//If passwords match try to create user
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).catch(function (error) {
// Handle Errors here when creating account
var errorCode = error.code;
var errorMessage = error.message;
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = errorMessage;
});
//Passwords don't match
} else if(userUsername.length == 0){
document.getElementById('createSuccess').innerHTML = 'Username must be filled!';
document.getElementById('createSuccess').style.display = 'block';
} else {
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = 'Passwords don\'t match!';
}
}
//Add new user to database
function setUserData(userId, username, email){
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
topScore : topScore
});
}
Thank you in advance for your time!
Your code is not calling setUserData anywhere, so that would definitely explain why nothing is written to the database.
You're probably looking to call if from the then of createUser...:
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).then(function(userCredential) {
setUserdata(userCredential.user.uid, userUsername, userEmailCreate);
}).catch(function (error) {
// Handle Errors here when creating account
var errorCode = error.code;
var errorMessage = error.message;
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = errorMessage;
});

Categories

Resources