Passwordless sign in is not working in Firebase. Email was sent successfully. But after clicking on the link provided in the email that link redirects to the website with api key, mode etc. But not signing in or saving the email in firebase.
Please help me!!
const handleContinueWithEmail = async (event: any) => {
event.preventDefault();
setSignInLoading(true);
if (isSignInWithEmailLink(auth, window.location.href)) {
setEmail(window.localStorage.getItem("emailForSignIn"));
if (!email) {
setEmail(window.prompt("Please provide your email for confirmation"));
}
signInWithEmailLink(auth, email, window.location.href)
.then((result) => {
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
console.log(result.user);
})
.catch((error) => {
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
console.log(error);
});
} else {
sendSignInLinkToEmail(auth, email, {
url: location.origin,
handleCodeInApp: true,
})
.then(() => {
window.localStorage.setItem("emailForSignIn", email);
setSignInLoading(false);
setShowSuccessToast(true);
setSuccessText(
"Sign in email has been sent! Check spam folder if not found."
);
setTimeout(function () {
setShowSuccessToast(false);
}, 6000);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setSignInLoading(false);
console.error(errorCode, errorMessage);
});
}
};
Successfully redirected with API key, mode, and more. But not sign in or saving email on Firebase.
I'm trying to add passwordless sign in using fireabase on my website. But it's not sign in or saving email to firebase user list. So, I need help to solve this problem.
Related
I'm trying to make just a simple authentication app with electron and firebase redirect, but if the user is already logged in and I use the firebase.auth().currentUser.getIdToken() to get the IdToken of that user, but when i try that token in
firebase.auth().signInWithCredential(credential) I get the error that says ERROR: auth/invalid-credential
Here is my code front-end
firebase.auth().onAuthStateChanged( async function (user) {
if (user) {
// User is signed in.
var user = await firebase.auth().currentUser;
if (user != null) {
await firebase.auth().currentUser.getIdToken().then(function(idToken) {
window.location.href = "electron://"+idToken;
}).catch(function(error) {
console.log(error)
});
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
Here is my code back-end
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (commandLine[2]) {
var url = commandLine[2].split('/')
var id_token = url[2]
console.log('id: ', id_token)
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential)
.then((success)=>{
myWindow.loadFile('./scr/welcome.html')
console.log('RESULT: ',success)
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('ERROR:', errorMessage)
// 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('ERROR:', credential)
// ...
})
}
I'm missing something or doing something wrong?
That's not how ID tokens work. The purpose of an ID token is to pass to your backend, so that it can validate the identity of the signed in user, and perform some action on their behalf. It's not valid for signing in on the client again. You might want to review the documentation on use of ID tokens to learn how this works.
signInWithCredential only works with Google Auth when you correctly construct a GoogleAuthProvider credential. There is plenty of sample code in the API documentation for that.
I'm developing an authentication system for my React app with Firebase Auth. When the user signs up, firebase auth registers the user (createUserWithEmailAndPassword) and returns a promise with auth.uid and auth.emailVerified set to "false". This is fine.
I then use sendEmailVerification() method so the email address can be verified. I've tested the code and it works ok for a "valid" and "existing" email address. "catch" does give error for duplicate email address as expected. The problem is, it does not send the NON-EXISTING email (which I suppose is the correct bahaviour) but its should then give an error (so I can display to the user) which it does not.
Can someone explain why I'm not getting error for NON EXISTENT email address?
export const unpSignUp = (newUser) => {
console.log("newUser", newUser);
return (dispatch, getState, { getFirebase, getFirestore }) => {
const firebase = getFirebase();
const firestore = getFirestore();
firebase.auth().createUserWithEmailAndPassword(
newUser.unp_a05_email,
newUser.unp_a10_password
)
.then((response) => {
return firestore
.collection("unps")
.doc(response.user.uid)
.set({
unp_a02_surname: newUser.unp_a02_surname,
unp_a03_name: newUser.unp_a03_name,
unp_a06_verify_email_sent_datetime: null,
unp_a07_email_verified_on_datetime: null,
unp_a18_acc_created_on_datetime: moment().format("YYYY MM DD HH:mm:ss"),
});
})
.then((response) => {
console.log("SIGNUP SUCCESS ", response);
// user has been signed up, next step is to send verification email
dispatch({ type: SIGNUP_SUCCESS })
})
.then(() => {
// user has been signed up, next step is to send verification email
console.log('send email adr verification')
return firebase.auth().currentUser.sendEmailVerification()
})
.then( (response) => {
console.log("Verification email sent", response);
const user = firebase.auth().currentUser
console.log('current user', user)
const unp = firestore.collection("unps").doc(user.uid);
return unp.update({
unp_a06_verify_email_sent_datetime: moment().format("YYYY MM DD HH:mm:ss"),
})
})
.then( () => {
console.log(`unp_a06_verify_email_sent_datetime update to ${moment().format("YYYY MM DD HH:mm:ss")} `)
})
.catch((error) => {
console.log("SIGNUP ERROR", error);
console.log("SIGNUP ERROR CODE", error.code);
console.log("SIGNUP ERROR MESAGE", error.message);
dispatch({ type: SIGNUP_ERROR, error });
});
};
};
From firebase reference,
the return type of sendEmailVerification is Promise<void> - and it does not tell about any error codes that are sent in case of wrong email or failed/bounce mails. The error code it mentions is with respect to actionCodeSettings
If the actionCodeSettings is not specified, no URL is appended to the action URL. The state URL provided must belong to a domain that is whitelisted by the developer in the console. Otherwise an error will be thrown.
Thus it can not be checked if it is a valid email id. (This is expected behaviour as receiving mail servers may be down at times and hence there is a concept of retrying bounce mails)
I'm implementing a workflow where every user using my app is an anonymous user until they sign-in/up (either email or Google).
To sign up, it's straightforward: I use linkWithPopup.
However, I had some issues with user signing in: I try to link them and, if I get the auth/credential-already-in-use error (happens if the user upgrades once, signs out and then try to sign in again), I sign them in.
firebase.auth().currentUser.linkWithPopup(provider).then(function (result) {
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
if (errorCode === 'auth/credential-already-in-use') {
return firebase.auth().signInWithCredential(error.credential);
}
}).then((result) => {
return dispatch(loadContent(result.user.uid))
}).then(() => {
history.push('/');
});
The code above is working great and that's less hassle than doing it all by myself.
However, how do I remove the anonymous users which are created and orphan in case the user signs in?
I tried to make a reference to the old useless anonymous user and to delete it once the user is signed in (and so, changed its account) but it is obviously not working because the account changed and that would be a big security flaw if a user could delete another one...
I'm not very familiar with Firebase ecosystem, how should I handle that? Do I need to use a combination of Firebase Cloud Function and Firebase Admin SDK or is there a standard way of solving this problem?
It is quite simple. APIs on the user continue to work even if the user is not current.
const anonymousUser = firebase.auth().currentUser;
firebase.auth().currentUser.linkWithPopup(provider)
.then(function (result) {
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
if (errorCode === 'auth/credential-already-in-use') {
return firebase.auth().signInWithCredential(error.credential);
}
}).then((result) => {
if (anonymousUser.uid !== result.user.uid) {
return anonymousUser.delete()
.then(() => {
return result;
});
}
return result;
}).then((result) => {
return dispatch(loadContent(result.user.uid))
}).then(() => {
history.push('/');
});
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.
When setting up a simple form - 2 buttons with 2 functions to test firebase's auth, i have a problem with sign out.
The sign in function works perfect.
However, sign out doesn't send any XHR. Nothing, nada. No errors.
But the promise resolves.
The console logs 'Signed Out'.
What am i doing wrong?
Thanks!
function signIn() {
firebase.auth().signInWithEmailAndPassword('email#email.com', 'password')
.then(() => {
console.log('Logged in')
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage)
});
}
function signOut() {
firebase.auth().signOut().then(() => {
console.log('Signed out!')
}).catch((error) => { console.log(error) });
}
Signing out just involves "forgetting" the refresh token that's used to keep the user signed in persistently over time. The server doesn't need to be notified that this happened.