How to add username with email and password in Firebase? - javascript

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

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

Firebase authentication and store user in MySQL

I want to know how I can register a user using Firebase authentication, and then proceed to store the user in a MySQL database as well for later use.
I am currently authenticating the user using Firebase, but am not sure how to go about calling a Nodejs API to query the MySQL database.
All the examples I have seen to store users in MySQL are calling the API from the form action itself. However, I want to first authenticate the user with Firebase.
If someone has experience with this I would appreciate the help.
const signupForm = document.querySelector('#sign-up-form');
signupForm.addEventListener('submit', (e) => {
e.preventDefault();
//get user info
const username = signupForm['signup-username'].value;
const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;
//signup the user
auth.createUserWithEmailAndPassword(email, password).then(cred => {
//createUser function returns the user credentials
user = auth.currentUser;
}).then(function () {
user.updateProfile({
displayName: username
})
}).catch((error) => {
//Handle errors
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
});
})
You need to have some sort of backend to send the user and then use Express or some other server make the query and save to MySQL. You can't do it from the client because it's insecure.
eg:
auth.createUserWithEmailAndPassword(email, password).then(async (user) {
user.updateProfile({
displayName: username
})
const result = await axios.post('/api/saveUser/', user, config)
})

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

save user's extra details on signup firebase

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

Can't write user data to firebase

I'm new at this so bear with me. I'm trying to use the fire base simple login with the email and password. I have that working with this:
var authClient = new FirebaseAuthClient(fireRef, function(error, user) {
if (error) {
// an error occurred while attempting login
if(error.code === "INVALID_EMAIL"){
$('#log_email_error').hide();
$('#log_pass_error').hide();
$('#log_email_error').html("Invalid email specified.").fadeIn();
$('.login_button').removeClass('login_button_success').attr('value','Log in');
}
if (error.code === "INVALID_PASSWORD") {
$('#log_email_error').hide();
$('#log_pass_error').hide();
$('#log_pass_error').html("The specified password is incorrect..").fadeIn();
$('.login_button').removeClass('login_button_success').attr('value','Log in');
}
console.log(error);
} else if (user) {
// user authenticated with Firebase
hideLogin();
$('.userInfo_cont').show();
$('.userInfo').html('<div> '+ user.email + ' <span class="grey">| </span> </div>');
$('.logout').on('click',function(){
authClient.logout();
});
console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
} else {
// user is logged out
$('.userInfo_cont').hide();
showLogin();
}
});
But when the user registers I want to store some additional info in a firebase/users area
which I can do with this in the registration:
$('#submit_reg').on('click',function(){
var firstName = $('#regFirstname').val();
var lastName = $('#regLastname').val();
var email = $('#regUsername').val();
var password = $('#regPassword').val();
authClient.createUser(email, password, function(error, user) {
if (!error) {
console.log('User Id: ' + user.id + ', Email: ' + user.email);
authClient.login('password', {
email: email,
password: password,
rememberMe: false
});
hideLogin();
userInfo = {
userId : user.id,
firstName : firstName,
lastName : lastName,
email : user.email
}
var url = USERS_LOCATION + "/" + user.id;
var userRef = new Firebase(url);
console.log(userInfo);
userRef.set(userInfo);
}else{
//display error
alert(error);
}
});
});
My Problem is when I implement the read write rules like the documentation has:
{
"rules": {
"users":{
"$userid": {
".read": "auth.id == $userid",
".write": "auth.id == $userid"
}
}
}
}
I get a permission denied when the user registers. So it registers the user just fine but won't write the additional data to the /users/id area.
Any help would be much appreciated.
Craig
In the snippet above, you're calling login(), and then immediately calling set() afterwards. This is problematic because the login() method is asynchronous, and you are almost always guaranteed to have called set() method prior to the return of the login attempt method, since login() is non-blocking yet makes a network call to the Firebase servers.
This means that even though you're calling login() with the correct email and password, you're trying to set the data before the authentication process has completed.
I would recommend moving your set() logic into a block that will only be executed when you are certain that the user has already authenticated, such as in the callback you passed when calling new FirebaseAuthClient() and detected a logged in user.

Categories

Resources