Automatic role assignment to new users of the website

I have been trying for while to automatically assign roles to users while signing up to my website. While the code works for most of the cases, it is inconsistent in some of the cases. Can anyone help with my issue?

Below there is my code:

import wixUsers from 'wix-users';
import wixLocation from 'wix-location';
import { assignRole } from 'backend/assignRole';
import { checkEmailExists } from 'backend/checkEmailExists';
import { deleteInvalidMembers } from 'backend/deleteInvalidUser';
import { currentMember } from 'wix-members-frontend';

$w.onReady(function () {
    // Handle user registration
    $w('#button1').onClick(async () => {
        try {
            // Get form values
            const firstName = $w('#input4').value;
            const lastName = $w('#input3').value;
            const email = $w('#input5').value;
            const password = $w('#input1').value;
            const role = $w('#radioGroup1').value;

            // Check if email already exists
            const emailExists = await checkEmailExists(email);
            
            // If email exists, show error and return
            if (emailExists) {
                // You can uncomment and customize this if needed
                // $w('#errorMessage').text = 'This email already exists';
                // $w('#errorMessage').show();
                console.error("Email already exists! Try another.");
                return;
            }

            // Register the user
            const result = await wixUsers.register(email, password, {
                contactInfo: {
                    firstName: firstName,
                    lastName: lastName,
                    emails: [email],
                }
            });

            console.log("User registered:", result.user);
            const user = result.user;

            // Log the user in
            await wixUsers.login(email, password);
            console.log("User logged in:", user);

            // Assign role to the user based on selection
            const tenantRoleID = TenantRoleID;
            const landlordRoleID = LandlordRoleID;

            let roleToAssign;
            if (role === 'Tenant') {
                roleToAssign = tenantRoleID;
            } else if (role === 'Landlord') {
                roleToAssign = landlordRoleID;
            } else {
                throw new Error("Invalid role selected");
            }

            // Assign role
            const assignRoleResult = await assignRole(roleToAssign, user.id);

            if (assignRoleResult.success) {
                console.log("Role assigned:", roleToAssign);
                
                // CRITICAL FIX: Wait to ensure role assignment is processed
                await new Promise(resolve => setTimeout(resolve, 3000));
                
                // Make profile private (moved from separate handler)
                await currentMember.makeProfilePrivate();
                console.log("Profile set to private");
                
                // Redirect to welcome page
                console.log("Redirecting to welcome page");
                wixLocation.to('/user-dashboard');
            } else {
                console.error("Error during role assignment:", assignRoleResult.error);
            }
        } catch (err) {
            console.error("Error during user registration or role assignment:", err);
        }
    });
    
    // Helper function to get member details (kept separate)
    $w('#button1').onClick(() => {
        currentMember.getMember({ fieldsets: ['FULL'] })
            .then((member) => {
                console.log("Member details:", member);
                const id = member._id;
                const fullName = `${member.contactDetails.firstName} ${member.contactDetails.lastName}`;
                console.log("Member ID:", id);
                console.log("Full Name:", fullName);
            })
            .catch((error) => {
                console.error("Error getting member details:", error);
            });
    });
});

// This runs when the built-in registration form is submitted
// (only needed if you're using the built-in form alongside custom logic)
$w('#registrationForm1').onWixFormSubmitted((event) => {
   setTimeout(() => {
      wixLocation.to(wixLocation.url); // Reloads the current page
    }, 2500); // 2500 milliseconds = 2.5 seconds
});  

The code for the assignRole is stored in assignRole.jsw file:

import { roles } from 'wix-users-backend';

export function assignRole(roleId, memberId) {
    return roles.assignRole(roleId, memberId, { suppressAuth: true })
        .then(() => {
            console.log("Role assigned to member:", memberId);
            return { success: true };
        })
        .catch((error) => {
            console.error("Error assigning role:", error);
            return { success: false, error };
        });
} 

Thank you in advance.

1 Like

Hi, @CBouf !!

Hello. I’m not entirely sure what the cause is, but I was wondering if the place in the code where you’re currently pausing the process might work better if it were adjusted slightly. :thinking:

const assignRoleResult = await assignRole(roleToAssign, user.id);
await new Promise(resolve => setTimeout(resolve, 3000));
// ↓
await new Promise(resolve => setTimeout(resolve, 3000));
const assignRoleResult = await assignRole(roleToAssign, user.id);

Also, I noticed that you’re reloading the current page after the registration form is submitted, but if the goal is simply to reset the UI, it might be enough to just clear the input fields instead. I’m not sure if this is related to the issue, but since wix-users has been deprecated for quite some time, it might be better to avoid using it. Using it alongside member-related APIs like wix-members-frontend could also be a potential source of confusion. :upside_down_face:

1 Like