Skip to main content

Assign a role to a user with the Go SDK

Permit.Api.Users.AssignRole() assigns a role to a user within one tenant. The role applies only in that tenant. This reference is for Go developers who grant permissions from backend code. To assign a role on one resource instance, such as a single document, use Users.AssignResourceRole.

Users.AssignRole signature

func (u *Users) AssignRole(ctx context.Context, userKey string, roleKey string, tenantKey string) (*models.RoleAssignmentRead, error)

Users.AssignRole parameters

ParameterTypeRequiredDescription
ctxcontext.ContextYesThe context of the request.
userKeystringYesThe key of the user who gets the role.
roleKeystringYesThe key of the role to assign.
tenantKeystringYesThe key of the tenant in which the role applies. Use default for the default tenant.

Example: assign a role with Users.AssignRole

The example uses a client named Permit, created with permit.NewPermit() as shown in Check permissions with the Go SDK, and a ctx of type context.Context. Replace user-key, role-key, and tenant-key with your own keys:

roleAssignment, err := Permit.Api.Users.AssignRole(ctx, "user-key", "role-key", "tenant-key")

Users.AssignRole return value and errors

On success, Users.AssignRole returns a *models.RoleAssignmentRead that describes the new role assignment, including the user, the role, and the tenant.

If the call fails, err holds an errors.PermitError from the github.com/permitio/permit-golang/pkg/errors package. Its StatusCode field has the HTTP status, and its ErrorCode field has one of these codes:

ErrorCodeCause
NotFoundHTTP 404: the Permit API can't find the user, the role, or the tenant in the environment.
UnprocessableEntityErrorHTTP 422: an argument failed validation.
Unauthorized, ForbiddenAccessHTTP 401 or 403: the API key is invalid or has no access to the environment.
UnexpectedErrorA server error (HTTP 5xx) or a network error.