Javascript and Firebase - Create user with Email and password and onAuthStateChange - javascript

Hi I'm having problems finding a way to have an auth state change auto direct to a page for logged in users. Before a user is created however I want to push to my database a user Profile.
So I create the user then add to the database with this code
firebase.auth().createUserWithEmailAndPassword(email, password).then(function (user){
firebase.database().ref('/Profiles').child(user.uid).set({
address: ''
})
}).catch(function(error){
let errorCode = error.code;
let errorMessage = error.message;
navigator.notification.alert('Error: Code: ' + errorCode + ', ' + errorMessage,false,'Error','Done');
});
However, Once the createUserWithEmailAndPassword is successful This onAuthStateChanged function navigates to the new page before the database 'Profile' record is added.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
let u = firebase.auth().currentUser;
window.location = 'loggedIn.html';
}
});
How can I make it so that my onAuthStateChanged function waits for the database record to be added before navigating away from the page
NOTE:: I want to keep the onAuthStateChanged so that if a user is logged into the session they will auto directed to the loggedIn page

You can try to register the onAuthStateChagned handler after saving to database.

I had the same problem. I tried several stuffs but one simple setState for some reason solved this issue.
Try to setState for something inside the createUserWithEmailAndPassword function. For example:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function (user){
firebase.database().ref('/Profiles').child(user.uid).set({
address: ''
})
// SET Some state
this.setState({ error: null, isLoading: false });
// Besides that I show the feedback as an alert (just in case you think it's a good idea)
Alert.alert(
`Welcome ${user.user.name}!`,
'Your account has been successfully created.',
[
{
text: 'OK',
onPress: () =>
navigation.navigate('Main'),
},
]
);
}).catch(function(error){
let errorCode = error.code;
let errorMessage = error.message;
navigator.notification.alert('Error: Code: ' + errorCode + ', ' + errorMessage,false,'Error','Done');
});

Related

Firebase signInWithEmailAndPassword and onAuthStateChanged Realtime Database logging issue

I'm working on a webpage using HTML5 CCS etc, where it uses a authentication process using firebase for users. Its my first time ever working on firebase, so i still have no idea how to correctly code using it.
I manually add a admin user on firebase, so i can use those credentials to log in to the webpage. In the signInWithEmailAndPassword i used a code to log into the console some information about credentials, but whats happening is that while it does work (the authentication). The only way it logs info into the console is when i don't redirect the user to another page using the onAuthStateChanged (basically not using it at all).
Basically it authenticates correctly, but its doesn't log the info in the realtime database unless i remove the onAuthStateChanged.
Here is the code
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const dt = new Date();
update(ref(database, 'users/' + user.uid), {
Email: email,
Password: password,
Last_Login: dt
})
alert('Usuario ingresado!')
location.href = 'test.html'
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage)
});
});
const user = auth.currentUser;
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
location.href = 'test.html'
// ...
} else {
// User is signed out
// ...
}
});
I heard this process is asynchronous.
Calls to Firebase (and most modern cloud APIs) are asynchronous, since they may take some time to complete. But as soon as the user is signed in, the local onAuthStateChanged will be called - which interrupts the write to the database.
If the user always actively signs in to this page (so you always call signIn...), then you don't need the onAuthStateChanged handler and can just include the navigation code in the then:
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const dt = new Date();
update(ref(database, 'users/' + user.uid), {
Email: email,
Password: password,
Last_Login: dt
}).then(() => {
location.href = 'test.html'; // đŸ‘ˆ
})
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage)
});
});

FireBase user authentication redirect to another page

I have created a signupPage.html to authenticate a user and and log information to the realtime database in firebase using this code:
signUp_button.addEventListener('click', (e) => {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
//signed up
const user = userCredential.user;
//log to database
set(ref(database, 'users/' + user.uid),{
email : email
})
//this is where page redirection
alert('User Created');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
});
Then when I click my submit button everything works and the user is authenticated and information is stored into the realtime database. Now I want to redirect the user to a login page after they submit their signup. In my code under "this is where page redirection", I put location.href = "login.html". This does redirect the page and authenticate the user but it no longer stores the data into the realtime database. Any suggestions?
You were close. set() is an asynchronous action, so by adding the redirect where you were, you would redirect before the set() had the chance to execute. You must first wait for the set() to finish, and then redirect.
signUp_button.addEventListener('click', (e) => {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
//signed up
const user = userCredential.user;
// log to database & wait for it to finish!
return set(ref(database, 'users/' + user.uid), {
email : email
})
})
.then(() => {
alert('User Created'); // avoid alert, it blocks user input!
// update a div with an information message instead
location.href = "login.html";
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage); // avoid alert, it blocks user input!
// update a div with an error message instead
});
});

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

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

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

Categories

Resources