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
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | The context of the request. |
userKey | string | Yes | The key of the user who gets the role. |
roleKey | string | Yes | The key of the role to assign. |
tenantKey | string | Yes | The 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:
ErrorCode | Cause |
|---|---|
NotFound | HTTP 404: the Permit API can't find the user, the role, or the tenant in the environment. |
UnprocessableEntityError | HTTP 422: an argument failed validation. |
Unauthorized, ForbiddenAccess | HTTP 401 or 403: the API key is invalid or has no access to the environment. |
UnexpectedError | A server error (HTTP 5xx) or a network error. |