Is there a way to restrict users from community creation

Hi, I’m using ts-sdk 6.19.0.
In my app I need to restrict users from community creation. I need to make sure that communities is going to be created only by admins. Is there a way to do something like this:

  • user goes to a page of community which is not already created
  • current user is logged out and we login admin user
  • admin user calls CommunityRepository.createCommunity
  • after success admin user is logged out and we login regular user back

Now when I try to do that I receive this type of errors Uncaught Error: client disconnecting at MqttClient._checkDisconnecting.
Is this flow possible or should we create communities manually through Amity console?

Hello, to restrict the creation of communities by users, we recommend utilizing the user’s role. You can detect their role, and if they are assigned the ‘member’ role, then hide the ‘create community’ button from their visibility.

For more information about role, please see here: Moderation, Roles & Privileges | Amity Docs

@amitysupport yes, I’ve used roles to restrict this behaviour. But that doesn’t really resolve my question about if flow I’ve mentioned is possible or not. Is it possible to logout current user and login an admin one when regular user tries to create a community?
I’ve tried to do it like this but I’ve faced Uncaught Error: client disconnecting at MqttClient._checkDisconnecting errors.

const useCreateOrFindCommunity = (communityId: string) => {
  const [currentUser, setCurrentUser] = useState<currentUserInfo>({
    userId: '',
    displayName: '',
  });
  const [community, setCommunity] = useState<Amity.Community[]>([]);
  const [communityExists, setCommunityExists] = useState<boolean>(false);
  const loggedInUser = useGetUser(client.userId || '');
  const { connectedToSocial } = useAppSelector(userSelectors.getUser);
  const dispatch = useAppDispatch();

  useEffect(() => {
    if (communityId && connectedToSocial) {
      const unsubscribe = CommunityRepository.getCommunities(
        { displayName: communityId },
        ({ data, loading, error }) => {
          if (error) {
            console.log('error fetching communities', error);
            return;
          }

          if (!loading) {
            setCommunityExists(!!data.length);
            setCommunity(data);
          }
        }
      );

      unsubscribe();
    }
  }, [communityId, connectedToSocial]);

  useEffect(() => {
    if (connectedToSocial && communityId && loggedInUser && !communityExists) {
      if (loggedInUser.roles.includes('global-admin')) {
        console.log('logged as admin');
        try {
          (async () => {
            const createdCommunity = await communityApi.create(
              communityId,
              currentUser.userId
            );

            return setCommunity([createdCommunity.data]);
          })();
        } catch (error) {
          console.log(error);
        }
      } else {
        setCurrentUser({
          userId: loggedInUser.userId,
          displayName: loggedInUser.displayName!,
        });
        try {
          clientApi.disconnectClient()
            .then((disconnected) => {
              console.log('disconnected', disconnected);
            })
            .catch((error) => {
              console.log('error while disconnecting', error);
            });
          if (disconnected) {
            const status = await Client.login(
              {
                userId: 'firstUser',
                displayName: 'firstUser',
              },
              sessionHandler
            );
            console.log('User logged in', status);
            dispatch(userActions.toggleIsConnectedToSocial(status));
            dispatch(userActions.toggleIsConnectedToSocial(false));
          }
        } catch (error) {
          console.log(error);
        }
      }
    }
  }, [communityExists, communityId, loggedInUser, connectedToSocial]);

  return community;
};

Your use case appears to be unique. Could you please provide further details and share the frontend flow with us? We’d like to understand ‘when regular user tries to create a community’ because the solution we recommended, it needs to be handled on the frontend as well, by detecting the user’s role and hide the button. Normal users shouldn’t be able to attempt to create a community.

Additionally, why is it necessary to log in again as an admin? Is this all happening on the same device? Clarifying these points will help us better assist you.

Yes, it is happening on the same device. The idea behind logging in as an admin is to create communities only as admin user.
The frontend flow doesn’t have explicit community creation. We have a page with a list of items, when a user clicks on some item app redirects him to a page where item details are shown, and also comments of users who follow this item, interested in his updates etc. The idea is, when user clicks an item, which currently doesn’t have created community in Amity, app should logout current user if he doesn’t have global-admin role and login an admin which does have this role. If user has this role, community is created, if it doesn’t exist, and returned from the hook. After that admin user is logged out and current user is logged in back into the app.

Thank you very much for your clarification. Let us consult with the team, and we will get back to you.

1 Like

After consulting with the team, to streamline your workflow, we suggest implementing an API call with the following steps: If the user’s role is not the global admin, proceed to create the community with the admin token. This eliminates the need to log out the normal user and then log in as the admin again, reducing complexity. This approach ensures the same outcome of creating the community while simplifying the process.

If you prefer to stick with your current flow, ensure that it is executed across different devices and users. We recommend avoiding the step where you log out the normal user and log in as the admin on the same device. This should prevent any errors from occurring.

Your suggestion works exactly how we’ve wanted it to work. Thank you!

1 Like