Firebase signInWithEmailAndPassword and onAuthStateChanged Realtime Database logging issue - javascript

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

Related

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

Password is gone when logging in a firebase account that was created using Email and Password

I created an app that supports both Email/Password and Google authentication. I found that if I created an account in a first way, but logged out and in again with Google, the origin password was gone, and no way to sign in with email anymore. Is there any way to avoid so?
// Google authentication
const signInWithGoogle = useCallback(
async event => {
event.preventDefault();
const provider = new firebase.auth.GoogleAuthProvider();
try {
await firebaseApp
.auth()
.signInWithRedirect(provider)
.then(function(result) {
var user = result.user.providerId;
alert(user);
});
history.push("/transfer");
} catch(error) {
alert(error.message);
}
},
[history]
);
//Email/Password sign-in
const handleLogin = useCallback(
async event => {
event.preventDefault();
const { email, password } = event.target.elements;
try {
await firebaseApp
.auth()
.signInWithEmailAndPassword(email.value, password.value)
.then(function(result) {
var user = result.user.providerId;
alert(user);
});
history.push("/transfer");
} catch (error) {
alert(error);
}
},
[history]
);
// Email/Password sign-up
const handleSignUp = useCallback(async event => {
event.preventDefault();
const { email, password } = event.target.elements;
try {
await firebaseApp
.auth()
.createUserWithEmailAndPassword(email.value, password.value);
history.push("/usersignupcred");
} catch (error) {
alert(error);
}
}, [history]);
Here in the documentation you can see this explanation:
Note that some providers, such as Google and Microsoft, serve as both email and social identity providers. Email providers are considered authoritative for all addresses related to their hosted email domain. This means a user logging in with an email address hosted by the same provider will never raise this error (for example, signing in with Google using an #gmail.com email, or Microsoft using an #live.com or #outlook.com email).
I would recommend to use as similar approach like here from the docu:
// User tries to sign in with Facebook.
auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()).catch(err => {
// User's email already exists.
if (err.code === 'auth/account-exists-with-different-credential') {
// The pending Facebook credential.
var pendingCred = err.credential;
// The provider account's email address.
var email = err.email;
// Get the sign-in methods for this email.
auth.fetchSignInMethodsForEmail(email).then(methods => {
// If the user has several sign-in methods, the first method
// in the list will be the "recommended" method to use.
if (methods[0] === 'password') {
// TODO: Ask the user for their password.
// In real scenario, you should handle this asynchronously.
var password = promptUserForPassword();
auth.signInWithEmailAndPassword(email, password).then(result => {
return result.user.linkWithCredential(pendingCred);
}).then(() => {
// Facebook account successfully linked to the existing user.
goToApp();
});
return;
}
// All other cases are external providers.
// Construct provider object for that provider.
// TODO: Implement getProviderForProviderId.
var provider = getProviderForProviderId(methods[0]);
// At this point, you should let the user know that they already have an
// account with a different provider, and validate they want to sign in
// with the new provider.
// Note: Browsers usually block popups triggered asynchronously, so in
// real app, you should ask the user to click on a "Continue" button
// that will trigger signInWithPopup().
auth.signInWithPopup(provider).then(result => {
// Note: Identity Platform doesn't control the provider's sign-in
// flow, so it's possible for the user to sign in with an account
// with a different email from the first one.
// Link the Facebook credential. We have access to the pending
// credential, so we can directly call the link method.
result.user.linkWithCredential(pendingCred).then(usercred => {
// Success.
goToApp();
});
});
});
}
});
But instead of waiting for the error to be raised (none will be raised if using Google login as you also explained in your case) try always to call first fetchSignInMethodsForEmail and if the user has the email provider and tries now to use the Google one first log him in with the email provider and link him later with the Google provider.

Send verification email before logging in

This is the code that i'm practicing in to create a new user. I can receive the email verification and confirm it however, the site will still logged me in even if I have not yet confirmed my email yet.
try{
const { user } = await auth.createUserWithEmailAndPassword(email,password);
await user.sendEmailVerification();
await handleUserProfile(user, { displayName});
this.setState({
...initialSate
});
}catch(err){
console.log(err);
}
}
This is the handleUserProfile in another js file.
export const handleUserProfile = async (userAuth, additionalData) => {
if (!userAuth) return;
const {uid} = userAuth;
const userRef = firestore.doc(`users/${uid}`);
//create new user
const snapshot = await userRef.get();
if (!snapshot.exists){
const { displayName, email} = userAuth;
const timestamp = new Date();
//if the user exist does not exist
try{
await userRef.set({
displayName,
email,
createdDate: timestamp,
...additionalData
});
}catch(err){
console.log(err);
}
}
return userRef;
};
Everything is explained in the firebase documentation.
There you have the corresponding code snippets to try.
You would need to narrow down your question with some of this trials.
Even you have the chance to check if user opens the link from a differenc device from which waas signed up.
I think this is the snippet you might need:
// Confirm the link is a sign-in with email link.
if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
// Additional state parameters can also be passed via URL.
// This can be used to continue the user's intended action before triggering
// the sign-in operation.
// Get the email if available. This should be available if the user completes
// the flow on the same device where they started it.
var email = window.localStorage.getItem('emailForSignIn');
if (!email) {
// User opened the link on a different device. To prevent session fixation
// attacks, ask the user to provide the associated email again. For example:
email = window.prompt('Please provide your email for confirmation');
}
// The client SDK will parse the code from the link for you.
firebase.auth().signInWithEmailLink(email, window.location.href)
.then((result) => {
// Clear email from storage.
window.localStorage.removeItem('emailForSignIn');
// You can access the new user via result.user
// Additional user info profile not available via:
// result.additionalUserInfo.profile == null
// You can check if the user is new or existing:
// result.additionalUserInfo.isNewUser
})
.catch((error) => {
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
});
}
The site will still logged me in even if I have not yet confirmed my
email yet.
Yes this is how it is implemented in Firebase: there is nothing, out of the box, that prevents a user with a non-verified email to authenticate to your app.
You should manage that yourself, by:
Checking the email is verified in the back-end security rules (Firestore, Cloud Storage, etc..). For example with a function like:
function isVerifiedEmailUser() {
return request.auth.token.email_verified == true;
}
Possibly redirect and logout the user from your app if his/her email is not verified. For example, right after signing-up, as follows:
try {
const { user } = await auth.createUserWithEmailAndPassword(email,password);
await user.sendEmailVerification();
if (user.emailVerified) {
// display the content, redirect to another page, etc...
} else {
auth.signOut(); // Maybe call that after showing an error message
}
} catch(err){
console.log(err);
}
}
plus, potentially, something similar with signInWithEmailAndPassword() and onAuthStateChanged().

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 to validate firebase user current password

I am creating a form, in react-redux to change user password. I am wondering how can I validate the user current password in order to change to new one.
in my form I have 2 fields: old password, new password.
this is my action:
const { currentUser } = auth
currentUser.updatePassword(newPassword)
.then(
success => {
dispatch({
type: CHANGE_USER_PASSWORD_SUCCESS,
payload: currentUser
})
},
error => {
dispatch({
type: CHANGE_USER_PASSWORD_FAIL,
error: error.message
})
}
)
I am wondering, how to validate the old password in firebase? Should I use signInWithEmailAndPassword()? Or, is there a function to validate the current password without calling the signIn again, since my user is already logged in?
Thanks
Well, I believe you want the user to enter the old password just to verify whether it's the actual owner of the account or not.
Firebase handles this situation very well, you just need to call the updatePassword method on the user object and pass in the new password.
const changePassword = async newPassword => {
const user = firebase.auth().currentUser;
try {
await user.updatePassword(newPassword)
console.log('Password Updated!')
} catch (err) {
console.log(err)
}
}
If it's been quite a while that the user last logged in then firebase will return back an error -
"This operation is sensitive and requires recent authentication. Log in before retrying this request."
Thus, you don't really need to check the old password as firebase does it for you.
But if you just want to do it in one go, without having the user to log in again.
There's a way for that as well.
There is a method on user object reauthenticateAndRetrieveDataWithCredential you just need to pass in a cred object(email and password) and it refreshes the auth token.
const reauthenticate = currentPassword => {
const user = firebase.auth().currentUser;
const cred = firebase.auth.EmailAuthProvider.credential(
user.email, currentPassword);
return user.reauthenticateAndRetrieveDataWithCredential(cred);
}
In your particular case, you can have something like this
const changePassword = async (oldPassword, newPassword) => {
const user = firebase.auth().currentUser
try {
// reauthenticating
await this.reauthenticate(oldPassword)
// updating password
await user.updatePassword(newPassword)
} catch(err){
console.log(err)
}
}
Learn more about firebase reauth - https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user
Hope it helps

Categories

Resources