In my application (SPA React), I use Moodle to authenticate my users by creating a custom social connection in Auth0 named “moodle-oauth2” with a corresponding organization “Moodle shell org“ with auto-provisioning turned on.
The flow is described as follows:
- User lands on my application
- auth0-react sdk logs the user in with connection “moodle-oauth2“
- The user is redirected to Moodle for login, then given consent to Auth0
- Finally, the user logs in to my application with “Moodle shell org”
The desired result is that in the post-login action, I want to assign the user to the corresponding organization based on their email domain, and remove the user from the Moodle shell org. Additionally, I want to authenticate the user into the new organization instead of the Moodle shell org.
I know how to assign and remove users from an organization. After this step, how can I re-authenticate them to the new org context?
Here is my script:
exports.onExecutePostLogin = async (event, api) => {
const moodleAcademyOrgId = "org_X6b3smoodle"
// Only assign user's organization when the user comes from moodle
if (event.connection.name !== "moodle-oauth2") {
return
}
const email = event.user.email
if (!email) return
const isFirstLogin = event.stats.logins_count == 1
if (!isFirstLogin) return
// Do nothing if there is already organization context
if (event.organization) {
if (event.organization.id !== moodleAcademyOrgId) {
console.log("Skip because already in organization context", event.organization.display_name)
return
}
}
const managementApi = new ManagementClient({
domain: event.secrets.DOMAIN,
clientId: event.secrets.CLIENT_ID,
clientSecret: event.secrets.CLIENT_SECRET,
})
try {
const orgId = "org_dedicated_org"
// Hardcode: assign user to a dedicated org
await managementApi.organizations.members.create(orgId, {
members: [event.user.user_id]
});
console.log("Successfully assign user to organization", event.user.user_id, orgId)
await managementApi.organizations.members.delete(moodleAcademyOrgId, {
members: [event.user.user_id]
});
console.log("Successfully remove user to organization", event.user.user_id, moodleAcademyOrgId)
// How to re-authenticate the user with the new org context
} catch (err) {
console.log("Organization assignment error:", err)
}
};