Skip to content

Add users and groups to content item permissions #342

@schloerke

Description

@schloerke

Related: https://github.com/rstudio/connect/issues/28825 ; https://docs.posit.co/connect/cookbook/content-access-controls/granting-access-to-a-group/
Related: Granting Access to a User: https://docs.posit.co/connect/cookbook/content-access-controls/granting-access-to-a-user/

Current Group recipe:

from posit import connect

# 1. specify the guid for the content item
content_guid = "CONTENT_GUID_HERE"
# 2. specify either the guid or name for the group to be added (group_name will be used if group_guid is blank)
group_guid = ""
group_name = "GROUP_NAME_HERE"
# 3. specify if the group should be added as a "viewer" or "owner" (collaborator)
access_type = "viewer"

client = connect.Client()

# search by group_name to find the group_guid if blank
if not group_guid and group_name:
    group_match = client.get("/v1/groups", params={"prefix": group_name}).json()
    if not group_match["results"]:
        raise Exception("Invalid group name")
    elif len(group_match["results"]) != 1:
        raise Exception("More than one group name found, ensure you enter a unique name")
    else:
        group_guid = group_match["results"][0]["guid"]
elif not group_name:
    raise Exception("Either group_guid or group_name must be specified")

# For the specified content item add the desired group
client.content.get(content_guid).permissions.create(
    principal_guid=group_guid,
    principal_type="group",
    role=access_type,
    )

# Confirm new permissions
client.content.get(content_guid).permissions.find()

Current User recipe:

from posit import connect

# 1. specify the guid for the content item
content_guid = "CONTENT_GUID_HERE"
# 2. specify either the guid or username for the user being added (username will be used if user_guid is blank)
user_guid = ""
username = "USERNAME_HERE"
# 3. specify if the user should be added as a "viewer" or "owner" (collaborator)
access_type = "viewer"

client = connect.Client()

# search by username to find the user_guid if blank
if not user_guid and username:
    user_match = client.users.find(prefix=username)
    if not user_match:
        raise Exception("Invalid username")
    elif len(user_match) != 1:
        raise Exception("More than one username found, ensure you enter a unique name")
    else:
        user_guid = user_match[0]["guid"]
elif not username:
    raise Exception("Either user_guid or username must be specified")

# For the specified content item add the desired user
client.content.get(content_guid).permissions.create(
    principal_guid=user_guid,
    principal_type="user",
    role=access_type,
)

# Confirm new permissions
client.content.get(content_guid).permissions.find()

Metadata

Metadata

Assignees

Labels

sdkUsed for automation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions