clerk

package module
v2.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 17 Imported by: 2

README


Clerk Go SDK

The official Clerk Go client library for accessing the Clerk Backend API.

Go Reference chat on Discord documentation twitter

Migrating from v1?

Check out the upgrade guide.

Requirements

  • Go 1.19 or later.

Installation

If you are using Go Modules and have a go.mod file in your project's root, you can import clerk-sdk-go directly.

import (
    "github.com/clerk/clerk-sdk-go/v2"
)

Alternatively, you can go get the package explicitly.

go get -u github.com/clerk/clerk-sdk-go/v2

Usage

For details on how to use this module, see the Go Documentation.

The library has a resource-based structure which follows the way the Clerk Backend API resources are organized. Each API supports specific operations, like Create or List. While operations for each resource vary, a similar pattern is applied throughout the library.

In order to start using API operations the library needs to be configured with your Clerk API secret key. Depending on your use case, there's two ways to use the library; with or without a client.

For most use cases, the API without a client is a better choice.

On the other hand, if you need to set up multiple Clerk API keys, using clients for API operations provides more flexibility.

Let's see both approaches in detail.

Usage without a client

If you only use one API key, you can import the packages required for the APIs you need to interact with and call functions for API operations.

import (
    "github.com/clerk/clerk-sdk-go/v2"
    "github.com/clerk/clerk-sdk-go/v2/$resource$"
)

// Each operation requires a context.Context as the first argument.
ctx := context.Background()

// Set the API key
clerk.SetKey("sk_live_XXX")

// Create
resource, err := $resource$.Create(ctx, &$resource$.CreateParams{})

// Get
resource, err := $resource$.Get(ctx, id)

// Update
resource, err := $resource$.Update(ctx, id, &$resource$.UpdateParams{})

// Delete
resource, err := $resource$.Delete(ctx, id)

// List
list, err := $resource$.List(ctx, &$resource$.ListParams{})
for _, resource := range list.$Resource$s {
    // do something with the resource
}
Usage with a client

If you're dealing with multiple keys, it is recommended to use a client based approach. The API packages for each resource export a Client, which supports all the API's operations. This way you can create as many clients as needed, each with their own API key.

import (
    "github.com/clerk/clerk-sdk-go/v2"
    "github.com/clerk/clerk-sdk-go/v2/$resource$"
)

// Each operation requires a context.Context as the first argument.
ctx := context.Background()

// Initialize a client with an API key
config := &clerk.ClientConfig{}
config.Key = "sk_live_XXX"
client := $resource$.NewClient(config)

// Create
resource, err := client.Create(ctx, &$resource$.CreateParams{})

// Get
resource, err := client.Get(ctx, id)

// Update
resource, err := client.Update(ctx, id, &$resource$.UpdateParams{})

// Delete
resource, err := client.Delete(ctx, id)

// List
list, err := client.List(ctx, &$resource$.ListParams{})
for _, resource := range list.$Resource$s {
    // do something with the resource
}

Here's an example of how the above operations would look like for specific APIs.

import (
    "github.com/clerk/clerk-sdk-go/v2"
    "github.com/clerk/clerk-sdk-go/v2/organization"
    "github.com/clerk/clerk-sdk-go/v2/organizationmembership"
    "github.com/clerk/clerk-sdk-go/v2/user"
)

func main() {
    // Each operation requires a context.Context as the first argument.
    ctx := context.Background()

    // Set the API key
    clerk.SetKey("sk_live_XXX")

    // Create an organization
    org, err := organization.Create(ctx, &organization.CreateParams{
        Name: clerk.String("Clerk Inc"),
    })

    // Update the organization
    org, err = organization.Update(ctx, org.ID, &organization.UpdateParams{
        Slug: clerk.String("clerk"),
    })

    // List organization memberships
    listParams := organizationmembership.ListParams{}
    listParams.Limit = clerk.Int64(10)
    memberships, err := organizationmembership.List(ctx, params)
    if memberships.TotalCount < 0 {
        return
    }
    membership := memberships[0]

    // Get a user
    usr, err := user.Get(ctx, membership.UserID)
}
Accessing API responses

Each resource that is returned by an API operation has a Response field which contains information about the response that was sent from the Clerk Backend API.

The Response contains fields like the the raw HTTP response's headers, the status and the raw response body. See the APIResponse documentation for available fields and methods.

dmn, err := domain.Create(context.Background(), &domain.CreateParams{})
if !dmn.Response.Success() {
    dmn.Response.TraceID
}
Errors

For cases where an API operation returns an error, the library will try to return an APIErrorResponse. The APIErrorResponse type provides information such as the HTTP status code of the response, a list of errors and a trace ID that can be used for debugging.

The APIErrorResponse is an APIResource. You can access the API response for errors as well.

See the APIErrorResponse documentation for available fields and methods.

_, err := user.List(context.Background(), &user.ListParams{})
if apiErr, ok := err.(*clerk.APIErrorResponse); ok {
    apiErr.TraceID
    apiErr.Error()
    apiErr.Response.RawJSON
}
HTTP Middleware

The library provides two functions that can be used for adding authentication with Clerk to HTTP handlers.

Both middleware functions support header based authentication with a bearer token. The token is parsed, verified and its claims are extracted as SessionClaims.

The claims will then be made available in the http.Request.Context for the next handler in the chain. The library provides a helper for accessing the claims from the context, SessionClaimsFromContext.

The two middleware functions are WithHeaderAuthorization and RequireHeaderAuthorization. Their difference is that the RequireHeaderAuthorization calls WithHeaderAuthorization under the hood, but responds with HTTP 403 Forbidden if it fails to detect valid session claims.

Let's see an example of how the middleware can be used.

import (
	"fmt"
	"net/http"

	"github.com/clerk/clerk-sdk-go/v2"
	clerkhttp "github.com/clerk/clerk-sdk-go/v2/http"
)

func main() {
	clerk.SetKey("sk_live_XXX")

	mux := http.NewServeMux()
	mux.HandleFunc("/", publicRoute)
	protectedHandler := http.HandlerFunc(protectedRoute)
	mux.Handle(
		"/protected",
		clerkhttp.WithHeaderAuthorization()(protectedHandler),
	)

	http.ListenAndServe(":3000", mux)
}

func publicRoute(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(`{"access": "public"}`))
}

func protectedRoute(w http.ResponseWriter, r *http.Request) {
	claims, ok := clerk.SessionClaimsFromContext(r.Context())
	if !ok {
		w.WriteHeader(http.StatusUnauthorized)
		w.Write([]byte(`{"access": "unauthorized"}`))
		return
	}
	fmt.Fprintf(w, `{"user_id": "%s"}`, claims.Subject)
}

Both WithHeaderAuthorization and RequireHeaderAuthorization can be customized. They accept various options as functional arguments.

For a comprehensive list of available options check the AuthorizationParams documentation.

Testing

There are various ways to mock the library in your test suite.

Usage without client

If you're using the library without instantiating clients for APIs, you can set the package's Backend with a custom configuration.

  1. Stub out the HTTP client's transport
func TestWithCustomTransport(t *testing.T) {
    clerk.SetBackend(clerk.NewBackend(&clerk.BackendConfig{
        HTTPClient: &http.Client{
            Transport: mockRoundTripper,
        },
    }))
}

type mockRoundTripper struct {}
// Implement the http.RoundTripper interface.
func (r *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
    // Construct and return the http.Response.
}
  1. Use a httptest.Server

Similar to the custom http.Transport approach, you can use the net/http/httptest package's utilities and provide the http.Client to the package's Backend.

func TestWithMockServer(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Write the response.
    }))
    defer ts.Close()
    clerk.SetBackend(clerk.NewBackend(&clerk.BackendConfig{
        HTTPClient: ts.Client(),
        URL: &ts.URL,
    }))
}
  1. Implement your own Backend

You can implement your own Backend and set it as the package's default Backend.

func TestWithCustomBackend(t *testing.T) {
    clerk.SetBackend(&customBackend{})
}

type customBackend struct {}
// Implement the Backend interface
func (b *customBackend) Call(ctx context.Context, r *clerk.APIRequest, reader *clerk.ResponseReader) error {
    // Construct a clerk.APIResponse and use the reader's Read method.
    reader.Read(&clerk.APIResponse{})
}
Usage with client

If you're already using the library by instantiating clients for API operations, or you need to ensure your test suite can safely run in parallel, you can simply pass a custom http.Client to your clients.

  1. Stub out the HTTP client's transport
func TestWithCustomTransport(t *testing.T) {
    config := &clerk.ClientConfig{}
    config.HTTPClient = &http.Client{
        Transport: mockRoundTripper,
    }
    client := user.NewClient(config)
}

type mockRoundTripper struct {}
// Implement the http.RoundTripper interface.
func (r *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
    // Construct and return the http.Response.
}
  1. Use a httptest.Server

Similar to the custom http.Transport approach, you can use the net/http/httptest package's utilities and provide the http.Client to the API client.

func TestWithMockServer(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Write the response.
    }))
    defer ts.Close()
    config := &clerk.ClientConfig{}
    config.HTTPClient = ts.Client()
    config.URL = &ts.URL
    client := user.NewClient(config)
}
  1. Implement your own Backend

You can implement your own Backend and set it as the API client's Backend.

func TestWithCustomBackend(t *testing.T) {
    client := user.NewClient(&clerk.ClientConfig{})
    client.Backend = &customBackend{}
}

type customBackend struct {}
// Implement the Backend interface
func (b *customBackend) Call(ctx context.Context, r *clerk.APIRequest, reader *clerk.ResponseReader) error {
    // Construct a clerk.APIResponse and use the reader's Read method.
    reader.Read(&clerk.APIResponse{})
}

Development

Contributions are welcome. If you submit a pull request please keep in mind that

  1. Code must be go fmt compliant.
  2. All packages, types and functions should be documented.
  3. Ensure that go test ./... succeeds. Ideally, your pull request should include tests.
  4. If your pull request introduces a new API or API operation, run go generate ./... to generate the necessary API functions.

License

This SDK is licensed under the MIT license found in the LICENSE file.

Documentation

Overview

Package clerk provides a way to communicate with the Clerk API. Includes types for Clerk API requests, responses and all available resources.

Index

Constants

View Source
const (
	// APIURL is the base URL for the Clerk API.
	APIURL string = "https://api.clerk.com/v1"
)

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the provided bool value.

func ContextWithSessionClaims

func ContextWithSessionClaims(ctx context.Context, value any) context.Context

ContextWithSessionClaims returns a new context which includes the active session claims.

func Int64

func Int64(v int64) *int64

Int64 returns a pointer to the provided int64 value.

func JSONRawMessage added in v2.0.3

func JSONRawMessage(v json.RawMessage) *json.RawMessage

JSONRawMessage returns a pointer to the provided json.RawMessage value.

func JoinPath

func JoinPath(base string, elem ...string) (string, error)

JoinPath returns a URL string with the provided path elements joined with the base path.

func SetBackend

func SetBackend(b Backend)

SetBackend sets the Backend that will be used to make requests to the Clerk API. Use this method if you need to override the default Backend configuration.

func SetKey

func SetKey(key string)

SetKey sets the Clerk API key.

func String

func String(v string) *string

String returns a pointer to the provided string value.

Types

type APIErrorResponse

type APIErrorResponse struct {
	APIResource

	Errors []Error `json:"errors"`

	HTTPStatusCode int    `json:"status,omitempty"`
	TraceID        string `json:"clerk_trace_id,omitempty"`
}

APIErrorResponse is used for cases where requests to the Clerk API result in error responses.

func (*APIErrorResponse) Error

func (resp *APIErrorResponse) Error() string

Error returns the marshaled representation of the APIErrorResponse.

type APIParams

type APIParams struct {
}

APIParams implements functionality that's common to all types that can be used as API request parameters. It is recommended to embed this type to all types that will be used for API operation parameters.

func (*APIParams) ToMultipart

func (params *APIParams) ToMultipart() ([]byte, string, error)

ToMultipart can transform the params to a multipart entity. It is currently a no-op, but is defined so that all types that describe API operation parameters implement the Params interface.

func (*APIParams) ToQuery

func (params *APIParams) ToQuery() url.Values

ToQuery can be used to transform the params to querystring values. It is currently a no-op, but is defined so that all types that describe API operation parameters implement the Params interface.

type APIRequest

type APIRequest struct {
	Method string
	Path   string
	Params Params
	// contains filtered or unexported fields
}

APIRequest describes requests to the Clerk API.

func NewAPIRequest

func NewAPIRequest(method, path string) *APIRequest

NewAPIRequest creates an APIRequest with the provided HTTP method and path.

func NewMultipartAPIRequest

func NewMultipartAPIRequest(method, path string) *APIRequest

NewMultipartAPIRequest creates an APIRequest with the provided HTTP method and path and marks it as multipart. Multipart requests handle their params differently.

func (*APIRequest) SetParams

func (req *APIRequest) SetParams(params Params)

SetParams sets the APIRequest.Params.

type APIResource

type APIResource struct {
	Response *APIResponse `json:"-"`
}

APIResource describes a Clerk API resource and contains fields and methods common to all resources.

func (*APIResource) Read

func (r *APIResource) Read(response *APIResponse)

Read sets the response on the resource.

type APIResponse

type APIResponse struct {
	Header     http.Header
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200

	// TraceID is a unique identifier for tracing the origin of the
	// response.
	// Useful for debugging purposes.
	TraceID string
	// RawJSON contains the response body as raw bytes.
	RawJSON json.RawMessage
}

APIResponse describes responses coming from the Clerk API. Exposes some commonly used HTTP response fields along with the raw data in the response body.

func NewAPIResponse

func NewAPIResponse(resp *http.Response, body json.RawMessage) *APIResponse

NewAPIResponse creates an APIResponse from the passed http.Response and the raw response body.

func (*APIResponse) Success

func (resp *APIResponse) Success() bool

Success returns true for API response status codes in the 200-399 range, false otherwise.

type ActorToken

type ActorToken struct {
	APIResource
	Object    string          `json:"object"`
	ID        string          `json:"id"`
	UserID    string          `json:"user_id"`
	Actor     json.RawMessage `json:"actor"`
	Token     string          `json:"token,omitempty"`
	URL       *string         `json:"url,omitempty"`
	Status    string          `json:"status"`
	CreatedAt int64           `json:"created_at"`
	UpdatedAt int64           `json:"updated_at"`
}

type AllowlistIdentifier

type AllowlistIdentifier struct {
	APIResource
	Object         string  `json:"object"`
	ID             string  `json:"id"`
	Identifier     string  `json:"identifier"`
	IdentifierType string  `json:"identifier_type"`
	InvitationID   *string `json:"invitation_id,omitempty"`
	CreatedAt      int64   `json:"created_at"`
	UpdatedAt      int64   `json:"updated_at"`
}

type AllowlistIdentifierList

type AllowlistIdentifierList struct {
	APIResource
	AllowlistIdentifiers []*AllowlistIdentifier `json:"data"`
	TotalCount           int64                  `json:"total_count"`
}

type Backend

type Backend interface {
	// Call makes requests to the Clerk API.
	Call(context.Context, *APIRequest, ResponseReader) error
}

Backend is the primary interface for communicating with the Clerk API.

func GetBackend

func GetBackend() Backend

GetBackend returns the library's supported backend for the Clerk API.

func NewBackend

func NewBackend(config *BackendConfig) Backend

NewBackend returns a default backend implementation with the provided configuration. Please note that the return type is an interface because the Backend is not supposed to be used directly.

type BackendConfig

type BackendConfig struct {
	// HTTPClient is an HTTP client instance that will be used for
	// making API requests.
	// If it's not set a default HTTP client will be used.
	HTTPClient *http.Client
	// URL is the base URL to use for API endpoints.
	// If it's not set, the default value for the Backend will be used.
	URL *string
	// Key is the Clerk secret key. If it's not set, the package level
	// secretKey will be used.
	Key *string
	// CustomRequestHeaders allows you to provide predefined custom
	// headers that will be added to every HTTP request that the Backend
	// does.
	CustomRequestHeaders *CustomRequestHeaders
}

BackendConfig is used to configure a new Clerk Backend.

type BlocklistIdentifier

type BlocklistIdentifier struct {
	APIResource
	Object         string `json:"object"`
	ID             string `json:"id"`
	Identifier     string `json:"identifier"`
	IdentifierType string `json:"identifier_type"`
	CreatedAt      int64  `json:"created_at"`
	UpdatedAt      int64  `json:"updated_at"`
}

type BlocklistIdentifierList

type BlocklistIdentifierList struct {
	APIResource
	BlocklistIdentifiers []*BlocklistIdentifier `json:"data"`
	TotalCount           int64                  `json:"total_count"`
}

type CNAMETarget

type CNAMETarget struct {
	Host  string `json:"host"`
	Value string `json:"value"`
}

type Claims

type Claims struct {
	SessionID                     string          `json:"sid"`
	AuthorizedParty               string          `json:"azp"`
	ActiveOrganizationID          string          `json:"org_id"`
	ActiveOrganizationSlug        string          `json:"org_slug"`
	ActiveOrganizationRole        string          `json:"org_role"`
	ActiveOrganizationPermissions []string        `json:"org_permissions"`
	Actor                         json.RawMessage `json:"act,omitempty"`
}

Claims represents private JWT claims that are defined and used by Clerk.

type Client

type Client struct {
	APIResource
	Object              string     `json:"object"`
	ID                  string     `json:"id"`
	LastActiveSessionID *string    `json:"last_active_session_id"`
	SignInID            *string    `json:"sign_in_id"`
	SignUpID            *string    `json:"sign_up_id"`
	SessionIDs          []string   `json:"session_ids"`
	Sessions            []*Session `json:"sessions"`
	CreatedAt           int64      `json:"created_at"`
	UpdatedAt           int64      `json:"updated_at"`
}

type ClientConfig added in v2.0.3

type ClientConfig struct {
	BackendConfig
}

ClientConfig is used to configure a new Client that can invoke API operations.

type ClientList

type ClientList struct {
	APIResource
	Clients    []*Client `json:"data"`
	TotalCount int64     `json:"total_count"`
}

type Clock added in v2.0.3

type Clock interface {
	Now() time.Time
}

Clock is an interface that can be used with the library instead of the time package. The interface is useful for testing time sensitive paths or feeding the library with an authoritative source of time, like an external time generator.

func NewClock added in v2.0.3

func NewClock() Clock

NewClock returns a default clock implementation which calls the time package internally. Please note that the return type is an interface because the Clock is not supposed to be used directly.

type CustomRequestHeaders

type CustomRequestHeaders struct {
	Application string
}

CustomRequestHeaders contains predefined values that can be used as custom headers in Backend API requests.

type DeletedResource

type DeletedResource struct {
	APIResource
	ID      string `json:"id,omitempty"`
	Slug    string `json:"slug,omitempty"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

DeletedResource describes an API resource that is no longer available. It's usually encountered as a result of delete API operations.

type Domain

type Domain struct {
	APIResource
	ID                string        `json:"id"`
	Object            string        `json:"object"`
	Name              string        `json:"name"`
	IsSatellite       bool          `json:"is_satellite"`
	FrontendAPIURL    string        `json:"frontend_api_url"`
	AccountPortalURL  *string       `json:"accounts_portal_url,omitempty"`
	ProxyURL          *string       `json:"proxy_url,omitempty"`
	CNAMETargets      []CNAMETarget `json:"cname_targets,omitempty"`
	DevelopmentOrigin string        `json:"development_origin"`
}

type DomainList

type DomainList struct {
	APIResource
	Domains    []*Domain `json:"data"`
	TotalCount int64     `json:"total_count"`
}

type EmailAddress

type EmailAddress struct {
	APIResource
	ID           string                  `json:"id"`
	Object       string                  `json:"object"`
	EmailAddress string                  `json:"email_address"`
	Reserved     bool                    `json:"reserved"`
	Verification *Verification           `json:"verification"`
	LinkedTo     []*LinkedIdentification `json:"linked_to"`
}

type Error

type Error struct {
	Code        string          `json:"code"`
	Message     string          `json:"message"`
	LongMessage string          `json:"long_message"`
	Meta        json.RawMessage `json:"meta,omitempty"`
}

Error is a representation of a single error that can occur in the Clerk API.

type ExternalAccount

type ExternalAccount struct {
	Object           string          `json:"object"`
	ID               string          `json:"id"`
	Provider         string          `json:"provider"`
	IdentificationID string          `json:"identification_id"`
	ProviderUserID   string          `json:"provider_user_id"`
	ApprovedScopes   string          `json:"approved_scopes"`
	EmailAddress     string          `json:"email_address"`
	FirstName        string          `json:"first_name"`
	LastName         string          `json:"last_name"`
	AvatarURL        string          `json:"avatar_url"`
	ImageURL         *string         `json:"image_url,omitempty"`
	Username         *string         `json:"username"`
	PublicMetadata   json.RawMessage `json:"public_metadata"`
	Label            *string         `json:"label"`
	Verification     *Verification   `json:"verification"`
}

type InstanceRestrictions

type InstanceRestrictions struct {
	APIResource
	Object                      string `json:"object"`
	Allowlist                   bool   `json:"allowlist"`
	Blocklist                   bool   `json:"blocklist"`
	BlockEmailSubaddresses      bool   `json:"block_email_subaddresses"`
	BlockDisposableEmailDomains bool   `json:"block_disposable_email_domains"`
}

type JSONWebKey

type JSONWebKey struct {
	APIResource
	Key       any    `json:"key"`
	KeyID     string `json:"kid"`
	Algorithm string `json:"alg"`
	Use       string `json:"use"`
	// contains filtered or unexported fields
}

func JSONWebKeyFromPEM

func JSONWebKeyFromPEM(key string) (*JSONWebKey, error)

JSONWebKeyFromPEM returns a JWK from an RSA key.

func (*JSONWebKey) UnmarshalJSON

func (k *JSONWebKey) UnmarshalJSON(data []byte) error

type JSONWebKeySet

type JSONWebKeySet struct {
	APIResource
	Keys []*JSONWebKey `json:"keys"`
}

type JWTTemplate

type JWTTemplate struct {
	APIResource
	Object           string          `json:"object"`
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	Claims           json.RawMessage `json:"claims"`
	Lifetime         int64           `json:"lifetime"`
	AllowedClockSkew int64           `json:"allowed_clock_skew"`
	CustomSigningKey bool            `json:"custom_signing_key"`
	SigningAlgorithm string          `json:"signing_algorithm"`
	CreatedAt        int64           `json:"created_at"`
	UpdatedAt        int64           `json:"updated_at"`
}

type JWTTemplateList

type JWTTemplateList struct {
	APIResource
	JWTTemplates []*JWTTemplate `json:"data"`
	TotalCount   int64          `json:"total_count"`
}

type LinkedIdentification

type LinkedIdentification struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

type ListParams

type ListParams struct {
	Limit  *int64 `json:"limit,omitempty"`
	Offset *int64 `json:"offset,omitempty"`
}

ListParams holds fields that are common for list API operations.

func (ListParams) ToQuery

func (params ListParams) ToQuery() url.Values

ToQuery returns url.Values with the ListParams values in the querystring.

type OAuthAccessToken

type OAuthAccessToken struct {
	ExternalAccountID string          `json:"external_account_id"`
	Object            string          `json:"object"`
	Token             string          `json:"token"`
	Provider          string          `json:"provider"`
	PublicMetadata    json.RawMessage `json:"public_metadata"`
	Label             *string         `json:"label"`
	// Only set in OAuth 2.0 tokens
	Scopes []string `json:"scopes,omitempty"`
	// Only set in OAuth 1.0 tokens
	TokenSecret *string `json:"token_secret,omitempty"`
}

type OAuthAccessTokenList

type OAuthAccessTokenList struct {
	APIResource
	OAuthAccessTokens []*OAuthAccessToken `json:"data"`
	TotalCount        int64               `json:"total_count"`
}

type Organization

type Organization struct {
	APIResource
	Object                  string          `json:"object"`
	ID                      string          `json:"id"`
	Name                    string          `json:"name"`
	Slug                    string          `json:"slug"`
	ImageURL                *string         `json:"image_url"`
	HasImage                bool            `json:"has_image"`
	MembersCount            *int64          `json:"members_count,omitempty"`
	PendingInvitationsCount *int64          `json:"pending_invitations_count,omitempty"`
	MaxAllowedMemberships   int64           `json:"max_allowed_memberships"`
	AdminDeleteEnabled      bool            `json:"admin_delete_enabled"`
	PublicMetadata          json.RawMessage `json:"public_metadata"`
	PrivateMetadata         json.RawMessage `json:"private_metadata"`
	CreatedBy               string          `json:"created_by"`
	CreatedAt               int64           `json:"created_at"`
	UpdatedAt               int64           `json:"updated_at"`
}

type OrganizationInvitation

type OrganizationInvitation struct {
	APIResource
	Object          string          `json:"object"`
	ID              string          `json:"id"`
	EmailAddress    string          `json:"email_address"`
	Role            string          `json:"role"`
	OrganizationID  string          `json:"organization_id"`
	Status          string          `json:"status"`
	PublicMetadata  json.RawMessage `json:"public_metadata"`
	PrivateMetadata json.RawMessage `json:"private_metadata"`
	CreatedAt       int64           `json:"created_at"`
	UpdatedAt       int64           `json:"updated_at"`
}

type OrganizationList

type OrganizationList struct {
	APIResource
	Organizations []*Organization `json:"data"`
	TotalCount    int64           `json:"total_count"`
}

type OrganizationMembership

type OrganizationMembership struct {
	APIResource
	Object          string                                `json:"object"`
	ID              string                                `json:"id"`
	Organization    *Organization                         `json:"organization"`
	Permissions     []string                              `json:"permissions"`
	PublicMetadata  json.RawMessage                       `json:"public_metadata"`
	PrivateMetadata json.RawMessage                       `json:"private_metadata"`
	Role            string                                `json:"role"`
	CreatedAt       int64                                 `json:"created_at"`
	UpdatedAt       int64                                 `json:"updated_at"`
	PublicUserData  *OrganizationMembershipPublicUserData `json:"public_user_data,omitempty"`
}

type OrganizationMembershipList

type OrganizationMembershipList struct {
	APIResource
	OrganizationMemberships []*OrganizationMembership `json:"data"`
	TotalCount              int64                     `json:"total_count"`
}

type OrganizationMembershipPublicUserData

type OrganizationMembershipPublicUserData struct {
	UserID     string  `json:"user_id"`
	FirstName  *string `json:"first_name"`
	LastName   *string `json:"last_name"`
	ImageURL   *string `json:"image_url"`
	HasImage   bool    `json:"has_image"`
	Identifier string  `json:"identifier"`
}

type OrganizationSettings

type OrganizationSettings struct {
	APIResource
	Object                 string   `json:"object"`
	Enabled                bool     `json:"enabled"`
	MaxAllowedMemberships  int64    `json:"max_allowed_memberships"`
	MaxAllowedRoles        int64    `json:"max_allowed_roles"`
	MaxAllowedPermissions  int64    `json:"max_allowed_permissions"`
	CreatorRole            string   `json:"creator_role"`
	AdminDeleteEnabled     bool     `json:"admin_delete_enabled"`
	DomainsEnabled         bool     `json:"domains_enabled"`
	DomainsEnrollmentModes []string `json:"domains_enrollment_modes"`
	DomainsDefaultRole     string   `json:"domains_default_role"`
}

type Params

type Params interface {
	ToQuery() url.Values
	ToMultipart() ([]byte, string, error)
}

Params can transform themselves to types that can be used as request parameters, like query string values or multipart data.

type PhoneNumber

type PhoneNumber struct {
	APIResource
	Object                  string                  `json:"object"`
	ID                      string                  `json:"id"`
	PhoneNumber             string                  `json:"phone_number"`
	ReservedForSecondFactor bool                    `json:"reserved_for_second_factor"`
	DefaultSecondFactor     bool                    `json:"default_second_factor"`
	Reserved                bool                    `json:"reserved"`
	Verification            *Verification           `json:"verification"`
	LinkedTo                []*LinkedIdentification `json:"linked_to"`
	BackupCodes             []string                `json:"backup_codes"`
}

type ProxyCheck

type ProxyCheck struct {
	APIResource
	Object     string `json:"object"`
	ID         string `json:"id"`
	DomainID   string `json:"domain_id"`
	ProxyURL   string `json:"proxy_url"`
	Successful bool   `json:"successful"`
	LastRunAt  *int64 `json:"last_run_at"`
	CreatedAt  int64  `json:"created_at"`
	UpdatedAt  int64  `json:"updated_at"`
}

type RedirectURL

type RedirectURL struct {
	APIResource
	Object    string `json:"object"`
	ID        string `json:"id"`
	URL       string `json:"url"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

type RedirectURLList

type RedirectURLList struct {
	APIResource
	RedirectURLs []*RedirectURL `json:"data"`
	TotalCount   int64          `json:"total_count"`
}

type RegisteredClaims

type RegisteredClaims struct {
	Issuer    string   `json:"iss,omitempty"`
	Subject   string   `json:"sub,omitempty"`
	Audience  []string `json:"aud,omitempty"`
	Expiry    *int64   `json:"exp,omitempty"`
	NotBefore *int64   `json:"nbf,omitempty"`
	IssuedAt  *int64   `json:"iat,omitempty"`
	ID        string   `json:"jti,omitempty"`
	// contains filtered or unexported fields
}

RegisteredClaims holds public claim values (as specified in RFC 7519).

func (*RegisteredClaims) UnmarshalJSON

func (c *RegisteredClaims) UnmarshalJSON(data []byte) error

func (*RegisteredClaims) ValidateWithLeeway

func (c *RegisteredClaims) ValidateWithLeeway(expected time.Time, leeway time.Duration) error

ValidateWithLeeway checks expiration and issuance claims against an expected time. You may pass a zero value to check the time values with no leeway, but it is not recommended. The leeway gives some extra time to the token from the server's point of view. That is, if the token is expired, ValidateWithLeeway will still accept the token for 'leeway' amount of time.

type ResponseReader

type ResponseReader interface {
	Read(*APIResponse)
}

ResponseReader reads Clerk API responses.

type SAMLAccount

type SAMLAccount struct {
	Object         string          `json:"object"`
	ID             string          `json:"id"`
	Provider       string          `json:"provider"`
	Active         bool            `json:"active"`
	EmailAddress   string          `json:"email_address"`
	FirstName      *string         `json:"first_name"`
	LastName       *string         `json:"last_name"`
	ProviderUserID *string         `json:"provider_user_id"`
	PublicMetadata json.RawMessage `json:"public_metadata"`
	Verification   *Verification   `json:"verification"`
}

type SAMLConnection added in v2.0.3

type SAMLConnection struct {
	APIResource
	ID                 string                         `json:"id"`
	Object             string                         `json:"object"`
	Name               string                         `json:"name"`
	Domain             string                         `json:"domain"`
	IdpEntityID        *string                        `json:"idp_entity_id"`
	IdpSsoURL          *string                        `json:"idp_sso_url"`
	IdpCertificate     *string                        `json:"idp_certificate"`
	IdpMetadataURL     *string                        `json:"idp_metadata_url"`
	IdpMetadata        *string                        `json:"idp_metadata"`
	AcsURL             string                         `json:"acs_url"`
	SPEntityID         string                         `json:"sp_entity_id"`
	SPMetadataURL      string                         `json:"sp_metadata_url"`
	AttributeMapping   SAMLConnectionAttributeMapping `json:"attribute_mapping"`
	Active             bool                           `json:"active"`
	Provider           string                         `json:"provider"`
	UserCount          int64                          `json:"user_count"`
	SyncUserAttributes bool                           `json:"sync_user_attributes"`
	AllowSubdomains    bool                           `json:"allow_subdomains"`
	AllowIdpInitiated  bool                           `json:"allow_idp_initiated"`
	CreatedAt          int64                          `json:"created_at"`
	UpdatedAt          int64                          `json:"updated_at"`
}

type SAMLConnectionAttributeMapping added in v2.0.3

type SAMLConnectionAttributeMapping struct {
	UserID       string `json:"user_id"`
	EmailAddress string `json:"email_address"`
	FirstName    string `json:"first_name"`
	LastName     string `json:"last_name"`
}

type SAMLConnectionList added in v2.0.3

type SAMLConnectionList struct {
	APIResource
	SAMLConnections []*SAMLConnection `json:"data"`
	TotalCount      int64             `json:"total_count"`
}

type Session

type Session struct {
	APIResource
	Object                   string          `json:"object"`
	ID                       string          `json:"id"`
	ClientID                 string          `json:"client_id"`
	UserID                   string          `json:"user_id"`
	Status                   string          `json:"status"`
	LastActiveOrganizationID string          `json:"last_active_organization_id,omitempty"`
	Actor                    json.RawMessage `json:"actor,omitempty"`
	LastActiveAt             int64           `json:"last_active_at"`
	ExpireAt                 int64           `json:"expire_at"`
	AbandonAt                int64           `json:"abandon_at"`
	CreatedAt                int64           `json:"created_at"`
	UpdatedAt                int64           `json:"updated_at"`
}

type SessionClaims

type SessionClaims struct {
	// Standard IANA JWT claims
	RegisteredClaims
	// Clerk specific JWT claims
	Claims

	// Custom can hold any custom claims that might be found in a JWT.
	Custom any `json:"-"`
}

SessionClaims represents Clerk specific JWT claims.

func SessionClaimsFromContext

func SessionClaimsFromContext(ctx context.Context) (*SessionClaims, bool)

SessionClaimsFromContext returns the active session claims from the context.

func (*SessionClaims) HasPermission

func (s *SessionClaims) HasPermission(permission string) bool

HasPermission checks if the session claims contain the provided organization permission. Use this helper to check if a user has the specific permission in the active organization.

func (*SessionClaims) HasRole

func (s *SessionClaims) HasRole(role string) bool

HasRole checks if the session claims contain the provided organization role. However, the HasPermission helper is the recommended way to check for permissions. Complex role checks can usually be translated to a single permission check. For example, checks for an "admin" role that can modify a resource can be replaced by checks for a "modify" permission.

func (*SessionClaims) UnmarshalJSON

func (s *SessionClaims) UnmarshalJSON(data []byte) error

type SessionList

type SessionList struct {
	APIResource
	Sessions   []*Session `json:"data"`
	TotalCount int64      `json:"total_count"`
}

type SvixWebhook

type SvixWebhook struct {
	APIResource
	SvixURL string `json:"svix_url"`
}

type Template

type Template struct {
	APIResource
	Object             string       `json:"object"`
	Slug               string       `json:"slug"`
	ResourceType       string       `json:"resource_type"`
	TemplateType       TemplateType `json:"template_type"`
	Name               string       `json:"name"`
	Position           int          `json:"position"`
	CanRevert          bool         `json:"can_revert"`
	CanDelete          bool         `json:"can_delete"`
	FromEmailName      *string      `json:"from_email_name,omitempty"`
	ReplyToEmailName   *string      `json:"reply_to_email_name,omitempty"`
	DeliveredByClerk   bool         `json:"delivered_by_clerk"`
	Subject            string       `json:"subject"`
	Markup             string       `json:"markup"`
	Body               string       `json:"body"`
	AvailableVariables []string     `json:"available_variables"`
	RequiredVariables  []string     `json:"required_variables"`
	CreatedAt          int64        `json:"created_at"`
	UpdatedAt          int64        `json:"updated_at"`
}

type TemplateList

type TemplateList struct {
	APIResource
	Templates  []*Template `json:"data"`
	TotalCount int64       `json:"total_count"`
}

type TemplatePreview

type TemplatePreview struct {
	APIResource
	Subject             string  `json:"subject,omitempty"`
	Body                string  `json:"body"`
	FromEmailAddress    *string `json:"from_email_address,omitempty"`
	ReplyToEmailAddress *string `json:"reply_to_email_address,omitempty"`
}

type TemplateType

type TemplateType string

Clerk supports different types of templates.

const (
	TemplateTypeEmail TemplateType = "email"
	TemplateTypeSMS   TemplateType = "sms"
)

List of supported values for template types.

type UnverifiedToken

type UnverifiedToken struct {
	RegisteredClaims
	// Any headers not recognized get unmarshalled
	// from JSON in a generic manner and placed in this map.
	Extra map[string]any
	KeyID string
}

UnverifiedToken holds the result of a JWT decoding without any verification. The UnverifiedToken includes registered and custom claims, as well as the KeyID (kid) header.

type User

type User struct {
	APIResource
	Object                        string             `json:"object"`
	ID                            string             `json:"id"`
	Username                      *string            `json:"username"`
	FirstName                     *string            `json:"first_name"`
	LastName                      *string            `json:"last_name"`
	ImageURL                      *string            `json:"image_url,omitempty"`
	HasImage                      bool               `json:"has_image"`
	PrimaryEmailAddressID         *string            `json:"primary_email_address_id"`
	PrimaryPhoneNumberID          *string            `json:"primary_phone_number_id"`
	PrimaryWeb3WalletID           *string            `json:"primary_web3_wallet_id"`
	PasswordEnabled               bool               `json:"password_enabled"`
	TwoFactorEnabled              bool               `json:"two_factor_enabled"`
	TOTPEnabled                   bool               `json:"totp_enabled"`
	BackupCodeEnabled             bool               `json:"backup_code_enabled"`
	EmailAddresses                []*EmailAddress    `json:"email_addresses"`
	PhoneNumbers                  []*PhoneNumber     `json:"phone_numbers"`
	Web3Wallets                   []*Web3Wallet      `json:"web3_wallets"`
	ExternalAccounts              []*ExternalAccount `json:"external_accounts"`
	SAMLAccounts                  []*SAMLAccount     `json:"saml_accounts"`
	PasswordLastUpdatedAt         *int64             `json:"password_last_updated_at,omitempty"`
	PublicMetadata                json.RawMessage    `json:"public_metadata"`
	PrivateMetadata               json.RawMessage    `json:"private_metadata,omitempty"`
	UnsafeMetadata                json.RawMessage    `json:"unsafe_metadata,omitempty"`
	ExternalID                    *string            `json:"external_id"`
	LastSignInAt                  *int64             `json:"last_sign_in_at"`
	Banned                        bool               `json:"banned"`
	Locked                        bool               `json:"locked"`
	LockoutExpiresInSeconds       *int64             `json:"lockout_expires_in_seconds"`
	VerificationAttemptsRemaining *int64             `json:"verification_attempts_remaining"`
	DeleteSelfEnabled             bool               `json:"delete_self_enabled"`
	CreateOrganizationEnabled     bool               `json:"create_organization_enabled"`
	LastActiveAt                  *int64             `json:"last_active_at"`
	CreatedAt                     int64              `json:"created_at"`
	UpdatedAt                     int64              `json:"updated_at"`
}

type UserList

type UserList struct {
	APIResource
	Users      []*User `json:"data"`
	TotalCount int64   `json:"total_count"`
}

type Verification

type Verification struct {
	Status                          string          `json:"status"`
	Strategy                        string          `json:"strategy"`
	Attempts                        *int64          `json:"attempts"`
	ExpireAt                        *int64          `json:"expire_at"`
	VerifiedAtClient                string          `json:"verified_at_client,omitempty"`
	Nonce                           *string         `json:"nonce,omitempty"`
	ExternalVerificationRedirectURL *string         `json:"external_verification_redirect_url,omitempty"`
	Error                           json.RawMessage `json:"error,omitempty"`
}

type Web3Wallet

type Web3Wallet struct {
	Object       string        `json:"object"`
	ID           string        `json:"id"`
	Web3Wallet   string        `json:"web3_wallet"`
	Verification *Verification `json:"verification"`
}

Directories

Path Synopsis
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Package clerktest provides utilities for testing.
Package clerktest provides utilities for testing.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Package http provides HTTP utilities and handler middleware.
Package http provides HTTP utilities and handler middleware.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Package jwt provides operations for decoding and validating JSON Web Tokens.
Package jwt provides operations for decoding and validating JSON Web Tokens.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.
Code generated by "gen"; DO NOT EDIT.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL