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;
// ..
});
Related
I have already tried it with the code below however once i login every device on my network is capable of automatically logging in. How can I create a secure authentication system?
.post('/logIn', async (req, res) => {
const context = { error: false }
await signInWithEmailAndPassword(auth, req.body.email, req.body.password)
.catch(err => {context.error = true})
if (context.error) {
return res.render('auth/logIn.ejs', context)
} else {
return res.redirect('/')
}
})
If possible can somebody redirect me to a youtube video or article from which I can find a solution?
You can dictace the behavioir using auth state persistence
import { getAuth, setPersistence, signInWithEmailAndPassword, browserSessionPersistence } from "firebase/auth";
const auth = getAuth();
setPersistence(auth, browserSessionPersistence)
.then(() => {
return signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
This will log out users if they end their session, i.e, close their browser.
You can read more about it here: https://firebase.google.com/docs/auth/web/auth-state-persistence
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)
});
});
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
});
});
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)
})
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);
}
})()