How to Trigger Password Reset From Post User Login Action

Hi,

Is this possible? I’m checking for the value of an app attribute in the profile, and if true I want to trigger the Password Rest email to them.

Thanks

Hey @rot welcome to the community!

This should definitely be possible - In the following example I’m using the node management client to check for a specific flag in a user’s app_metadata and triggering a password reset email accordingly:

const { ManagementClient } = require('auth0');

exports.onExecutePostLogin = async (event, api) => {
  // Initialize the Management Client
  const management = new ManagementClient({
    token: event.secrets.MANAGEMENT_API_TOKEN,
    domain: event.secrets.DOMAIN
  });

  // Check the app_metadata directly
  if (event.user.app_metadata && event.user.app_metadata.triggerPasswordReset) {
    // Trigger password reset email
    await management.sendPasswordChangeEmail({ user_id: event.user.user_id });
  }
};

1 Like

Thanks, so it doesn’t seem to be triggering any email. It is falling into the if statement correctly though. No errors when testing it either :confused:

1 Like

Thanks for the heads up! My apologies, it looks like that example may have worked in the past but the way in which you trigger a password reset email has changed :confused: The following should be accurate and up to date:

const AuthenticationClient = require('auth0').AuthenticationClient;

exports.onExecutePostLogin = async (event, api) => {

    var auth0 = new AuthenticationClient({
        domain: event.secrets.AUTH0_DOMAIN,
        clientId: event.secrets.CLIENT_ID,
        clientSecret: event.secrets.CLIENT_SECRET
      });

    const data = {
        email: event.user.email, // The user's email address
        connection: 'Username-Password-Authentication', // The name of your database connection in Auth0 (only works for database connections)
      };
      
    auth0.database.changePassword(data)
        .then(response => {
          console.log('Password change email sent:', response);
        })
        .catch(error => {
          console.error('Error sending password change email:', error);
        });
}
1 Like

Ok so… Yes the code works thank you.

The issue I have now is when it runs, what I actually wanted to happened was for this to run when a user tries to login and fails (because they are newly migrated and therefore do not have a password set).

However it seems the Login action only runs Post-Login. I wonder if my use case is possible or not…? Where it would run Post-Login-Fail…

1 Like

Ah, gotcha! Thanks for clarifying - It sounds like the following is what you are looking for:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.