Skip to main content

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

ParameterTypeRequiredDescription
ctxcontext.ContextYesThe context of the request.
userCreatemodels.UserCreateYesThe user to create. Build it with models.NewUserCreate(key).

UserCreate fields

FieldTypeRequiredDescription
KeystringYesA 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*stringNoThe email of the user. Set it with SetEmail().
FirstName*stringNoThe first name of the user. Set it with SetFirstName().
LastName*stringNoThe last name of the user. Set it with SetLastName().
Attributesmap[string]interface{}NoUser 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:

ErrorCodeCause
ConflictHTTP 409: a user with the same key already exists in the environment.
UnprocessableEntityErrorHTTP 422: a field 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.