Management

Manage Groups

Groups allow Workspace admins to easily modify and control access to database connections and Collection membership for logical clusters of members with similar needs (e.g., departments, project teams, etc.). This example shows various endpoints that let you create groups, add users to groups, or remove users from groups.

Note: Spaces have been rebranded as Collections in Mode, but the API will continue to refer to spaces. The spaces object and resources are the same as Collections in the Mode UI.

Endpoints used

.../{workspace}/groups
Supported methods:

  • GET: returns a list of groups in your Workspace.
  • POST: creates a new group

.../{workspace}/groups/{group_token}/memberships
Supported methods:

  • GET: returns a list of memberships in a given group
  • POST: adds a new member to a given group

.../{workspace}/groups/{group_token}/memberships/{membership_token}
Supported methods:

  • GET: returns a group membership
  • DELETE: removes a member from a group

How this example works

This code example encapsulates creating a group, adding a user to a group, and removing a user from a group. There are helper functions such as get_group_token, get_membership_token, and get_group_membership_token that return necessary tokens to be used in the API paths. Based on what you need, you could use one method at a time in your own script, for example, add_user_to_group, and include the helper functions for add_user_to_group: get_group_token and get_membership_token.

To try it yourself

  • Download the example code to a .py file
  • Input the API token, API secret, Workspace name, and other custom information as needed. Follow these steps to create an API token.
  • Save the .py file in your desired directory
  • Open the terminal and navigate to that directory
  • Run the command python3 {file_name}.py
  • All of our Python recipes require Python 3
import json
import requests

from requests.auth import HTTPBasicAuth


host = 'https://modeanalytics.com'
ws = 'workspace_name' # Note: workspace_name value should be all lowercase
un = 'api token'
pw = 'api secret'


def create_group(group_name):
  url = '%s/api/%s/groups' %(host, ws)
  headers = {'Content-Type': 'application/json'}
  payload = {'embed[new_group_membership]':'1', 'user_group':{'name': group_name}}
  r = requests.post(url, auth=HTTPBasicAuth(un, pw), headers=headers, json=payload)
  result = r.json()
  return result


def add_user_to_group(group,username):
  group_token = get_group_token(group)
  member_token = get_membership_token(username)

  url = '%s/api/%s/groups/%s/memberships' % (host, ws, group_token)
  headers = {'Content-Type': 'application/json'}
  payload = {'embed[member]':'1', 'membership':{'member_token':member_token}}
  r = requests.post(url, auth=HTTPBasicAuth(un, pw), headers=headers, json=payload)

  return r.json()

def remove_user_from_group(group,username):
  group_token = get_group_token(group)
  member_token = get_membership_token(username)
  membership_token = get_group_membership_token(group_token, member_token)

  url = '%s/api/%s/groups/%s/memberships/%s' % (host, ws, group_token, membership_token)
  headers = {'Content-Type': 'application/json'}
  r = requests.delete(url=url, auth=HTTPBasicAuth(un, pw), headers=headers)
  return r.json()


def get_group_token(group_name):
  url = '%s/api/%s/groups' % (host, ws)
  r = requests.get(url, auth=HTTPBasicAuth(un, pw))
  result = r.json()

  groups = result['_embedded']['groups']
  selected_group = [g['token'] for g in groups if g['name'] == group_name]

  return selected_group[0]

def get_membership_token(username):
  group_token = get_group_token('Everyone')
  url = '%s/api/%s/groups/%s/memberships' % (host, ws, group_token)
  r = requests.get(url, auth=HTTPBasicAuth(un, pw))
  result = r.json()
  members = result['_embedded']['group_memberships']
  selected_member = [m['member_token'] for m in members if m['_links']['member']['href'] == '/api/%s' % username]
  return selected_member[0]


def get_group_membership_token(group_token, member_token):
  url = '%s/api/%s/groups/%s/memberships' % (host, ws, group_token)
  r = requests.get(url, auth=HTTPBasicAuth(un, pw))
  result = r.json()

  members = result['_embedded']['group_memberships']
  selected_member = [m['token'] for m in members if m['member_token'] == member_token]

  return selected_member[0]

create_group('group_name')
add_user_to_group('group_name','user_name')
remove_user_from_group('group_name','username')
const request = require('request-promise');

const host = 'https://modeanalytics.com';
const ws = 'workspaceName'; // Note: workspaceName value should be all lowercase
const username = 'apiToken';
const password = 'apiSecret';

const createGroup = async groupName => {
  const payload = {
    embed: {
      new_group_membership: 1,
    },
    user_group: {
      name: groupName,
    },
  };

  const res = await request({
    method: 'POST',
    url: `${host}/api/${ws}/groups`,
    auth: { username, password },
    json: true,
    body: payload,
  });
  return res;
};

const addUserToGroup = async (group, userName) => {
  const groupToken = await getGroupToken(group);
  const memberToken = await getMemberToken(userName);

  const payload = {
    embed: {
      member: 1,
    },
    membership: {
      member_token: memberToken,
    },
  };
  const res = await request({
    url: `${host}/api/${ws}/groups/${groupToken}/memberships`,
    method: 'POST',
    auth: { username, password },
    json: true,
    body: payload,
  });
  return res;
};

const removeUserFromGroup = async (group, userName) => {
  const groupToken = await getGroupToken(group);
  const memberToken = await getMemberToken(userName);
  const membershipToken = await getGroupMembershipToken(groupToken, memberToken);

  return await request({
    url: `${host}/api/${ws}/groups/${groupToken}/memberships/${membershipToken}`,
    method: 'DELETE',
    json: true,
    auth: { username, password },
  });
};

const getMemberToken = async userName => {
  const groupToken = await getGroupToken('Everyone');
  const res = await request({
    url: `${host}/api/${ws}/groups/${groupToken}/memberships`,
    auth: { username, password },
    json: true,
  });
  return res._embedded.group_memberships.filter(m => m._links.member.href === `/api/${userName}`)[0].member_token;
};

const getGroupToken = async group => {
  const groups = await request({
    url: `${host}/api/${ws}/groups`,
    json: true,
    auth: { username, password },
  });
  return groups._embedded.groups.filter(group => group.name = group)[0].token;
};

const getGroupMembershipToken = async (groupToken, memberToken) => {
  const res = await request({
    url: `${host}/api/${ws}/groups/${groupToken}/memberships`,
    auth: { username, password },
    json: true,
  });

  return res._embedded.group_memberships.filter(m => m.member_token === memberToken )[0].token;
};

createGroup('groupName');
addUserToGroup('groupName', 'userName');
removeUserFromGroup('groupName', 'username');