How to add a hook for password under user.ts

default discord avatar
clhomelast year
1 2

I need to determine whether the password strength meets the requirements when the user sets or changes the password. How can I set it up?
I can`t find password in user.ts,
How to add a hook for password under user.ts

  • Selected Answer
    discord user avatar
    DanRibbens
    last year

    @clhome
    Here is a code example for you:

    /**
     * Throws error if password strength is not met. Password must have:
     *  - 8 or more characters
     *  - uppercase and lowercase letters
     *  - at least one symbol
    **/
    const validatePassword: CollectionBeforeValidateHook = ({ data: { password } }) => {
      let message: string;
      if (password.length <= 8) message = 'Password must be at least 8 characters long';
    
      const hasUpperCase = /[A-Z]/.test(password);
      const hasLowerCase = /[a-z]/.test(password);
      if (!hasUpperCase || !hasLowerCase) message = 'Password must have both uppercase and lowercase letters')
    
      const hasSymbols = /[$-/:-?{-~!"^_`\[\]]/.test(password);
      if (!hasSymbols) message = 'Password must include at least one symbol.'
    
      if (message) throw new ValidationError([{ message, field: 'password'}]);
    };
    
    // if you don't have a users collection already you need to make one to set the beforeValidate hook:
    const Users: CollectionConfig = {
      slug: 'users',
      auth: true,
      hooks: {
        beforeValidate: [validatePassword],
      },
      fields: [],
    }
    2 replies
  • default discord avatar
    clhomelast year

    Thank you very much, The problem has been resolved.

  • default discord avatar
    gycsabeszlast year

    @DanRibbens this won't get triggered before reset password API call (/api/[collection-slug]/reset-password). Moreover, it seems like none of the hooks gets triggered in that case. :( Any idea how to overcome this?

    Payload CMS version: 1.10.4

  • discord user avatar
    DanRibbens
    last year

    Great question!
    This has to be done in a beforeValidate function on the auth collection.

    1 reply
    default discord avatar
    clhomelast year

    sorry,I don't understand where to write beforeValidate , can you give me an example, thank you.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.