Delete grants on post password change

I am trying to write a custom action that upon a user changing their password, will delete any existing grants and device credentials. I’ve gone through the password change flow and I’m not seeing any logs showing up. I’m not sure if I wrote this correctly. Can anyone help? I’ve tried running the action manually but this type of thing can’t be tested through the run method.

exports.onExecutePostChangePassword = async (event, api) => {
  const { ManagementClient } = require("auth0");
  const { DOMAIN, CLIENT_ID, CLIENT_SECRET } = event.secrets || {};
  const management = new ManagementClient({
    domain: DOMAIN,
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    scope: 'read:grants delete:grants read:device_credentials delete:device_credentials'
  });
  try {
    // Delete all grants
    const grantManager = management.grants;
    const grants = await grantManager.getAll({ user_id: event.user.user_id });
    if (Array.isArray(grants)) {
      for (const grant of grants) {
        await grantManager.deleteByUserId({ user_id: event.user.user_id })
      }
      console.log(`Successfully deleted grants for user ${event.user.user_id}`);
    } else {
      console.log("No grants found");
    }
  } catch (error) {
    console.error(`Error deleting grants for user ${event.user.user_id}:`, error);
    // Optionally, throw an error
    // throw new Error('Failed to revoke user sessions.');
  }
  try {
    // Delete all device credentials (refresh tokens)
    const deviceCredentialsManager = management.deviceCredentials;
    const deviceCredentials = await deviceCredentialsManager.getAll({
      user_id: event.user.user_id,
      type: 'refresh_token'
    });
    if (Array.isArray(deviceCredentials)) {
      for (const deviceCredential of deviceCredentials) {
        await deviceCredentialsManager.delete({ id: deviceCredential.id})
      }
      console.log(`Successfully deleted device credentials for user ${event.user.user_id}`);
    } else {
      console.log("No device credentials found");
    }
  } catch (error) {
    console.error(`Error deleting device credentials for user ${event.user.user_id}:`, error);
    // Optionally, throw an error
    // throw new Error('Failed to revoke user device credentials.');
  }
};

Hi @shafty023,

I have reviewed your Post Change Password action script, and it looks good and calls all the appropriate methods.

If you need to view the logs for the password change flow, you can use the Real-time Webtask Logs Extension to see your console.log() statements in real-time as you test the password change flow.

Let me know if you have any follow-up questions.

Thanks,
Rueben

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