Managing a User’s Groups

Problem

You want to view or adjust a user’s group memberships.

Solution

from posit.connect import Client

client = Client()

group_guid = "GROUP_GUID_HERE"
user_guid = "USER_GUID_HERE"

# Get user and group objects
group = client.groups.get(group_guid)
user = client.users.get(user_guid)


# View groups that a user belongs to
user_groups = user.groups.find()

# Add user to a group
user.groups.add(group)

# Remove user from a group
user.groups.delete(group)
library(connectapi)
library(dplyr)
library(purrr)

client <- connect()

group_guid = "GROUP_GUID_HERE"
user_guid = "USER_GUID_HERE"

# View groups that a user belongs to
user_groups <-
  get_groups(client) %>%
  mutate(
    members = map(guid, ~ get_group_members(client, .x))
  ) %>%
  filter(map_lgl(members, ~ nrow(.x) > 0)) %>%
  filter(map_lgl(members, ~ user_guid %in% .x$guid)) %>%
  mutate(members = NULL)

# Add a user to a group
client$PUT(paste0("groups/", group_guid, "/members"), body=list(user_guid=user_guid))

# Remove a user from a group
client$DELETE(paste0("groups/", group_guid, "/members/", user_guid))