12

I need to add to my current code, the necessary functionality and the exact code so that the user must verify the email before logging in.

Now, the user registers and automatically accesses all the functions of the application and its user panel. I want to add the necessary function so that when a user registers, a message is shown telling him that: You must verify your email In this way we ensure that it is a valid email and avoid the registration of SPA users.

I need the user to verify her email to be able to log in, until she does, she can continue using the App as she did, without logging in.

You can see that I did several tests, and other users tried to help me, but we have not achieved what is necessary, since I need to add the functionality to the code that I have now, since it is the only way I know to continue building my application.

The app has registration with Firebase, registered by email and password and I'm using Formik to control the state of the form and Yup to validate.

I have read Firebase documentation about "Send a verification message to a user",

This is the Firebase function:

``` const auth = getAuth(); sendEmailVerification(auth.currentUser) .then(() => { // Email verification sent! // ... }) ``` 

The registration system I use now is Mail and Password. The user enters an email, a password, verifies the password and is automatically registered in the application.

I did several tests trying to add sendEmailVerification to my registration system, and for now what I have achieved is that the confirmation email arrives to the user (SPA folder) but the confirmation email arrives after the user already registered and use the app.

It would be necessary that the user could not register until receiving and confirming the "Confirmation Email"

I need a code example that fits my current app, I don't have the knowledge to change all my code, this is the base of my app.

What do I have to do so that this works correctly and the verification email arrives before the user can register? What am I doing wrong in my code?

I show the application on GitHub, so they can see all the files

You can test the project as it is built with Expo:

exp://exp.host/@miguelitolaparra/restaurantes-5-estrellas?release-channel=default

enter image description here

This is the method I'm using to register users:

const formik = useFormik({ initialValues: initialValues(), validationSchema: validationSchema(), // validate the form data validateOnChange: false, onSubmit: async(formValue) => { try { // send the data to Firebase const auth = getAuth() // sendEmailVerification(auth.currentUser) await createUserWithEmailAndPassword( auth, formValue.email, formValue.password ) sendEmailVerification(auth.currentUser) navigation.navigate(screen.account.account) } catch (error) { // We use Toast to display errors to the user Toast.show({ type: "error", position: "bottom", text1: "Failed to register, please try again later", }) } }, }) 

And I also show you the complete file:

import { useFormik } from 'formik' import { getAuth, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth' export function RegisterForm() { const [showPassword, setShowPassword] = useState(false) const [showRepeatPassword, setShowRepeatPassword] = useState(false) const navigation = useNavigation() const formik = useFormik({ initialValues: initialValues(), validationSchema: validationSchema(), // validate the form data validateOnChange: false, onSubmit: async (formValue) => { try { // send the data to Firebase const auth = getAuth() //sendEmailVerification(auth.currentUser) await createUserWithEmailAndPassword( auth, formValue.email, formValue.password ) sendEmailVerification(auth.currentUser) navigation.navigate(screen.account.account) } catch (error) { // We use Toast to display errors to the user Toast.show({ type: "error", position: "bottom", text1: "Error al registrarse, intentelo mas tarde", }) } }, }) // function to hide or show the password const showHidenPassword = () => setShowPassword((prevState) => !prevState) const showHidenRepeatPassword = () => setShowRepeatPassword((prevState) => !prevState) return ( // Registration form interface <View> <Input placeholder="Correo electronico" keyboardType="email-address" containerStyle={AuthStyles.input} rightIcon={ <Icon type="material-community" name="at" iconStyle={AuthStyles.icon} /> } onChangeText={(text) => formik.setFieldValue("email", text)} errorMessage={formik.errors.email} /> <Input placeholder="Contraseña" containerStyle={AuthStyles.input} secureTextEntry={showPassword ? false : true} rightIcon={ <Icon type="material-community" name={showPassword ? "eye-off-outline" : "eye-outline"} iconStyle={AuthStyles.icon} onPress={showHidenPassword} /> } onChangeText={(text) => formik.setFieldValue("password", text)} errorMessage={formik.errors.password} /> <Input placeholder="Repetir contraseña" containerStyle={AuthStyles.input} secureTextEntry={showRepeatPassword ? false : true} rightIcon={ <Icon type="material-community" name={showRepeatPassword ? "eye-off-outline" : "eye-outline"} iconStyle={AuthStyles.icon} onPress={showHidenRepeatPassword} /> } onChangeText={(text) => formik.setFieldValue("repeatPassword", text)} errorMessage={formik.errors.repeatPassword} /> <Button title="REGISTRATE" containerStyle={AuthStyles.btnContainer} buttonStyle={AuthStyles.btn} onPress={formik.handleSubmit} // send the form loading={formik.isSubmitting}// show loading while doing user registration /> </View> ) } 

And this is the file to validate the form with Yup RegistreFormValidar.js

import * as Yup from "yup" // object that has the elements of the form export function initialValues() { return { email: "", password: "", repeatPassword: "", } } // validate the form data whit Yup export function validationSchema() { return Yup.object({ email: Yup.string() .email("El email no es correcto") .required("El email es obligatorio"), password: Yup.string().required("La contraseña es obligatoria"), repeatPassword: Yup.string() // validate that the passwords are the same .required("La contraseña es obligatoria") .oneOf([Yup.ref("password")], "Las contraseñas tienen que ser iguales"), }) } 
13
  • 2
    Some sendmail servers support VRFY that lets you check the validity of an email address without sending email, but that's not universal. Also confirm that you can send any email at all Commented Aug 1, 2022 at 15:13
  • 1
    "Is there another method to verify that the Email is correct other than Sending a verification message to a user?" Can you clarify what you have in mind there? I understand what you don't want to do, but how do you then expect an email verification mechanism to work? Commented Aug 1, 2022 at 15:27
  • 2
    "the confirmation message does not arrive in his email" This most likely means it's being marked as spam, either on their system or before it even reaches that. Have the user's check their spam folder, and see stackoverflow.com/questions/72922475/… Commented Aug 1, 2022 at 15:28
  • 1
    OK, just try sending any email to yourself just to make sure you have "email sending" enabled in Firebase Commented Aug 1, 2022 at 15:29
  • 1
    In order to send an email to a user, that user has to be signed in to Firebase Authentication. Whether you allow anyone who is signed in to use your app and access data, is up to you though and is specific to each app (plenty of apps don't require email verification, so Firebase can't require this on an API level). If you want to only allow them to do so after they verified their email address, you can check for that in their token/profile in the client-side code, in any server-side code you have, and in the security rules of your database and storage. Commented Aug 1, 2022 at 16:12

4 Answers 4

3
+75

You have several options to achieve your purpose. First, to fix the SPA issue, you can use a custom domain, as shown on Firebase

To get what you are looking for, you can follow these steps: 1 - The user registers with an email address. 2 - The new record is created, but with status "To be verified" and an activation string is assigned. 3 - You send user data and activation string, along with a link to verify registration. 4 - The user clicks on the link, enters their data and, if they are valid, you change the status to "Active".

You can try to do it. You also have the option to do it with "Authenticate with Firebase via email link"

  • For users to sign in via an email link, you must first enable the Email Provider and Email Link sign-in method for your Firebase project.

-Then send an authentication link to the user's email address.

To start the authentication process, show the user an interface that prompts them to enter their email address, then call sendSignInLinkToEmail to ask Firebase to send the authentication link to the user's email.

You can see all the details in the official Firebase documentation 1 - Build the ActionCodeSettings object, which provides Firebase with instructions to build the email link

const actionCodeSettings = { // URL you want to redirect back to. The domain (www.example.com) for this // URL must be in the authorized domains list in the Firebase Console. url: 'https://www.example.com/finishSignUp?cartId=1234', // This must be true. handleCodeInApp: true, iOS: { bundleId: 'com.example.ios' }, android: { packageName: 'com.example.android', installApp: true, minimumVersion: '12' }, dynamicLinkDomain: 'example.page.link' }; 

2 - Ask the user for the email.

3 - Send the authentication link to the user's email and save their email in case the user completes the login with email on the same device

import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; const auth = getAuth(); sendSignInLinkToEmail(auth, email, actionCodeSettings) .then(() => { // The link was successfully sent. Inform the user. // Save the email locally so you don't need to ask the user for it again // if they open the link on the same device. window.localStorage.setItem('emailForSignIn', email); // ... }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; // ... }); 

Finally complete the access with the email link.

This is not exactly what you are looking for, but it may help.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is interesting @MariaCruzFernandez, but I can't accept it because it's not what I'm looking for.
0

As far as I understood, you need to verify email address of the user first, then create the user. Blocking functions maybe what you need.

exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => { const locale = context.locale; if (user.email && !user.emailVerified) { // Send custom email verification on sign-up. return admin.auth().generateEmailVerificationLink(user.email).then((link) => { return sendCustomVerificationEmail(user.email, link, locale); }); } }); 

This Firebase function will trigger before a new user is saved to the Firebase Authentication database, and before a token is returned to your client app. However, I think after this function executes, user is created. To prevent user creation you may have to implement a more complex flow.

One naive approach I can think of is as follows: After sending email to user, do not terminate the function and inside the function periodically check if user's email address is verified. Also set a timeout option and reject user creation after timeout. As expected, this approach increases the function execution time and can be costly.

If you are fine with the user being created in the Firebase Authentication database, I suggest implementing the solution stated in the documentation.

exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => { const locale = context.locale; if (user.email && !user.emailVerified) { // Send custom email verification on sign-up. return admin.auth().generateEmailVerificationLink(user.email).then((link) => { return sendCustomVerificationEmail(user.email, link, locale); }); } }); exports.beforeSignIn = functions.auth.user().beforeSignIn((user, context) => { if (user.email && !user.emailVerified) { throw new functions.auth.HttpsError( 'invalid-argument', `"${user.email}" needs to be verified before access is granted.`); } }); 

This will block users with unverified emails from logging into your app.

Check this documentation for other possible options: https://firebase.google.com/docs/auth/extend-with-blocking-functions#requiring_email_verification_on_registration

3 Comments

Thank you for the trouble you took to prepare your answer @ayseasude , it really is very good. The problem is that I don't know how or where I can add your example to my code. Can you give me more details of where I should place this ? Thanks, at the moment I can't accept your answer, I've read this too, but I don't know how to implement it in my file without breaking it too much
This piece of code is deployed with Firebase Functions so it is not on the client side. If you want to use these functions your project must be on Blaze plan and you must activate Firebase Authentication with Identity Platform. After deploying your function to the cloud, when a user signs in, it automatically runs (triggers).
I think this is not the most suitable for me, I'm sorry, as you can see, to offer the reward I said that I needed a detailed and functional answer. What you tell me I have already read, and anyone can add an answer like the one you have given. I'm sorry, I can't accept it. Thank you for your dedication @ayseasude And of course my app doesn't need a Blaze plan so far
0

Put this listener in your route You can tweak it according to your usage

 useEffect(() => { const unsubscribe = auth().onAuthStateChanged( async (user) => { if (user) { if (user.emailVerified) { store.setUser(user); } else { await user.sendEmailVerification(); auth() .signOut() .then(() => { store.resetStore(); store.setAlertModal('Please Verify Your Email'); }) .catch((error) => log.error('Signout Error', error)); } } } ); return () => { // Unsubscribe unsubscribe(); }; }, [store]); 

9 Comments

Where should I put this exactly friend @BhavyaKoshiya ? I don't know where to put it in my code
in your routing class or function where your navigation container is
I would be grateful if you help me. I show him the app on GitHub so he can tell me where to add this code snippet. I've done several tests and I haven't been able to get it to work. The bounty is about to end. can we get another
inside your AppNavigation.js
No problem dude, just sad that was not able to help you enough
|
0

I have the same case, without using Cloud functions I found one solution, it is not the most optimal, but it works. The essence of the solution: After registration, immediately log out.

if (!isRegistering) { setIsRegistering(true); try { /* if(!user){ throw Error("Telegram orqali kiring brodar") } */ const response = await doCreateUserWithEmailAndPassword(email, password); doSendEmailVerification(); logout() } catch (error) { setErrorMessage(error.message); } finally { setIsRegistering(false); } } 

And my logout() function:

async function logout() { await doSignOut(); setCurrentUser(null); setUserLoggedIn(false); setIsEmailUser(false); setLoading(false); navigate("/login"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.