Skip to content

Instantly share code, notes, and snippets.

@joshcanhelp
Last active November 14, 2022 23:20
Show Gist options
  • Save joshcanhelp/bee9bff4d4bacad90e91b0f0188ca7f4 to your computer and use it in GitHub Desktop.
Save joshcanhelp/bee9bff4d4bacad90e91b0f0188ca7f4 to your computer and use it in GitHub Desktop.
Auth0 Action to check a WordPress migration endpoint for the existence of a user.
const axios = require("axios");
const customClaimNamespace = "https://wp/has_account";
exports.onExecutePostLogin = async (event, api) => {
const {
WP_API_CLIENT_ID,
WP_API_IDENTIFIER,
WP_API_BASE_URL,
WP_API_TOKEN,
} = event.secrets;
if (!event.user.email) {
console.log("User does not have an email to use. Skipping ...");
return;
}
if (!WP_API_IDENTIFIER || !WP_API_BASE_URL || !WP_API_TOKEN) {
console.log("Missing required configuration. Skipping ...");
return;
}
if (event.client.client_id === WP_API_CLIENT_ID) {
console.log("Logging into WP application. Skipping ...");
return;
}
const { query = {} } = event.request || {};
if (!query.audience || query.audience !== WP_API_IDENTIFIER) {
console.log(`Not requesting a WP API token. Skipping ...`);
return;
}
api.idToken.setCustomClaim(customClaimNamespace, false);
const formData = new URLSearchParams({ username: event.user.email });
const getUserUrl = new URL(WP_API_BASE_URL);
getUserUrl.pathname = "index.php";
getUserUrl.search = "a0_action=migration-ws-get-user";
let apiResponse;
try {
apiResponse = await axios.post(
getUserUrl.toString(),
formData.toString(), {
headers: {
Authorization: `Bearer ${WP_API_TOKEN}`,
"Content-Type": "application/x-www-form-urlencoded",
},
});
} catch (apiHttpError) {
console.log(`Error calling the WP API: ${apiHttpError.message}`);
return;
}
if (apiResponse.data.error) {
console.log(`Error returned from the WP API: ${apiResponse.data.error}`);
return;
}
if (apiResponse.data.ID) {
api.idToken.setCustomClaim(customClaimNamespace, true);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment