I am trying to create a document in firestore in the path "users" and the name user.uid every time a new user signs up. In this document I want to store some attributes such as firstname, lastname, email and uid. The issue i have is that the auth works perfectly, but no document is created.
var email = signupEmail.value;
var password = signupPassword.value;
var firstname = signupFirstname.value;
var lastname = signupLastname.value;
var password_repeat = signupRepeatPw.value;
const auth = getAuth();
const db = getFirestore();
if (firstname != "" && lastname != "") {
if (password == password_repeat) {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
const user = userCredential.user;
await setDoc(doc(db, "users", user.uid), {
firstName: firstname,
lastName: lastname,
accountLevel: 0,
UID: user.uid,
email: email,
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
})
.catch((error) => {
const errorCode = error.code;
var errorMessage = error.message;
Any help will be very appreciated as I have been stuck on this for quite some time!
Best regards,
Isak
If anyone else is struggling with this issue, I fixed my mistake.
The problem was that I redirected the user to their profile page when the auth state changed, from another script tag running simaltaniously. This led to the code redirecting the user before the promise was complete and therefore it does not update the db.
Best regards,
Isak
Related
I am trying to register user with createUserWithEmailAndPassword function, which logically receives only email and password. But I want also to write fullname field of user. Can you tell me what is the way of doing this? Thanks
But I want also to write fullname field of user.
I make the assumption that you want to update the displayName property of the user Object.
Do as follows, by using the updateProfile() method:
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
return user.updateProfile({displayName: "Your name"});
})
.then(() => {
console.log("Profile updated successfully!");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
});
Upon sign up, I want to add a user to a "users" collection using the corresponding userID. Under this userID would be the user's data, such as name, email, posts, etc...
Here is my code:
I get no errors, and the user is created and is visible in firebase auth. However the user is not added to the firestore database.
firebase.initializeApp(config);
const auth = firebase.auth();
const db = firebase.firestore();
auth.createUserWithEmailAndPassword(email, pass).then(cred => {
const userId = cred.user.uid;
const userData = {
firstName: firstName,
lastName: lastName,
email: email
};
db.collection("users").doc(userId).set(userData).then(() => {
console.log("User successfully added to the DB!");
})
.catch((e) => {
console.log("Error adding user to the DB: ", e);
});
}).then(() => {
console.log('User created! - ' + email);
}).catch(e => {
console.log(e.message);
txtErrMsg.classList.remove('hide');
txtErrMsg.innerHTML = e.message;
});
It just seems like I am not able call the DB inside of the auth.createUserWithEmailAndPassword(email, pass) function. If I put the db.collection("users").doc(userId).set(userData) call with some dummy data outside of the auth.createUserWithEmailAndPassword(email, pass) function, then the data appears in the firestore DB.
FYI: I have console logged the parameters (userId and userData), and they appear as expected.
I want to have my create users to be added into my database by their user uid when i sign them up from my firebase.
currently my code is working , just i dont understand why when my data is save into my firebase, the name (which is suppose to be the created user uid) shows "undefined". but the data that is grabbed and saved is correct.
My firebase database which shows undefined: https://imgur.com/ATRsmKe
My JS code which i am trying to save and create user:
/*Show Login User*/
// Firebase Variables
var auth = firebase.auth();
$(document).ready(function () {
//Pass parameter from form to Firebase
$('.addpic').on('submit', event => {
event.preventDefault();
const name = $('#name').val();
const hp = $('#hp').val();
const email = $('#email').val();
const password = $('#password').val();
const role = $('#role').val();
//Firebase user authentication
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => {
//set data into User database
firebase.database().ref('Admin/Person In Charge' + "/" + user.uid).set({
Name: name,
ContactNo: hp,
Email: email,
Password: password,
Role: role
}).then(success => {
console.log(user);
window.alert("Registered");
window.location = "user.html";
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
});
});
});
I want my data to be saved under the UID of the created user. I tried all possible solutions, but none work for me.
You should take a look at the return type of createUserWithEmailAndPassword. If I'm reading the docs correctly, it returns an instance of firebase.auth.UserCredential, not an actual user. I think you need to actually drill down one more level into that credential object and get the user.uid.
Example
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(userCredential => {
//set data into User database
firebase.database().ref('Admin/Person In Charge' + "/" + userCredential.user.uid).set({
Name: name,
ContactNo: hp,
Email: email,
Role: role
}).then(success => {
console.log(user);
window.alert("Registered");
window.location = "user.html";
});
})
You could figure this out in the future by inspecting the value of your user in your then via a console.log().
I'm trying to create a new user and store their information in firebase database. I successfully create the user but the user information isn't getting stored in firebase.
The function that is running is handleAuthWithFirebase
The console.log("Storing user") is showing up in the console so I'm not sure why firebase.database().ref().set isn't running.
Here is my code
export function handleAuthWithFirebase (newUser) {
return function (dispatch, getState) {
dispatch(authenticating());
console.log(newUser);
console.log('Signing up user');
var email = newUser.email;
var password = newUser.password;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}).then(() => {
const user = firebase.auth().currentUser;
// Set user in Firebase
console.log("Storing user")
firebase.database().ref('/users/' + user.uid).set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
}).then(() => {
const user = firebase.auth().currentUser;
dispatch(isAuthed(user.uid))
})
}
}
The problem is that you're missing a child object, so you have to specify it after ref. It would be more helpful if you can post the tree of your database as well, but before try this and figure out yout child.
firebase.database().ref('myRef').child('myChild').set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
Here's what I got working, for those coming across this post.
firebaseApp.auth()
.createUserAndRetrieveDataWithEmailAndPassword(this.state.email, this.state.password)
.then(response => {
firebaseApp.database().ref('users').child(response.user.uid).set({
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
email: this.state.email
});
response.user.sendEmailVerification().then(response => {
AlertIOS.alert('Message', 'Sending email verification to '+this.state.email)
});
this.setState({authenticating: false})
}, error => {
AlertIOS.alert('Error', error.message);
this.setState({authenticating: false})
})
I'm using Firebase at a school project and I'm having the same problem a while... I have looked at various sites but I can't find anyone with the same problem...
The User authentication is working correctly, but the problem is with saving the user data in the database.
I have two available ways to authenticate:
Email and password;
Facebook.
With email and password, the data is written successfully in the database, and I'm using the following JavaScript code:
function signUp(){
//Get DOM data
const email = String(document.getElementById('TXTEmail').value);
const pass = String(document.getElementById('TXTPassword').value);
const name = String(document.getElementById('TXTNome').value);
const gender = document.registo.sexo.value;
const auth = firebase.auth();
var promise = auth.createUserWithEmailAndPassword(email,pass);
promise.catch(e => console.log(e.message));
firebase.database().ref('users/' + firebase.auth().currentUser.uid).set({
name : name,
email : email,
gender : gender,
uid: firebase.auth().currentUser.uid
});
}
However, when using the function of facebook I can't save the data, I can only authenticate the user, and the code I'm using is as follows:
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// 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;
const name = user.displayName;
const email = user.email;
const photo = user.photoURL;
if(user != 0) {
firebase.database().ref('users/' + user.uid).set({
name: nome,
email: email,
photo: photo,
uid: user.uid
});
}
//Tests only
if(user != 0){
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
And I get this output on my console:
Console output.
name: Rafael Veloso
email: rafael****#gmail.com
photoUrl: scontent.xx.fbcdn.net/v/t1.0-1/s100x100/…
uid: **HY43Tl******KoO6OhZjG****
Also, my database.rules.json is:
{
"rules": {
".read": true,
".write": true
}
}
Does anyone know what is the problem that I'm having?
Thank you.
with the help of the Firebase support I managed to solve my problem :)
First, created a script within the .html document like that:
<script>
document.getElementById('btnFacebook').addEventListener('click', signUpFacebook, false);
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
}
function createNewPost(name, email, photo, uid) {
firebase.database().ref('users/' + uid).set({
name: name,
email: email,
photo: photo,
uid: uid
});
}
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
var token = result.credential.accessToken;
}
// The signed-in user info.
if(user != null) {
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var name = user.displayName;
var email = user.email;
var photo = user.photoURL;
var uid = user.uid;
createNewPost(name, email, photo, uid);
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
});
With just that, I still wasn't able to add the user data to the Realtime Database, so I changed my "imports", I was with this:
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
and only when I changed to the following I was able to save the user data in the Database:
<!-- <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
But I find that strange, can anyone help and explain me why that worked out?