FusionAuth
    • Home
    • Categories
    • Recent
    • Popular
    • Pricing
    • Contact us
    • Docs
    • Login

    Assign a user role when a user logs in using Google

    Scheduled Pinned Locked Moved Solved
    Q&A
    1
    2
    1.2k
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • danD
      dan
      last edited by

      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?

      --
      FusionAuth - Auth for devs, built by devs.
      https://fusionauth.io

      danD 1 Reply Last reply Reply Quote 0
      • danD
        dan @dan
        last edited by

        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);
        
        }
        
        

        --
        FusionAuth - Auth for devs, built by devs.
        https://fusionauth.io

        1 Reply Last reply Reply Quote 0
        • danD dan has marked this topic as solved on
        • First post
          Last post