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

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

Related

Firebase auth password reset

I'm working on a firebase app that contains an authentication system that allows users to sign up/login and create a profile. The app stores and calls profile info about the users. The system worked just fine until I realized there's no way for a user to reset their password. So I added sendPasswordResetEmail function and it's been downhill since then. I'm a newbie to firebase and to StackOverflow so forgive the mess you're about to see. Am I missing something in that function?
const resetpassword = async () => {
const email = document.getElementById('email').value;
try {
const { user } = auth.sendPasswordResetEmail(email);
alert('Password Reset Email Sent!');
}
catch(error) {
console.log("error ===>", error);
if (error.message === "Firebase: Error (auth/user-not-found).") {
alert("There is no user corresponding to this email address.")}
else (errorCode == 'auth/invalid-email') {
alert(errorMessage)}
}
}
If you are using firebase version 9 then use code snippet below to reset user password
import { getAuth, sendPasswordResetEmail } from "firebase/auth";
const auth = getAuth();
sendPasswordResetEmail(auth, email)
.then(() => {
// Password reset email sent!
// ..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});

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

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

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

Firebase signInWithRedirect says Cannot read property 'dataset' of null

I am building the React application where I want my users to login with Google. My code for authentication looks like
import {firebaseAuth, googleProvider} from "../config/constants";
export function loginWithGoogle() {
return authenticate(loginWithFirebase(googleProvider));
}
function authenticate(promise) {
return promise
.then(function (result) {
// login with your app with result object to get accessToken (token)
// localStorage.save(token);
var token = result.credential.accessToken;
var user = result.user;
console.log("login happened with firebase, ", JSON.stringify(user));
localStorage.setItem("firebaseUser", JSON.stringify(result));
return Promise.resolve(result);
}).catch(function(error){
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;
console.log("failed firebase login", error);
return Promise.reject("err");
});
}
function loginWithFirebase(provider) {
return firebaseAuth().signInWithRedirect(provider);
/*
firebaseAuth().signInWithPopup(provider).then(function (result) {
// This gives you a Google Access Token. You can use it to access the Google API.
const token = result.credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
console.log("google login success. token=", token, ",user=", JSON.stringify(user));
}).catch(function (error) {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The firebase.auth.AuthCredential type that was used.
const credential = error.credential;
// ...
console.log("google login failed.reason=", errorMessage);
});
*/
}
export function logout() {
return firebaseAuth().signOut();
}
When I start my app and go to http://localhost:3000, I see the button which takes me to the Google accounts to select for login to the app, but when it comes back to the app, I see error in the console which says
bundle.js:6106 Uncaught TypeError: Cannot read property 'dataset' of null
at HTMLDocument.r (bundle.js:6106)
Additionally, on Mobile Safari, the click of the button does not take me anywhere.
The entire codebase is available at https://github.com/hhimanshu/react-firebase-social-authentication
Please let me know what am I doing wrong?
UPDATE
I made few changes based on the documentation
In auth.js I only do
export function loginWithGoogle() {
firebaseAuth().signInWithRedirect(googleProvider);
}
In Login.js, at the top of the class (in global scope), I do
firebaseAuth().getRedirectResult().then(function(result) {
console.log("GoogleLogin Redirect result");
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
console.log("user:", JSON.stringify(user));
}).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;
// ...
});
As a result, this redirection worked on the dekstop browser, but when I click on "Login with Google" on iOS Safari and iOS Chrome, nothing happens.
How can I further debug this? I pushed the latest changes to https://github.com/hhimanshu/react-firebase-social-authentication
Thanks

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