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;
// ..
});
Related
I have a create user and login authentication setup with firebase realtime database. I have a user field in my database where I will store user data. However, I would like to create a child element under the user field that is the user id then the user information can be displayed under that child.
So far I have tried to create such a field with this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getDatabase, set, ref, update } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
//Signup section
signup.addEventListener('click',(e) => {
var username = document.getElementById('signup-user').value;
var email = document.getElementById('signup-email').value;
var schoolID = document.getElementById('signup-id').value;
var password = document.getElementById('signup-pwd').value;
createUserWithEmailAndPassword(auth, email, password, schoolID)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
update(ref(database, "user/" +user.id),{
username: username,
schoolID: schoolID,
email: email
})
alert('User Created!');
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert('Error please try again');
// ..
});
});
But it only gives me an undefined field in my realtime database:
Not only that but it overwrites the previous entry every time a make an new user.
userCredential.user is a User type object, which is a subclass of UserInfo. As you can see from the linked API documentation, User doesn't have an property called id. It will always be undefined.
What you want instead is uid.
update(ref(database, "user/" + user.uid), {...})
I'm logging in users via firebase-auth and need to pass their user uid to the redirected page. How can the user-uid be passed?
I've tried using the docs on firebase auth but cant quite solve it
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm['email'].value;
const password = loginForm['password'].value;
console.log(email, password);
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword(email, password)
.then(cred => {
if(email ==='admin#mombasa.com' && password ==='adminMomb') {
window.location = './admin-map.php';
}
else if(email ==='admin#nairobi.com' && password ==='adminNai') {
window.location = './admin-map.php';
}
else if(email ==='admin#eldoret.com' && password ==='adminEld') {
window.location = './admin-map.php';
}
else firebase.auth().onAuthStateChanged(function(user) {
window.user = user;
console.log('logged in ', user);
window.location = './dailyreports.php';
console.log('logged in ', user);
});
}).catch(
function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorMessage, errorCode);
}
)
;
});
On navigation to the next page, I expected to see the user-uid output in the console but it returns blank
Instead of passing the UID, it's better to pick up the state in the next page with a so-called authentication state listener.
As shown in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
There will be no delay in picking up the user account this way on the new page, as the Firebase SDK will be able to restore the state from the information it stored in local storage.
Using createUserWithEmailAndPassword function of firebase I am able to sign users up but how to add extra information such as display name and picture URL?
This is what I have done.
const signup = document.querySelector('#signup-form');
signup.addEventListener('submit', e=>{
e.preventDefault();
//get user info
const first_name = signup['firstname'].value;
const last_name = signup['lastname'].value;
const email = signup['email1'].value;
const password = signup['pswd1'].value;
//sigup the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(()=>{
firebase.auth().onAuthStateChanged(function(user){
if(user){
user.updateProfile({
displayName: first_name
})
}
})
signup.reset();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
});
Once you have created the user, you can access user object provided by firebase. Using its updateProfile function, you can pass an object containing the properties you want the user object to have, like the code below:
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Update successful.
}).catch(function(error) {
// An error happened.
});
This worked for me.
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{
cred.user.updateProfile({
displayName: first_name + " " + last_name
})
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
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().
My use case is similar to Parse Suggested Migration Strategy
(but I'm not using Parse, just integrating 3rd party auth)
On Node.js / express, here is relevant code:
firebaseWebSDK.auth().signInWithCustomToken(customToken)
.then(user => {
let nextStep
let message
// check if returned user has "email" field set..
if (!user.email) {
message = 'Signed up user, saved: email, password, and display name.'
const usersRef = firebaseServerSDK.database().ref('users')
nextStep = Promise.all([
user.updateEmail(email),
user.updatePassword(password),
user.updateProfile({ displayName }),
usersRef.child(user.uid).set({ displayName, email }),
])
} else {
message = `User already exists for that email: ${email}`
nextStep = Promise.resolve(null)
}
nextStep.then(() => {
delete req.session.user
return res.json({ message })
})
.catch(updateError => res.json({ error: updateError.message }))
})
.catch(signInError => {
const errorCode = signInError.code
const errorMessage = signInError.message
return res.json({ type: 'signInError', errorCode, errorMessage })
})
Here's what happens:
Sometimes user email updates, sometimes it doesn't
Never does the password update
Pretty sure the Profile updates always
database "/users" saves correctly, no issues there.
Always tested with new user, so it's always entering the "update" branch of code...
Any ideas? Code follows structure of documentation linked above, so not sure what issue is.