Create a user with the Go SDK
Permit.Api.Users.Create() creates a user in the environment that your API key belongs to, so you can run permission checks on that user. This reference is for Go developers who sync users from backend code. To create a user or update the user if the key already exists, use Users.SyncUser instead.
Users.Create signature
func (u *Users) Create(ctx context.Context, userCreate models.UserCreate) (*models.UserRead, error)
Users.Create parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | The context of the request. |
userCreate | models.UserCreate | Yes | The user to create. Build it with models.NewUserCreate(key). |
UserCreate fields
| Field | Type | Required | Description |
|---|---|---|---|
Key | string | Yes | A unique ID by which Permit identifies the user. You pass the same key as the user in Permit.Check(). Use any value that is unique in your system, such as a user ID from your identity provider. |
Email | *string | No | The email of the user. Set it with SetEmail(). |
FirstName | *string | No | The first name of the user. Set it with SetFirstName(). |
LastName | *string | No | The last name of the user. Set it with SetLastName(). |
Attributes | map[string]interface{} | No | User attributes that attribute-based access control (ABAC) policies evaluate. Set them with SetAttributes(). |
Example: create a user with Users.Create
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.
Build the UserCreate struct with the key user-key, an email, a first and last name, and an age attribute:
user := models.NewUserCreate("user-key")
user.SetEmail("john@doe.com")
user.SetFirstName("John")
user.SetLastName("Doe")
user.SetAttributes(map[string]interface{}{
"age": "26",
})
Pass the struct to Users.Create:
newUser, err := Permit.Api.Users.Create(ctx, *user)
Users.Create return value and errors
On success, Users.Create returns a *models.UserRead with the user's Key, Id, Email, FirstName, LastName, and Attributes.
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 |
|---|---|
Conflict | HTTP 409: a user with the same key already exists in the environment. |
UnprocessableEntityError | HTTP 422: a field 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. |