### Install auth-go Source: https://github.com/supabase-community/auth-go/blob/main/README.md Use `go get` to install the auth-go library. ```sh go get github.com/supabase-community/auth-go ``` -------------------------------- ### Example Function Signatures for Godoc in Go Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Illustrates the expected function signatures for creating runnable Godoc examples. These examples are crucial for demonstrating API usage within the documentation. ```go func ExampleClient_SignInWithEmailPassword() { ... } func ExampleClient_SignUp() { ... } func ExampleClient_EnrollFactor() { ... } ``` -------------------------------- ### Install Go Dependencies Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Download all necessary Go modules for the project. ```bash go mod download ``` -------------------------------- ### Example Directory Structure for Go Client Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Shows a typical directory layout for example applications using the Supabase Auth Go client. This structure helps organize different use cases and configurations. ```go examples/ ├── basic-auth/main.go ├── mfa-totp/main.go ├── admin-user-mgmt/main.go ├── oauth-flow/main.go ├── custom-config/main.go └── README.md ``` -------------------------------- ### Migration: Context Support Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Illustrates the change in method signatures for context support from v1.x to v2.0. The example shows how to pass context.Background() to methods. ```go # Migrating from v1.x to v2.0 ## Context Support **Before (v1.x):** ```go resp, err := client.SignInWithEmailPassword("user@example.com", "password") ``` **After (v2.0):** ```go ctx := context.Background() resp, err := client.SignInWithEmailPassword(ctx, "user@example.com", "password") ``` ``` -------------------------------- ### Conventional Commit Example: Documentation Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a commit message for documentation-only changes. ```bash git commit -m "docs: add security best practices to README" ``` -------------------------------- ### Table-Driven Test Example Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Implement table-driven tests to cover multiple scenarios for a function. This example demonstrates testing a token request. ```go func TestTokenRequest(t *testing.T) { tests := []struct { name string input types.TokenRequest want *types.AuthenticatedResponse wantErr bool }{ { name: "successful login", input: types.TokenRequest{ GrantType: "password", Email: "user@example.com", Password: "password", }, wantErr: false, }, { name: "invalid credentials", input: types.TokenRequest{ GrantType: "password", Email: "wrong@example.com", Password: "wrong", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := client.Token(tt.input) if (err != nil) != tt.wantErr { t.Errorf("Token() error = %v, wantErr %v", err, tt.wantErr) return } // Additional assertions... }) } } ``` -------------------------------- ### Bug Report Steps to Reproduce Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Provide clear, numbered steps to reproduce a bug. This example outlines the general structure. ```text 1. Initialize client with '...' 2. Call method '...' 3. See error ``` -------------------------------- ### Module Path for v2 Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Example of how to specify the v2 module path if breaking changes necessitate it. However, the library prefers using v2.x.x tags with the same path. ```go github.com/supabase-community/auth-go/v2 ``` -------------------------------- ### Conventional Commit Example: Feature Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a commit message for a new feature, following the conventional commits format. ```bash git commit -m "feat: add retry logic with exponential backoff" ``` -------------------------------- ### Migration: Error Handling Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Demonstrates the change in error handling from v1.x to v2.0. The example shows how to use errors.As to check for and extract structured AuthError types. ```go ## Error Handling **Before (v1.x):** ```go _, err := client.SignUp(req) if err != nil { log.Printf("Error: %v", err) } ``` **After (v2.0):** ```go _, err := client.SignUp(ctx, req) if err != nil { var authErr *types.AuthError if errors.As(err, &authErr) { // Access structured error log.Printf("Status: %d, Message: %s", authErr.StatusCode, authErr.Message) } } ``` ``` -------------------------------- ### Godoc Comment Example Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Document exported types, functions, and methods using godoc comments. This example shows how to document a client method. ```go // SignInWithEmailPassword authenticates a user with email and password. // It returns an AuthenticatedResponse containing the user and session tokens. // // POST /token func (c *Client) SignInWithEmailPassword(email, password string) (*types.AuthenticatedResponse, error) { // ... } ``` -------------------------------- ### Automated Migration Script Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md A bash script example for automating the migration of client method calls to include context. This uses 'find' and 'sed' for in-place replacement. ```bash # Find and replace (example - customize per method) find . -name "*.go" -exec sed -i '' 's/client.SignInWithEmailPassword(\\(.*\\), \\([^)]*\\))/client.SignInWithEmailPassword(context.Background(), \\1, \\2)/g' {} \\; ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Follow conventional commit message formats for automated release management. Use '!' or 'BREAKING CHANGE:' for major version bumps. ```bash feat: add retry logic with exponential backoff fix(admin): handle strconv.Atoi errors properly docs: add security best practices section test: add unit tests for token endpoint # Breaking changes (triggers MAJOR version): feat!: add context.Context to all methods # OR feat: add context support BREAKING CHANGE: All methods now require context as first parameter ``` -------------------------------- ### Conventional Commit Example: Refactoring Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a refactoring commit message, explaining the change and its purpose. ```bash git commit -m "refactor: rename client.client to client.httpClient Improves code clarity by using a more descriptive field name." ``` -------------------------------- ### Conventional Commits Example Source: https://github.com/supabase-community/auth-go/blob/main/README.md Examples of commit messages following the Conventional Commits specification for different types of changes. ```bash feat: add retry logic with exponential backoff fix(admin): handle pagination errors properly docs: update README with examples ``` -------------------------------- ### Error Wrapping Example Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Wrap errors with context using fmt.Errorf to provide more information about the error's origin. ```go fmt.Errorf("failed to do X: %w", err) ``` -------------------------------- ### Format and Lint Code Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Format code using go fmt and lint using go vet. goimports can also be used if installed. ```bash # Format code go fmt ./... # Run goimports (if installed) goimports -w . # Run linter go vet ./... ``` -------------------------------- ### Bug Report Code Snippet Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Include a minimal reproducible code example when reporting a bug. This helps in quickly identifying the issue. ```go client := auth.New("ref", "key") // Minimal reproducible example ``` -------------------------------- ### Get Public Server Settings with Supabase Auth Go Source: https://context7.com/supabase-community/auth-go/llms.txt Retrieves the publicly available configuration of the Auth server, including enabled providers, autoconfirm state, and MFA availability. Uses a standard client. ```go settings, err := client.GetSettings() if err != nil { log.Fatal(err) } log.Printf("Signup disabled: %v", settings.DisableSignup) log.Printf("MFA enabled: %v", settings.MFAEnabled) log.Printf("Email provider: %v", settings.External.Email) log.Printf("GitHub OAuth: %v", settings.External.GitHub) log.Printf("Google OAuth: %v", settings.External.Google) ``` -------------------------------- ### Get Current User Information Source: https://context7.com/supabase-community/auth-go/llms.txt Retrieves the full user profile object for the authenticated user. The client must be configured with an access token. ```go authedClient := client.WithToken(accessToken) user, err := authedClient.GetUser() if err != nil { log.Fatal(err) } log.Printf("id=%s email=%s role=%s created_at=%s", user.ID, user.Email, user.Role, user.CreatedAt) log.Printf("metadata: %v", user.UserMetadata) ``` -------------------------------- ### Initiate SSO Session Source: https://context7.com/supabase-community/auth-go/llms.txt Initiates a SAML SSO session with a registered identity provider, identified by either its UUID or an email domain. Set `SkipHTTPRedirect: true` to get the redirect URL instead of following it. ```APIDOC ## POST /sso ### Description Initiates a SAML SSO session with a registered identity provider, identified by either its UUID or an email domain. Set `SkipHTTPRedirect: true` to get the redirect URL instead of following it. ### Method POST ### Endpoint /sso ### Request Body - **Domain** (string) - Optional - The email domain to identify the IdP. - **ProviderID** (string) - Optional - The UUID of the IdP. - **RedirectTo** (string) - Required - The URL to redirect to after SSO. - **SkipHTTPRedirect** (boolean) - Optional - If true, returns the redirect URL instead of following it. ### Request Example ```json { "Domain": "corp.example.com", "RedirectTo": "https://app.example.com/auth/callback", "SkipHTTPRedirect": true } ``` ### Response #### Success Response (200) - **URL** (string) - The SSO redirect URL. ### Response Example ```json { "URL": "https://idp.example.com/sso?..." } ``` ``` -------------------------------- ### Initialize and Use auth-go Client Source: https://github.com/supabase-community/auth-go/blob/main/README.md Initializes the client with project reference and API key, then logs in a user using their email and password to obtain access and refresh tokens. ```go package main import ( "github.com/supabase-community/auth-go" "github.com/supabase-community/auth-go/types" ) const ( projectReference = "" apiKey = "" ) func main() { // Initialise client client := auth.New( projectReference, apiKey, ) // Log in a user (get access and refresh tokens) resp, err := client.Token(types.TokenRequest{ GrantType: "password", Email: "", Password: "", }) if err != nil { log.Fatal(err.Error()) } log.Printf("%+v", resp) } ``` -------------------------------- ### Configure Client Options in Go Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Demonstrates how to use the options pattern for configuring the Supabase Auth client, including setting timeouts and custom HTTP clients. This approach is backward compatible with existing usage. ```go type ClientOption func(*clientOptions) type clientOptions struct { httpClient *http.Client timeout time.Duration headers map[string]string retryPolicy *RetryPolicy } // WithTimeout sets request timeout func WithTimeout(d time.Duration) ClientOption { return func(o *clientOptions) { o.timeout = d } } // WithHTTPClient uses custom HTTP client func WithHTTPClient(client *http.Client) ClientOption { return func(o *clientOptions) { o.httpClient = client } } // Update New() to accept options func New(projectRef, apiKey string, opts ...ClientOption) Client { options := &clientOptions{ timeout: 10 * time.Second, // default } for _, opt := range opts { opt(options) } // ... create client with options } ``` ```go // Old way still works (backward compatible) client := auth.New("ref", "key") // NEW: Configure timeout client := auth.New("ref", "key", auth.WithTimeout(30 * time.Second)) // NEW: Custom HTTP client httpClient := &http.Client{ Transport: &http.Transport{ MaxIdleConns: 100, }, } client := auth.New("ref", "key", auth.WithHTTPClient(httpClient)) ``` -------------------------------- ### Client Initialization and Token Request Source: https://github.com/supabase-community/auth-go/blob/main/README.md Demonstrates how to initialize the auth-go client and perform a user login to obtain access and refresh tokens. ```APIDOC ## Client Initialization and Token Request ### Description Initializes the auth-go client and logs in a user to retrieve authentication tokens. ### Method `auth.New(projectReference, apiKey)` initializes the client. `client.Token(types.TokenRequest)` requests authentication tokens. ### Parameters #### Client Initialization - **projectReference** (string) - Your Supabase project reference. - **apiKey** (string) - Your Supabase anon key. #### Token Request - **types.TokenRequest** (struct) - Contains authentication grant type, email, and password. - **GrantType** (string) - e.g., "password" - **Email** (string) - User's email address. - **Password** (string) - User's password. ### Request Example ```go package main import ( "github.com/supabase-community/auth-go" "github.com/supabase-community/auth-go/types" ) const ( projectReference = "" apiKey = "" ) func main() { client := auth.New( projectReference, apiKey, ) resp, err := client.Token(types.TokenRequest{ GrantType: "password", Email: "", Password: "", }) if err != nil { log.Fatal(err.Error()) } log.Printf("%+v", resp) } ``` ### Response #### Success Response (200) - **resp** (*types.TokenResponse) - Contains access and refresh tokens. - **err** (error) - If an error occurred during the request. #### Response Example ```json { "access_token": "", "refresh_token": "", "expires_in": 3600, "expires_at": 1678886400, "user": { "id": "", "aud": "authenticated", "role": "authenticated", "email": "", "email_confirmed_at": "2023-01-01T12:00:00Z", "phone_confirmed_at": null, "confirmed_at": "2023-01-01T12:00:00Z", "last_sign_in_at": "2023-01-01T12:00:00Z", "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:00:00Z", "app_metadata": {}, "user_metadata": {}, "identities": [] } } ``` ``` -------------------------------- ### Conventional Commit Example: Bug Fix Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a bug fix commit message, specifying the scope and detailing the fix. ```bash git commit -m "fix(admin): handle strconv.Atoi errors in audit endpoint Previously errors from strconv.Atoi were silently ignored in adminaudit.go:77. This now properly handles the error and returns it to the caller. Fixes #456" ``` -------------------------------- ### Conventional Commit Example: Feature with Scope Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a feature commit that includes a scope and a detailed body, referencing an issue. ```bash git commit -m "feat(admin): add pagination support for user list Adds Page and PerPage parameters to AdminListUsersRequest to enable efficient pagination of large user lists. Closes #123" ``` -------------------------------- ### Initialize Supabase Auth Client Source: https://context7.com/supabase-community/auth-go/llms.txt Creates a base client for Supabase Auth. Ensure you have your project reference and API key. The default HTTP timeout is 10 seconds. ```go package main import ( "log" auth "github.com/supabase-community/auth-go" "github.com/supabase-community/auth-go/types" ) func main() { client := auth.New( "abcdefghijklmnop", // Supabase project reference (Reference ID in dashboard) "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // anon key ) // Check the server is reachable health, err := client.HealthCheck() if err != nil { log.Fatal(err) } log.Printf("Auth server %s v%s", health.Name, health.Version) // Output: Auth server GoTrue v2.x.x _ = types.HealthCheckResponse{} // types are in the types sub-package } ``` -------------------------------- ### Register a New User with Email and Password Source: https://context7.com/supabase-community/auth-go/llms.txt Performs user registration using email and password. If the server has autoconfirm enabled, a session is returned; otherwise, only the user details are provided. The library ensures user fields are always populated. ```go resp, err := client.Signup(types.SignupRequest{ Email: "newuser@example.com", Password: "MyStr0ngPass!", Data: map[string]interface{}{ "full_name": "Ada Lovelace", "plan": "free", }, }) if err != nil { log.Fatal("signup failed:", err) } log.Printf("User created: id=%s email=%s", resp.ID, resp.Email) // If autoconfirm is on, a session is also returned: if resp.AccessToken != "" { log.Println("Access token:", resp.AccessToken) } ``` -------------------------------- ### Conventional Commit Example: Breaking Change Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Example of a commit message introducing a breaking change, with a clear BREAKING CHANGE footer and migration guidance. ```bash git commit -m "feat!: add context.Context to all methods BREAKING CHANGE: All client methods now require context.Context as the first parameter. This enables proper timeout and cancellation support. Migration guide: Pass context.Background() for top-level calls, or propagate context from your application. Closes #789" ``` -------------------------------- ### Configure Client with Token Source: https://github.com/supabase-community/auth-go/blob/main/README.md Creates a new client instance that includes an authentication token in the `Authorization` header for subsequent requests. This is useful for making authenticated API calls after a user has logged in. ```go token, err := client.Token(types.TokenRequest{ GrantType: "password", Email: email, Password: password, }) if err != nil { // Handle error... } authedClient := client.WithToken( token.AccessToken, ) user, err := authedClient.GetUser() if err != nil { // Handle error... } ``` -------------------------------- ### Get User Information Source: https://github.com/supabase-community/auth-go/blob/main/README.md Retrieves the current user's information using an authenticated client. ```APIDOC ## Get User Information ### Description Fetches the details of the currently authenticated user using the provided access token. ### Method `authedClient.GetUser()` ### Parameters This method does not take any direct parameters, but it requires the `authedClient` to be initialized with a valid access token using `WithToken()`. ### Request Example ```go // Assuming 'client' is initialized and 'token' is obtained from a previous login authedClient := client.WithToken(token.AccessToken) user, err := authedClient.GetUser() if err != nil { // Handle error... } log.Printf("%+v", user) ``` ### Response #### Success Response (200) - **user** (*types.UserResponse) - Contains the user's profile information. - **err** (error) - If an error occurred during the request. #### Response Example ```json { "id": "", "aud": "authenticated", "role": "authenticated", "email": "", "email_confirmed_at": "2023-01-01T12:00:00Z", "phone_confirmed_at": null, "confirmed_at": "2023-01-01T12:00:00Z", "last_sign_in_at": "2023-01-01T12:00:00Z", "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:00:00Z", "app_metadata": {}, "user_metadata": {}, "identities": [] } ``` ``` -------------------------------- ### GetSettings Source: https://context7.com/supabase-community/auth-go/llms.txt Returns the publicly available configuration of the Auth server. ```APIDOC ## GetSettings — public server settings (`GET /settings`) ### Description Returns the publicly available configuration of the Auth server: enabled providers, autoconfirm state, MFA availability, and so on. ### Method GET ### Endpoint `/settings` ### Request Example ```go settings, err := client.GetSettings() ``` ### Response #### Success Response (200) - **DisableSignup** (boolean) - Indicates if signup is disabled. - **MFAEnabled** (boolean) - Indicates if Multi-Factor Authentication is enabled. - **External** (object) - Configuration for external authentication providers. - **Email** (boolean) - Indicates if email-based authentication is enabled. - **GitHub** (boolean) - Indicates if GitHub OAuth is enabled. - **Google** (boolean) - Indicates if Google OAuth is enabled. ``` -------------------------------- ### Client Configuration Options Source: https://github.com/supabase-community/auth-go/blob/main/README.md Explains how to customize the auth-go client using various options like setting a custom token, authentication URL, or HTTP client. ```APIDOC ## Client Configuration Options ### Description Customize the auth-go client's behavior by providing specific options during initialization or by modifying an existing client. ### Options #### WithToken ```go func (*Client) WithToken(token string) *Client ``` Returns a client that will use the provided token in the `Authorization` header on all requests. ### Parameters - **token** (string) - The authentication token to use for requests. #### WithCustomAuthURL ```go func (*Client) WithCustomAuthURL(url string) *Client ``` Returns a client that will use the provided URL instead of the default Supabase Auth URL. This is useful for self-hosted Auth servers. ### Parameters - **url** (string) - The custom authentication server URL. #### WithClient ```go func (*Client) WithClient(client http.Client) *Client ``` Allows you to provide a custom `http.Client` instance to be used for all requests made by the auth-go client. This is useful for configuring timeouts, transport settings, etc. ### Parameters - **client** (http.Client) - The custom HTTP client to use. ``` -------------------------------- ### Clone the Repository Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Clone your forked repository and navigate into the project directory. ```bash git clone https://github.com/YOUR-USERNAME/auth-go.git cd auth-go ``` -------------------------------- ### Configure Client for Self-Hosted Auth Server Source: https://context7.com/supabase-community/auth-go/llms.txt Creates a client instance that targets a custom authentication server URL. This is necessary when running a self-hosted Supabase Auth instance. ```go selfHostedClient := client.WithCustomAuthURL("https://auth.internal.example.com") health, err := selfHostedClient.HealthCheck() if err != nil { log.Fatal(err) } log.Println("Self-hosted server version:", health.Version) ``` -------------------------------- ### Implement MockHTTPClient for Go Tests Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Provides a mock HTTP client for unit testing Go applications that make HTTP requests. Allows simulating responses and errors without making actual network calls. ```go package testing import ( "bytes" "io" "net/http" ) type MockHTTPClient struct { DoFunc func(req *http.Request) (*http.Response, error) } func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) { if m.DoFunc != nil { return m.DoFunc(req) } return &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString("{}")), }, nil } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Execute all unit tests in the project. Use the -cover flag to include coverage analysis. ```bash # Run all tests go test ./... # Run with coverage go test -cover ./... # Generate coverage report go test -coverprofile=coverage.out ./... go tool cover -html=coverage.out ``` -------------------------------- ### Go Code Formatting Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Use gofmt to ensure consistent code formatting across the project. ```bash go fmt ./... ``` -------------------------------- ### Configure Client with Custom HTTP Client Source: https://github.com/supabase-community/auth-go/blob/main/README.md Returns a client that uses a provided `http.Client` instance for all network requests. This allows for custom HTTP configurations, such as custom transport, timeouts, or proxy settings. ```go func (*Client) WithClient(client http.Client) *Client ``` -------------------------------- ### auth.New - Create a base client Source: https://context7.com/supabase-community/auth-go/llms.txt Constructs a client pointed at the Supabase Auth API endpoint and attaches the API key. The returned client has a default HTTP timeout. ```APIDOC ## auth.New ### Description Constructs a client pointed at `https://.supabase.co/auth/v1` and attaches the API key to every request as the `apikey` header. The returned client has a 10-second default HTTP timeout. ### Method `auth.New(projectReference string, apiKey string) Client` ### Parameters - **projectReference** (string) - Required - Supabase project reference (Reference ID in dashboard). - **apiKey** (string) - Required - The API key for authentication. ### Request Example ```go package main import ( "log" auth "github.com/supabase-community/auth-go" "github.com/supabase-community/auth-go/types" ) func main() { client := auth.New( "abcdefghijklmnop", // Supabase project reference (Reference ID in dashboard) "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // anon key ) // Check the server is reachable health, err := client.HealthCheck() if err != nil { log.Fatal(err) } log.Printf("Auth server %s v%s", health.Name, health.Version) _ = types.HealthCheckResponse{} // types are in the types sub-package } ``` ### Response #### Success Response Returns a `Client` interface. #### Response Example (See Go code example for usage) ``` -------------------------------- ### Testing with Docker Compose Source: https://github.com/supabase-community/auth-go/blob/main/README.md Commands for managing the Docker Compose environment used for testing the auth-go library. ```bash make test make up make down ``` -------------------------------- ### Sign In with Email and Password Source: https://context7.com/supabase-community/auth-go/llms.txt Convenience function for signing in users with their email and password. Handles the underlying token exchange for a new session. ```go // Email + password session, err := client.SignInWithEmailPassword("user@example.com", "password123") if err != nil { log.Fatal(err) } log.Printf("Signed in: user_id=%s", session.User.ID) ``` -------------------------------- ### Signup - Register a new user Source: https://context7.com/supabase-community/auth-go/llms.txt Registers a new user with email and password or phone and password. The response may contain a session if autoconfirm is enabled. ```APIDOC ## Signup ### Description Registers a new user with email+password or phone+password. When the server has autoconfirm enabled the response embeds a full `Session`; otherwise it returns only the pending `User`. The library normalises both cases so that `resp.Email` (and other `User` fields) is always populated regardless of autoconfirm state. ### Method `POST /signup` ### Parameters #### Request Body - **SignupRequest** (`types.SignupRequest`) - Required - Object containing user registration details. - **Email** (string) - Optional - User's email address. - **Password** (string) - Required - User's password. - **Phone** (string) - Optional - User's phone number. - **Data** (map[string]interface{}) - Optional - User-defined metadata. ### Request Example ```go resp, err := client.Signup(types.SignupRequest{ Email: "newuser@example.com", Password: "MyStr0ngPass!", Data: map[string]interface{}{ "full_name": "Ada Lovelace", "plan": "free", }, }) if err != nil { log.Fatal("signup failed:", err) } log.Printf("User created: id=%s email=%s", resp.ID, resp.Email) // If autoconfirm is on, a session is also returned: if resp.AccessToken != "" { log.Println("Access token:", resp.AccessToken) } ``` ### Response #### Success Response (200) - **User** (`types.UserResponse`) - Contains user details. - **Session** (`types.SessionResponse`) - Contains session details (if autoconfirm is enabled). #### Response Example ```json { "ID": "a0eeb994-956f-4797-a16e-7a8408f22200", "Email": "newuser@example.com", "AccessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "ExpiresIn": 3600, "ExpiresAt": 1678886400, "TokenType": "bearer", "User": { "ID": "a0eeb994-956f-4797-a16e-7a8408f22200", "Aud": "authenticated", "Role": "authenticated", "Email": "newuser@example.com", "AppMetaData": { "provider": "email", "full_name": "Ada Lovelace", "plan": "free" }, "UserMetaData": {}, "Identities": [ { "ID": "a0eeb994-956f-4797-a16e-7a8408f22200", "UserID": "a0eeb994-956f-4797-a16e-7a8408f22200", "Provider": "email", "Traits": { "email": "newuser@example.com" }, "IdentityData": { "email": "newuser@example.com" } } ], "CreatedAt": "2023-03-15T10:00:00Z", "UpdatedAt": "2023-03-15T10:00:00Z", "IsOAuthUser": false, "HasPassword": true } } ``` ``` -------------------------------- ### Add and Commit Changes Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Stage all changes and commit them using the conventional commit format. ```bash git add . git commit -m "feat: add awesome new feature" ``` -------------------------------- ### Admin Create User with Go Source: https://context7.com/supabase-community/auth-go/llms.txt Creates a user directly, bypassing email confirmation. Requires a service-role or admin token. `EmailConfirm: true` marks the email as already confirmed. ```go adminClient := client.WithToken(serviceRoleToken) password := "InitialPass#123" newUser, err := adminClient.AdminCreateUser(types.AdminCreateUserRequest{ Email: "admin-created@example.com", Password: &password, EmailConfirm: true, Role: "authenticated", UserMetadata: map[string]interface{}{"source": "admin-import"}, AppMetadata: map[string]interface{}{"subscription": "pro"}, }) if err != nil { log.Fatal(err) } log.Printf("Admin-created user: id=%s confirmed=%v", newUser.ID, newUser.EmailConfirmedAt != nil) ``` -------------------------------- ### Run Integration Tests Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Execute integration tests. This requires Docker to be running and uses docker-compose to set up the test environment. ```bash cd integration_test docker-compose up -d go test -v docker-compose down ``` -------------------------------- ### Environment Details for Bug Report Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Provide essential environment details when reporting a bug, including Go version, auth-go version, and operating system. ```text Go version: go version auth-go version: v1.4.0 Operating System: macOS/Linux/Windows ``` -------------------------------- ### Admin List Users with Go Source: https://context7.com/supabase-community/auth-go/llms.txt Returns a paginated list of all users in the project. Use `Page` and `PerPage` to control pagination. ```go page, perPage := 1, 20 users, err := adminClient.AdminListUsers(types.AdminListUsersRequest{ Page: &page, PerPage: &perPage, }) if err != nil { log.Fatal(err) } for _, u := range users.Users { log.Printf(" %s <%s> created=%s", u.ID, u.Email, u.CreatedAt.Format("2006-01-02")) } ``` -------------------------------- ### Development Workflow with Git Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Standard Git commands for development, including committing changes and pushing to the repository. ```bash # Make changes git commit -m "feat: add new feature" git push # Create PR, merge ``` -------------------------------- ### Create Authenticated Client with Bearer Token Source: https://context7.com/supabase-community/auth-go/llms.txt Returns a new client instance configured to send a bearer token for authenticated requests. Useful after a user signs in to perform user-specific operations. ```go // After sign-in, create an authenticated client for user operations. tokenResp, err := client.SignInWithEmailPassword("user@example.com", "s3cr3t!") if err != nil { log.Fatal(err) } authedClient := client.WithToken(tokenResp.AccessToken) user, err := authedClient.GetUser() if err != nil { log.Fatal(err) } log.Printf("Signed in as %s (id: %s)", user.Email, user.ID) ``` -------------------------------- ### Release Process with release-please Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md Commands and steps involved in the automatic release process managed by release-please. This includes reviewing and merging the release PR. ```bash # When ready to release: # 1. Review Release PR # 2. Merge Release PR # → release-please automatically: # - Creates GitHub release # - Creates git tag # - Closes Release PR ``` -------------------------------- ### Configure Client with Custom Auth URL Source: https://github.com/supabase-community/auth-go/blob/main/README.md Returns a client configured to use a custom authentication server URL instead of the default Supabase-hosted URL. This allows integration with self-hosted Supabase Auth deployments. ```go func (*Client) WithCustomAuthURL(url string) *Client ``` -------------------------------- ### Sign In with Phone and Password Source: https://context7.com/supabase-community/auth-go/llms.txt Convenience function for signing in users with their phone number and password. Similar to email sign-in, it manages the token exchange. ```go // Phone + password session2, err := client.SignInWithPhonePassword("+15550001234", "password123") if err != nil { log.Fatal(err) } log.Printf("Phone sign-in: user_id=%s", session2.User.ID) ``` -------------------------------- ### Push to Fork Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Push your feature branch to your forked repository on GitHub. ```bash git push origin feat/my-new-feature ``` -------------------------------- ### WithClient - Custom HTTP client Source: https://context7.com/supabase-community/auth-go/llms.txt Returns a copy of the client that uses a supplied `http.Client` for all requests. Allows configuration of timeouts, proxies, TLS settings, etc. ```APIDOC ## WithClient ### Description Returns a copy of the client that uses the supplied `http.Client` for all requests. Use this to configure timeouts, proxies, TLS settings, or redirect behaviour. ### Method `Client.WithClient(httpClient http.Client) Client` ### Parameters - **httpClient** (`http.Client`) - Required - The custom HTTP client to use for requests. ### Request Example ```go import "net/http" import "time" httpClient := http.Client{ Timeout: 30 * time.Second, // Prevent following redirects (useful for Authorize / SAML ACS): CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } customClient := client.WithClient(httpClient) ``` ### Response Returns a new `Client` instance configured to use the custom HTTP client. ``` -------------------------------- ### Invite User with Supabase Auth Go Source: https://context7.com/supabase-community/auth-go/llms.txt Sends an invite email to a new or existing user. Requires a service-role token to initialize the client. The invite can include custom data and a redirect URL. ```go adminClient := client.WithToken(serviceRoleToken) inviteResp, err := adminClient.Invite(types.InviteRequest{ Email: "colleague@example.com", RedirectTo: "https://app.example.com/accept-invite", Data: map[string]interface{}{ "invited_by": "alice@example.com", "role": "editor", }, }) if err != nil { log.Fatal(err) } log.Printf("Invite sent. User id: %s, invited_at: %s", inviteResp.ID, inviteResp.InvitedAt) ``` -------------------------------- ### Test Changes Source: https://github.com/supabase-community/auth-go/blob/main/CONTRIBUTING.md Run all tests and integration tests to ensure your changes are correct and do not introduce regressions. ```bash # Run all tests go test ./... # Run integration tests cd integration_test docker-compose up -d go test -v docker-compose down ``` -------------------------------- ### WithCustomAuthURL - Self-hosted Auth server Source: https://context7.com/supabase-community/auth-go/llms.txt Returns a copy of the client that targets a custom URL instead of the default Supabase-hosted endpoint. Useful for self-hosted Auth servers. ```APIDOC ## WithCustomAuthURL ### Description Returns a copy of the client that targets the given URL instead of the default Supabase-hosted endpoint. Useful when running a self-hosted Auth server. ### Method `Client.WithCustomAuthURL(url string) Client` ### Parameters - **url** (string) - Required - The custom URL for the Auth server. ### Request Example ```go selfHostedClient := client.WithCustomAuthURL("https://auth.internal.example.com") health, err := selfHostedClient.HealthCheck() if err != nil { log.Fatal(err) } log.Println("Self-hosted server version:", health.Version) ``` ### Response Returns a new `Client` instance configured to use the custom Auth URL. ``` -------------------------------- ### Manage SAML SSO Providers with Supabase Auth Go Source: https://context7.com/supabase-community/auth-go/llms.txt Full CRUD operations for SAML SSO identity providers registered in the Auth server. Requires an initialized admin client. Ensure necessary imports like 'github.com/google/uuid' for provider ID manipulation. ```go // List providers, err := adminClient.AdminListSSOProviders() for _, p := range providers.Providers { log.Printf("SSO provider: id=%s entity=%s", p.ID, p.SAMLProvider.EntityID) } ``` ```go // Create a new SAML provider from a metadata URL created, err := adminClient.AdminCreateSSOProvider(types.AdminCreateSSOProviderRequest{ Type: "saml", MetadataURL: "https://idp.corp.example.com/metadata", Domains: []string{"corp.example.com"}, }) if err != nil { log.Fatal(err) } log.Printf("Created SSO provider: %s", created.ID) ``` ```go // Delete import "github.com/google/uuid" providerID := uuid.MustParse(created.ID.String()) deleted, err := adminClient.AdminDeleteSSOProvider(types.AdminDeleteSSOProviderRequest{ ProviderID: providerID, }) log.Printf("Deleted SSO provider: %s", deleted.ID) ``` -------------------------------- ### Initiate SAML SSO Session Source: https://context7.com/supabase-community/auth-go/llms.txt Initiates a SAML SSO session with a registered identity provider, identified by UUID or email domain. Set `SkipHTTPRedirect: true` to obtain the redirect URL instead of following it. Ensure the `types.SSORequest` struct is correctly populated. ```go import "github.com/google/uuid" ssoResp, err := client.SSO(types.SSORequest{ Domain: "corp.example.com", RedirectTo: "https://app.example.com/auth/callback", SkipHTTPRedirect: true, }) if err != nil { log.Fatal(err) } log.Println("Redirect user to IdP:", ssoResp.URL) // Or by provider UUID: providerID := uuid.MustParse("11111111-2222-3333-4444-555555555555") ssoResp2, err := client.SSO(types.SSORequest{ ProviderID: providerID, RedirectTo: "https://app.example.com/auth/callback", SkipHTTPRedirect: true, }) ``` -------------------------------- ### GitHub Action for Release Automation Source: https://github.com/supabase-community/auth-go/blob/main/ROADMAP.md This GitHub Actions workflow uses the release-please-action to automate the release process for Go projects. It requires write permissions for contents and pull-requests. ```yaml name: release-please on: push: branches: - main permissions: contents: write pull-requests: write jobs: release-please: runs-on: ubuntu-latest steps: - uses: googleapis/release-please-action@v4 with: release-type: go package-name: auth-go changelog-types: | [ {"type":"feat","section":"Features","hidden":false}, {"type":"fix","section":"Bug Fixes","hidden":false}, {"type":"perf","section":"Performance","hidden":false}, {"type":"docs","section":"Documentation","hidden":false}, {"type":"refactor","section":"Code Refactoring","hidden":false}, {"type":"test","section":"Tests","hidden":true}, {"type":"chore","section":"Miscellaneous","hidden":true} ] ```