Like what we’re doing? Star us on GitHub!

Conditional verification email

TheFrontend
3 weeks ago
10

Is there a way to conditionally send verification emails upon account creation?


I'm currently creating a plugin for Google Authentication and I'd like to not send verification emails if a user signs up with Google. As the default Email / Password auth is still active, verification emails should be send here.



Also, it looks like I can not create a new already verified account. It takes two steps: create an account and then update _verified: true.



As I can see I can only pass 'true' or 'generateEmailHTML' for ´´´verify´´´ option in a collection config.

  • thisisnotchris
    3 weeks ago

    @TheFrontend You cant alter the _verified prop once they auth with Google?

  • TheFrontend
    3 weeks ago

    I can, but not before the email is sent.



     const registered = await payload.create({
              collection: 'users',
              showHiddenFields: true,
              data: {
                email: user.email,
                name: user?.name,
                password: pw,
                oauth: pw,
                loginMethod: 'google',
              },
            })


    Now the email is sent, before I can update the _verified. I can login directly but the email is still sent.



    await payload.update({
                  id: registered.id,
                  collection: 'users',
                  data: {
                      _verified: true,
                  },
              });
  • thisisnotchris
    3 weeks ago

    @TheFrontend Unless there is a better way..



    How about disabling email



    And then manually calling

    payload.sendEmail(message)


    on creation of a user with the type you want

  • denolfe
    Payload Team
    3 weeks ago

    We've done something similar in the past by using a

    beforeOperation

    hook that contains the conditional logic for setting

    disableVerificationEmail

    . Let me post a snippet



    This used a previous Payload version, but still should be good.



    import type { CollectionBeforeOperationHook } from 'payload/types';
    
    const skipVerificationEmail: CollectionBeforeOperationHook = ({ args, operation }) => {
      if (operation === 'create' && args.req.query && typeof args.req.query.checkout !== 'undefined') {
        return {
          ...args,
          disableVerificationEmail: true,
        };
      }
    
      return args;
    };


    Just change up the conditional. You

    should

    have access to the user off of req

  • TheFrontend
    3 weeks ago

    Works perfectly, thanks!

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More