save user's extra details on signup firebase - javascript

I want to save the user's extra details i.e number, age only when the user signup(one time). But there is no callback for to check if the signup was successful or not.
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
so what to do when you want to store the data only one time when the user signup rather using
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
which will be fired every time user login/logout but I dont want to save the extra signup details every time.

firebase.auth().createUserWithEmailAndPassword($scope.email, $scope.password)
.then(function(user) {
var ref = firebase.database().ref().child("user");
var data = {
email: $scope.email,
password: $scope.password,
firstName: $scope.firstName,
lastName: $scope.lastName,
id:user.uid
}
ref.child(user.uid).set(data).then(function(ref) {//use 'child' and 'set' combination to save data in your own generated key
console.log("Saved");
$location.path('/profile');
}, function(error) {
console.log(error);
});
})
.catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else if (errorCode == 'auth/email-already-in-use') {
alert('The email is already taken.');
} else if (errorCode == 'auth/weak-password') {
alert('Password is weak');
} else {
alert(errorMessage);
}
console.log(error);
});
Here I have saved data in 'user.uid' key which is returned by firebase upon successful registration of user.

Calling createUserWithEmailAndPassword() return a promise, which has both a catch() and then() method you can respond to.
The Firebase documentation intentionally doesn't use then then() clause, since it's in general better to respond to the onAuthStateChanged() event (which also fires when the user reloads the app and is still signed in. Even in your case that might be the better place to put the code to store the user profile, as some of the data might change when the app reloads.
But if you want to explicitly respond to "the user was created successfully", you can do so with:
firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then(function(user) {
console.log("Create user and sign in Success", user);
});

Related

Get user id after creating a user in firebase

I am trying to retrieve the id of the newly created user on my website. Admin creates the account based on the user's email and password. But as soon as the account is created, I need the id and use it in the firestore database as a document id to store user info. This is how my code looks:
firebase.auth().createUserWithEmailAndPassword(email.trim(), password.trim())
.then(function () {
db.collection("users").add({
email: email.trim(),
name: username.trim(),
id: //I need the user's id here
}).then(function () {
window.alert('User registered successfully');
window.location = 'user.html';
}).catch(function (error) {
window.alert("There was some error. Please try again.");
console.log(error.code);
console.log(error.message);
});
})
Is there a way that I can get that user's id in then part?
You can try this:
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => { // the userCredential is a variable that will hold the response in it, it contains all the user info in it
// Signed in
var user = userCredential.user;
// This user variable contains all the info related to user including its id
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});
Reference

How do I store the user uid to firebase database after I register an account?

Here's my code in .js
$("#loginBtn").click(
function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
if(email != "" && password != ""){
$("#loginProgress").show();
$("#loginBtn").hide();
$("#registerBtn").hide();
firebase.auth().signInWithEmailAndPassword(email,
password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
$("#loginError").show().text(errorMessage);
$("#loginProgress").hide();
$("#loginBtn").show();
$("#register_account_Btn").hide();
$("#back_btn").hide();
});
}
}
);
/* REGISTER PROCESS */
$("#register_account_Btn").click(
function () {
var email = $("#regEmail").val();
var password = $("#regPassword").val();
if(email != "" && password != ""){
$("#loginProgress").show();
$("#loginBtn").hide();
firebase.auth().createUserWithEmailAndPassword(email,
password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
$("#loginError").show().text(errorMessage);
$("#loginProgress").hide();
$("#loginBtn").show();
$("#register_account_Btn").hide();
$("#back_btn").hide();
});
}
I found this on the internet but I don't know where to insert it.
Is this correct?
var uid = firebase.auth().currentUser.uid;
firebase.database().ref().child('accounts').child(uid).set({
email: user.email,
userId: uid
})
Should I create another function?
and these are the rules in my firebase database. Is it advisable to use this?
Additional Question:
I want to create a user roles: teacher and student. Teacher can create classroom, add students, view the list of students. While the student can view his/her classmates and teacher. How should I do this?
{
"rules": {
"users": {
"$uid": {
".read": false,
".write": "$uid === auth.uid"
}
}
}
}
Sincerest apology but I'm new to this ;(
The firebase.auth().createUserWithEmailAndPassword function returns a Promise: firebase.User.
You're only catching exceptions with your code, if you chain a .then onto the function you can get the user information and save that user to the data.
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => {
// Save user here.
return firebase.database().ref('/users/' + user.uid).set({
email: user.email,
uid: user.uid
});
})
.catch(function(error) {
// Handle Errors here.
});
Your other question around the teacher / student is very broad - try to narrow it down to a solution and if you get stuck with some specific create a new question.
Since version 5.0.0 of the Firebase JavaScript SDK, createUserWithEmailAndPassword() returns a Promise containing the new user's credentials as a UserCredentials object instead of a User object.
However, the UserCredentials object contains the User object as it's user property, which you can get the new email and user ID from as in #sketchthat's answer.
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(credential => {
// Save user here.
return firebase.database().ref('/users/' + credential.user.uid).set({
email: credential.user.email,
uid: credential.user.uid
});
})
.catch(function(error) {
// Handle Errors here.
});

How can I know if the creation of a user with email and password was successful? and take actions

For example:
firebase.auth().createUserWithEmailAndPassword(email, password).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.');
exit;
} else {
alert(errorMessage);
exit;
}
console.log(error);
// [END_EXCLUDE]
});
this only creates the user and verifies errors, but does not indicate if the user's creation was successful, since I need to take actions, such as saving the user's name in my database (if the user's creation was successful) or Redirect if the user's creation is successful.
How can I take actions if was successful the user createUserWithEmailAndPassword?
Use .then() instead:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(result){
// update your database
}, function(error){
// handle the error
});

How to add username with email and password in Firebase?

I'm using Firebase and I'm trying to add a username to the database with the email and password.
Is there a way to do it or is createUserWithEmailAndPassword() function only for email and password?
signUp.addEventListener("click", function(user)
{
var username = usernameTxt.value;
var email = emailTxt.value;
var password = passwordTxt.value;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/email-already-in-use')
{
alert('email-already-in-use.');
}
else
{
alert(errorMessage);
}
console.log(error);
});
});
The solution that i found to how to add username with the createUserWithEmailAndPassword() function:
firebase.auth().onAuthStateChanged(function(user) {
var username = usernameTxt.value;
if (user) {
firebaseDataBase.ref('users/' + user.uid).set({
email: user.email,
uid : user.uid,
username: username
});
console.log("User is signed in.");
} else {
console.log("No user is signed in.");
}
});
You need to create that database users child node yourself ;-)
The createUserWithEmailAndPassword function only creates a new user in Firebase authentication service. The database itself isn't changed at all as a result.
To add this new user to the database as well, try:
firebase.database().ref("users").child(user.uid).set(...)
This cannot be done through createUserWithEmailAndPassword() but there is a firebase method for this . You will need to listen for when authentication state is changed , get the user , then update the profile info . See Below
This code would come after createUserWithEmailAndPassword()
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Updates the user attributes:
user.updateProfile({ // <-- Update Method here
displayName: "NEW USER NAME",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Profile updated successfully!
// "NEW USER NAME"
var displayName = user.displayName;
// "https://example.com/jane-q-user/profile.jpg"
var photoURL = user.photoURL;
}, function(error) {
// An error happened.
});
}
});
As stated in firebase User Api here : https://firebase.google.com/docs/reference/js/firebase.User#updateProfile
Hope this helps
You can create a users endpoint and store custom user data in there.
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
// Add more stuff here
});
}
Have a look to https://firebase.google.com/docs/database/web/read-and-write

"auth/user-not-found" when signing in user with Firebase

I have a firebase app connected to monaca CLI and OnsenUI. I am trying to create a user and log them in in the same action. I can successfully create a user, but I can't log in. When I log them in I get the following error
auth/user-not-found
and
There is no user record corresponding to this identifier. The User may have been deleted
I confirmed that the new user is in the db...Here is my code for the signup and signin
//signup function stuff
var login = function() {
console.log('got to login stuff');
var email = document.getElementById('username').value;
var password = document.getElementById('password').value;
//firebases authentication code
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('User did not sign up correctly');
console.log(errorCode);
console.console.log(errorMessage);
});
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
fn.load('home.html');
};
You have a so-called race condition in your flow.
When you call createUserWithEmailAndPassword() Firebase starts creating the user account. But this may take some time, so the code in your browser continues executing.
It immediately continues with signInWithEmailAndPassword(). Since Firebase is likely still creating the user account, this call will fail.
The solution in general with this type of situation is to chain the calls together, for example with a then():
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('User did not sign up correctly');
console.log(errorCode);
console.console.log(errorMessage);
});
But as André Kool already commented: creating a user automatically signs them in already, so in this case you can just do:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
// User is created and signed in, do whatever is needed
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('User did not sign up correctly');
console.log(errorCode);
console.console.log(errorMessage);
});
You'll likely soon also want to detect whether the user is already signed in when they get to your page. For that you'd use onAuthStateChanged. From the docs:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
async/await works too.
(async () => {
try {
const result = await auth().createUserWithEmailAndPassword(email, password).signInWithEmailAndPassword(email, password);
console.log(result);
} catch (error) {
console.error(error);
}
})()

Categories

Resources