Firebase still isn't saving user info to firestore after auth - javascript

I found a tutorial on how to save the user's data under the uid in firestore. My function successfully retrieves the data and authenticates it, but it skips the firestore save function and jumps to the next window. I have two questions, why is it skipping the store in firebase function and why isn't reading the newly authenticated user as the current user when I set it and go to the next window? Sorry for all the similar questions, I'm trying different ways to do this and none have worked for me so far. I have provided my code below.
JS:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth();
const db = firebase.firestore().collection("/studiopick/studios/users");
const element = document.querySelector("form");
element.addEventListener("submit", (event) => {
event.preventDefault();
// renamed from newStudio
// don't use alert - it blocks the thread
console.log("debug: retrieving data... please wait");
// Get data
(studioName = document.getElementById("studioName").value),
(email = document.getElementById("email").value),
(password = document.getElementById("password").value),
(firstName = document.getElementById("firstName").value),
(lastName = document.getElementById("lastName").value),
(phoneNumber = document.getElementById("phoneNumber").value);
console.log({ studioName, firstName, email }); // note added braces here
// Validate input fields
if (!validate_email(email) || !validate_password(password)) {
// TODO: replace this alert with updating the form with an error message
alert("Error with email or password");
return false; // cancel submission
}
if (
!validate_field(firstName) ||
!validate_field(lastName) ||
!validate_field(phoneNumber) ||
!validate_field(studioName)
) {
// TODO: replace this alert with updating the form with an error message
alert("One or More Extra Fields is Outta Line!!");
return false; // cancel submission
}
console.log("Info grab successful");
// creates the user, and waits for it to finish being created
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(function (userCredential) {
usersRef.doc(`${userCredential.user.uid}`).set({
studioName: studioName,
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber,
uid: userCredential.user.uid,
});
})
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == "auth/weak-password") {
alert("The password is too weak.");
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
const uid = firebase.auth().currentUser;
// once the above tasks succeed, navigate to the dashboard.
window.location.href = "studiodash.html?id=" + uid;
return false;
});
// Validate Functions
function validate_email(email) {
expression = /^[^#]+#\w+(\.\w+)+\w$/;
if (expression.test(email) == true) {
// Email is good
return true;
} else {
// Email is not good
return false;
}
}
function validate_password(password) {
// Firebase only accepts lengths greater than 6
if (password < 6) {
return false;
} else {
return true;
}
}
function validate_field(field) {
if (field == null) {
return false;
}
if (field.length <= 0) {
return false;
} else {
return true;
}
}

Ended up figuring it out myself. Hope this helps someone:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log("firebase ===", firebase);
// Initialize variables
const auth = firebase.auth();
const db = firebase.firestore().collection("/studiopick/studios/users");
const element = document.querySelector("form");
element.addEventListener("submit", (event) => {
event.preventDefault();
// renamed from newStudio
// don't use alert - it blocks the thread
console.log("debug: retrieving data... please wait");
// Get data
(studioName = document.getElementById("studioName").value),
(email = document.getElementById("email").value),
(password = document.getElementById("password").value),
(firstName = document.getElementById("firstName").value),
(lastName = document.getElementById("lastName").value),
(phoneNumber = document.getElementById("phoneNumber").value);
console.log({ studioName, firstName, email }); // note added braces here
// Validate input fields
if (!validate_email(email) || !validate_password(password)) {
// TODO: replace this alert with updating the form with an error message
alert("Error with email or password");
return false; // cancel submission
}
if (
!validate_field(firstName) ||
!validate_field(lastName) ||
!validate_field(phoneNumber) ||
!validate_field(studioName)
) {
// TODO: replace this alert with updating the form with an error message
alert("One or More Extra Fields is Outta Line!!");
return false; // cancel submission
}
console.log("Info grab successful");
// creates the user, and waits for it to finish being created
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async (userCredential) => {
console.log("userCredential ===", userCredential);
var usersRef = db;
await usersRef.doc(`${userCredential.user.uid}`).set({
studioName: studioName,
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber,
uid: userCredential.user.uid,
});
console.log("firebase.auth().currentUser ===", firebase.auth().currentUser.uid);
const uid = firebase.auth().currentUser.uid;
// once the above tasks succeed, navigate to the dashboard.
window.location.href = "studiodash.html?id=" + uid;
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == "auth/weak-password") {
alert("The password is too weak.");
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
return false;
});
// Validate Functions
function validate_email(email) {
expression = /^[^#]+#\w+(\.\w+)+\w$/;
if (expression.test(email) == true) {
// Email is good
return true;
} else {
// Email is not good
return false;
}
}
function validate_password(password) {
// Firebase only accepts lengths greater than 6
if (password < 6) {
return false;
} else {
return true;
}
}
function validate_field(field) {
if (field == null) {
return false;
}
if (field.length <= 0) {
return false;
} else {
return true;
}
}

Related

Firebase web realtime database not updating

I am trying to update my firebase realtime database with user info when I am creating new user through firebase password authentication. And on successful sign in I am moving to another page. The problem is that my database is not getting updated in the above scenario however if stay in the login page and don't change to any other url; the database gets updated.
Here's my create user code
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
if (user !== null) {
const db = firebase.database();
db.ref("/").set({
uid: user.uid,
});
}
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
// ..
});
And here's where I'm switching to another page,
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
console.log(user);
//If I remove the below line, database is updated
window.location.href = "../html/home.html";
// ...
} else {
// User is signed out
// ...
console.log("not logged in");
}
});
This calls is asynchronous:
db.ref("/").set({
uid: user.uid,
});
That means that the code continues to run after the set() function returns, and asynchronously sends the data to the database. But when you change window.location, it interrupts this write operation. That's also why it works when you don't send the user to a new location: the write operation can then complete without interruption.
A quick simple fix is to flag when you're updating the database:
isCreatingUser = true; // 👈 Flag that we're creating a user
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
var user = userCredential.user;
if (user !== null) {
const db = firebase.database();
db.ref("/").set({
uid: user.uid,
}).then(() => {
isCreatingUser = false; // 👈 We're done
window.location.href = "../html/home.html"; // 👈 Navigate away
}).catch((e) => {
isCreatingUser = false; // 👈 We're done
throw e;
})
}
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
// ..
isCreatingUser = false; // 👈 We're done
});
And then:
firebase.auth().onAuthStateChanged((user) => {
if (user && !isCreatingUser) {
...
You'll probably need some more synchronization, but that's the gist of it.

firebase login authentication gives me that email must be a valid string

It always gives me "first argument (email) must be a valid string" and it doesn't login
i don't know if the problem is in the js code but im pretty sure it's not in the html .
and another question .. do i need the " onAuthStateChanged " function?
<script>
var rightAccount = 0;
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn();
function SignIn(email,password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
authStateListener();
rightAccount = 1;
//Signed in
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
alert(errorMessage);
});
};
function authStateListener() {
// [START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
currentUser = user;
console.log(currentUser.email + " has logged in")
} else {
// ...
}
});
// [END auth_state_listener]
};
if (rightAccount == 1) {
setTimeout(function Redirect() {
window.location.replace("Website/homePage.php");
}, 2000)
}
</script>
You must pass email and password values to function. Otherwise it will be give error.
...
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn(email, password); // <-- Here pass them
...

Firebase: How to forward to a new webpage if authentication is correct?

In my web app, the authentication process is handled via firebase. I am using firebase javascript api for this process. In my HTML, I am passing the username and password to login. Those information are captured by Javascript and sent to firebase.
</head>
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/5.9.4/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.9.4/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.4/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxx-xxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxx-xxxxxxxxxx.firebaseio.com",
projectId: "xxxxxxxx-xxxxxxxxx",
storageBucket: "xxxxxxxxxx-xxxxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(config);
</script>
<script type="text/javascript">
function toggleSignIn()
{
if (firebase.auth().currentUser) {
// [START signout]
alert('same user');
//firebase.auth().signOut();
// [END signout]
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
alert('hi');
// [END authwithemail]
}
document.getElementById('quickstart-sign-in').disabled = true;
}
</script>
</head>
Here I capture the errors, which is fine. But if the username and password are correct, I need to forward to a servlet named LoadUsers which will provide the next UI for the logged in user.
How can I do this?
There is then in the signInWithEmailAndPassword. Just check below.
function toggleSignIn()
{
if (firebase.auth().currentUser)
{
// [START signout]
alert('same user');
//firebase.auth().signOut();
// [END signout]
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser)
{
window.location.href = 'LoadSellPendingApprovals'
})
.catch(function(error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode === 'auth/wrong-password')
{
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
alert('hi');
// [END authwithemail]
}
document.getElementById('quickstart-sign-in').disabled = true;
}

Firebase create user with email and password and put data in database

I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.
registerUser.addEventListener('click', function (user) {
event.preventDefault();
closeRegisterForm();
email = registerEmail.value;
password = registerPassword.value;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function (event) {
var ref = firebase.database().ref("users").child(user.uid).set({
email: user.email,
uid: user.uid
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
});
Hi I was having the exact same problem. But i used a local function to solve it. Something like this:
createNewUser(form) {
//create new user with provided data of the form
this.afAuth.auth.createUserWithEmailAndPassword(form.email, form.password)
.then(function(firebaseUser) {
console.log("User " + firebaseUser.uid + " created successfully!");
updateFirestore(form, firebaseUser.uid);
return firebaseUser;
}).catch(function(error) {
alert(error)
});
function updateFirestore(form, uidNewUser) {
//push data into firestore using the uid provided
let data = {};
data['mail'] = form.email;
data['name'] = form.name;
//se empuja el arreglo data en el documento del usuario
this.afs.collection('users').doc(uidNewUser).set(data);
console.log(data, uidNewUser);
}
}
You refer to user.uid and user.email but never define user. The return type of sign in method createUserWithEmailAndPassword is a user but you define it as event. Also make sure you wait for the db write promise to resolve and catch any errors there as Frank advised.
Working for me:
const val = this.signupForm.value;
this.authService.doRegister(val)
.then(res => {
this.msg = 'You have registered successfully!';
this.msgType = 'success';
this.authService.updateUser(val.name, null)
.then(suc => {
const created = firebase.firestore.FieldValue.serverTimestamp();
const user = {
first_name: val.name,
last_name: '',
email_personal: val.email,
created: created,
updated: created
};
this.userCollection = this.afs.collection<User>('users');
this.userCollection.doc(suc).set(user);
}, err => {
// console.log(err);
});
this.router.navigate(['/']);
}, err => {
this.msg = err.message;
})
const [phone, setPhone] = useState()
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleSignUp = async () => {
if (!email == ' ' && !password == ' ') {
try {
const result = await auth().createUserWithEmailAndPassword(email, password)
firestore()
.collection('Users')
.doc(result?.user?.uid)
.set({
email: result?.user?.email,
phoneNumber: phone,
uid: result?.user?.uid,
displayName: result?.user?.email.split('#')[0],
})
.then(() => {
alert('User added!');
});
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
Alert.alert('That email address is already in use!');
}
else if (error.code === 'auth/invalid-email') {
Alert.alert('That email address is invalid!');
}
else {
Alert.alert(error)
}
}
} else {
Alert.alert("Please Enter Your All Field");
}
}

How to check if there's no errors in authentication process in Firebase Web?

I'm new to Web Development, especially to Firebase.
I'm trying to check if there are no errors while creating a user in Firebase Authentication system, so I can put this user into Database.
Here's my code:
function register() {
var firebaseRef = firebase.database().ref();
var shaObj = new jsSHA("SHA-256", "TEXT")
shaObj.update(passwordField.value)
//console.log(hash)
var email = emailField.value
var password = shaObj.getHash("HEX")
if (isBarber != null) {
if (email != "" && password != "") {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
$('#errorMsg').show();
$('#errorMsg').text(error.message);
if (error === null) {
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}
});
} else {
alert('Email or password fields are empty')
}
} else {
alert('Select your role')
}
}
createUserWithEmailAndPassword works properly and creates a user, but I don't know how to check if there are no errors so I could add this user to database.
Thanks a lot
You can use then() to action on a successful registration as follows:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Registration is successful
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}).catch(error) {
//Registration unsuccessful
$('#errorMsg').show();
$('#errorMsg').text(error.message);
});

Categories

Resources