Assign a user role when a user logs in using Google
-
Hey, I am just curious if it's possible for us to assign user role if we choose to do login using Google as identity provider (we directly call Google for sign in, then link the user to FusionAuth, as per this guide).
To elaborate more, let's say we want user to be assigned to the user role upon sign in. But if the user email is under the domain @example.com, we want to assign them as teacher role. Would it be possible?
-
This is possible today using a Google Reconcile Lambda. Our Lambdas allow arbitrary JavaScript to be executed during a login event. You can write logic to check the user's domain and assign them the appropriate role associated with the FusionAuth Application they're authenticating through.
Below is a code example demonstrating how you could implement such logic:
function reconcile(user, registration, idToken) { function extractDomain(email) { // Split the email address by '@' symbol var parts = email.split('@'); // Return the second part which represents the domain name return parts[1]; } // function to extract the email domain from the user object and stores in domain variable var domain = extractDomain(user.email); // Conditional statement checks domain for fusionauth.io and adds 'counsellor' role, if any other domain exist adds 'user' role if (domain === 'example.com') { registration.roles.push('teacher'); } else { registration.roles.push('user'); } //This is optional, but is good to have for debugging purposes. The results will be returned in the event logs. console.info(registration.roles); }
-