auth

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package auth provides a comprehensive SDK for Supabase Authentication.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidArgument is returned when an argument is invalid
	ErrInvalidArgument = errors.New("invalid argument")

	// ErrNotAuthenticated is returned when the client is not authenticated
	ErrNotAuthenticated = errors.New("not authenticated")

	// ErrFailedRequest is returned when a request fails
	ErrFailedRequest = errors.New("failed to make request")

	// ErrFailedParsing is returned when parsing a response fails
	ErrFailedParsing = errors.New("failed to parse response")

	// ErrFailedEncoding is returned when encoding a request fails
	ErrFailedEncoding = errors.New("failed to encode request")

	// ErrAPIError is returned when the Supabase API returns an error
	ErrAPIError = errors.New("supabase API error")

	// ErrInvalidToken is returned when a token is invalid
	ErrInvalidToken = errors.New("invalid token")

	// ErrExpiredToken is returned when a token has expired
	ErrExpiredToken = errors.New("token has expired")

	// ErrUserNotFound is returned when a user is not found
	ErrUserNotFound = errors.New("user not found")

	// ErrEmailTaken is returned when an email is already taken
	ErrEmailTaken = errors.New("email already taken")

	// ErrPhoneTaken is returned when a phone number is already taken
	ErrPhoneTaken = errors.New("phone number already taken")

	// ErrNotImplemented is returned when a feature is not implemented
	ErrNotImplemented = errors.New("not implemented")
)

Functions

func BuildFilter

func BuildFilter(field, operator, value string) string

BuildFilter creates a filter string for user queries

func GetRoleFromToken

func GetRoleFromToken(token string) (string, error)

GetRoleFromToken extracts the role from a JWT token

func GetUserIDFromToken

func GetUserIDFromToken(token string) (string, error)

GetUserIDFromToken extracts the user ID from a JWT token

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError checks if an error is an authentication error

func IsAuthorizationError

func IsAuthorizationError(err error) bool

IsAuthorizationError checks if an error is an authorization error

func IsConflictError

func IsConflictError(err error) bool

IsConflictError checks if an error is a conflict error (e.g., email already taken)

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is a not found error

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError checks if an error is a rate limit error

func IsServerError

func IsServerError(err error) bool

IsServerError checks if an error is a server error

func IsTokenExpired

func IsTokenExpired(token string) (bool, error)

IsTokenExpired checks if a JWT token has expired

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	ErrorType  string
	ErrorCode  string
}

APIError represents an error returned by the Supabase API

func NewAPIError

func NewAPIError(statusCode int, errorType string, message string, errorCode string) *APIError

NewAPIError creates a new APIError

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface for APIError

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a Supabase client that handles both user and admin operations

func NewClient

func NewClient(projectURL, apiKey string) *Client

NewClient creates a new Supabase client with default configuration

func (*Client) CreateAuthProvider

func (c *Client) CreateAuthProvider(ctx context.Context, provider string, options map[string]interface{}) error

CreateAuthProvider enables a new auth provider

func (*Client) CreateManyUsers

func (c *Client) CreateManyUsers(ctx context.Context, users []*CreateUserOptions) ([]interface{}, error)

CreateManyUsers creates multiple users in a batch operation

func (*Client) CreateUser

func (c *Client) CreateUser(ctx context.Context, options *CreateUserOptions) (*User, error)

CreateUser creates a new user with the specified properties

func (*Client) DeleteAuthProvider

func (c *Client) DeleteAuthProvider(ctx context.Context, provider string) error

DeleteAuthProvider disables an auth provider

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, userID string) error

DeleteUser deletes a user by their ID

func (*Client) DeleteUserSessions

func (c *Client) DeleteUserSessions(ctx context.Context, userID string) error

DeleteUserSessions invalidates all sessions for a user

func (c *Client) GenerateLink(ctx context.Context, action LinkAction, options *GenerateLinkOptions) (*LinkResponse, error)

GenerateLink generates an email link for a specific action

func (*Client) GenerateUserMigration

func (c *Client) GenerateUserMigration(ctx context.Context, userID string, options map[string]interface{}) (map[string]interface{}, error)

GenerateUserMigration generates a migration token for a user

func (*Client) GetAuthSettings

func (c *Client) GetAuthSettings(ctx context.Context) (map[string]interface{}, error)

GetAuthSettings gets the auth settings for the project

func (*Client) GetSession

func (c *Client) GetSession() (accessToken, refreshToken string, expiry time.Time)

GetSession returns the current session tokens

func (*Client) GetUser

func (c *Client) GetUser(ctx context.Context, userID string) (*User, error)

GetUser retrieves a user by their ID

func (*Client) GetUserByEmail added in v0.1.1

func (c *Client) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a user by their email

func (*Client) InviteUserByEmail

func (c *Client) InviteUserByEmail(ctx context.Context, email string, options *InviteOptions) (*User, error)

InviteUserByEmail creates a user and sends an invite link

func (*Client) ListAuditLogs

func (c *Client) ListAuditLogs(ctx context.Context, options map[string]string) ([]map[string]interface{}, error)

ListAuditLogs retrieves the audit logs for the project

func (*Client) ListFactors

func (c *Client) ListFactors(ctx context.Context, userID string) ([]Factor, error)

ListFactors lists all MFA factors for a user

func (*Client) ListUserSessions

func (c *Client) ListUserSessions(ctx context.Context, userID string) ([]Session, error)

ListUserSessions lists all active sessions for a user

func (*Client) ListUsers

func (c *Client) ListUsers(ctx context.Context, options *ListUsersOptions) (*UserList, error)

ListUsers returns a list of users with pagination

func (*Client) RefreshSession

func (c *Client) RefreshSession(ctx context.Context) error

RefreshSession refreshes the access token using the refresh token

func (*Client) ResetPasswordForEmail

func (c *Client) ResetPasswordForEmail(ctx context.Context, email string) error

ResetPasswordForEmail sends a password reset email

func (*Client) SetSession

func (c *Client) SetSession(accessToken, refreshToken string, expiresIn int)

SetSession sets the current session tokens

func (*Client) SetUserRole

func (c *Client) SetUserRole(ctx context.Context, userID, role string) (*User, error)

SetUserRole updates a user's role

func (*Client) SignIn

func (c *Client) SignIn(ctx context.Context, email, password string) (*TokenResponse, error)

SignIn authenticates a user with email and password

func (*Client) SignOut

func (c *Client) SignOut(ctx context.Context) error

SignOut invalidates all session tokens for a user

func (*Client) SignUp

func (c *Client) SignUp(ctx context.Context, email, password string, userData map[string]interface{}) (*TokenResponse, error)

SignUp registers a new user with email and password

func (*Client) UpdateAuthProvider

func (c *Client) UpdateAuthProvider(ctx context.Context, provider string, options map[string]interface{}) error

UpdateAuthProvider updates an existing auth provider

func (*Client) UpdateAuthSettings

func (c *Client) UpdateAuthSettings(ctx context.Context, settings map[string]interface{}) error

UpdateAuthSettings updates the auth settings for the project

func (*Client) UpdateUser

func (c *Client) UpdateUser(ctx context.Context, userID string, options *UpdateUserOptions) (*User, error)

UpdateUser updates an existing user with new properties

func (*Client) VerifyJWT added in v0.1.1

func (c *Client) VerifyJWT(token, jwtSecret string, issuer string) (*JWTPayload, error)

VerifyJWT validates a JWT token locally without calling the Supabase API It verifies the token signature using the provided JWT secret, checks the issuer (if provided), and token expiration Returns the decoded token payload if verification is successful

func (*Client) VerifyTokenWithAPI added in v0.1.1

func (c *Client) VerifyTokenWithAPI(ctx context.Context, token string) (*User, error)

VerifyTokenWithAPI validates a JWT token by calling the Supabase API and returns the user information

func (*Client) WithConfig

func (c *Client) WithConfig(config *Config) *Client

WithConfig returns a client with a custom configuration

func (*Client) WithHTTPClient

func (c *Client) WithHTTPClient(httpClient *http.Client) *Client

WithHTTPClient returns a client with a custom HTTP client

type Config

type Config struct {
	// ProjectURL is the URL of your Supabase project (required)
	ProjectURL string

	// APIKey is your Supabase project API key (service_role key for admin functions)
	APIKey string

	// AutoRefreshTokens determines whether to automatically refresh expired tokens
	AutoRefreshTokens bool

	// PersistSession determines whether to persist session information
	PersistSession bool

	// TokenCallback is called when tokens are refreshed
	TokenCallback func(accessToken, refreshToken string)

	// Debug enables debug logging
	Debug bool
}

Config represents the configuration for the Supabase Auth client

func DefaultConfig

func DefaultConfig(projectURL, apiKey string) *Config

DefaultConfig returns a default configuration

type CreateUserOptions

type CreateUserOptions struct {
	Email        string                 `json:"email,omitempty"`
	Phone        string                 `json:"phone,omitempty"`
	Password     string                 `json:"password,omitempty"`
	EmailConfirm bool                   `json:"email_confirm,omitempty"`
	PhoneConfirm bool                   `json:"phone_confirm,omitempty"`
	UserMetadata map[string]interface{} `json:"user_metadata,omitempty"`
	AppMetadata  map[string]interface{} `json:"app_metadata,omitempty"`
	BanDuration  string                 `json:"ban_duration,omitempty"`
	Data         map[string]interface{} `json:"data,omitempty"` // For custom claims
	Role         string                 `json:"role,omitempty"`
}

CreateUserOptions contains options for creating a user

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message"`
	Code    string `json:"code"`
}

ErrorResponse represents an error response from the Supabase API

type Factor

type Factor struct {
	ID           string                 `json:"id"`
	UserID       string                 `json:"user_id"`
	Type         string                 `json:"type"`
	Status       string                 `json:"status"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
	FriendlyName string                 `json:"friendly_name"`
	FactorData   map[string]interface{} `json:"factor_data"`
}

Factor represents a multi-factor authentication factor

type GenerateLinkOptions

type GenerateLinkOptions struct {
	Email      string                 `json:"email"`
	RedirectTo string                 `json:"redirect_to,omitempty"`
	Data       map[string]interface{} `json:"data,omitempty"`
}

GenerateLinkOptions contains options for generating authentication links

type Identity

type Identity struct {
	ID           string                 `json:"id"`
	UserID       string                 `json:"user_id"`
	IdentityData map[string]interface{} `json:"identity_data"`
	Provider     string                 `json:"provider"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
	LastSignInAt time.Time              `json:"last_sign_in_at"`
}

Identity represents a user's identity from an OAuth provider

type InviteOptions

type InviteOptions struct {
	RedirectTo   string                 `json:"redirect_to,omitempty"`
	Data         map[string]interface{} `json:"data,omitempty"`
	UserMetadata map[string]interface{} `json:"user_metadata,omitempty"`
}

InviteOptions contains options for inviting users

type JWTPayload

type JWTPayload struct {
	Sub          string                 `json:"sub"`
	Role         string                 `json:"role"`
	Email        string                 `json:"email"`
	Exp          int64                  `json:"exp"`
	Iat          int64                  `json:"iat"`
	Aud          string                 `json:"aud"`
	Iss          string                 `json:"iss"`
	AppMetadata  map[string]interface{} `json:"app_metadata"`
	UserMetadata map[string]interface{} `json:"user_metadata"`
}

JWTPayload represents the decoded JWT payload

func DecodeJWT

func DecodeJWT(token string) (*JWTPayload, error)

DecodeJWT decodes a JWT token without verification

func VerifyJWTWithSecret added in v0.1.1

func VerifyJWTWithSecret(token string, jwtSecret string, issuer string) (*JWTPayload, error)

VerifyJWTWithSecret verifies a JWT token locally without making an API call to Supabase It checks the token signature, issuer (if provided), and expiration Returns the decoded claims and an error if verification fails

type LinkAction

type LinkAction string

LinkAction represents the type of action for which to generate a link

const (
	// LinkActionSignUp generates a signup link
	LinkActionSignUp LinkAction = "signup"
	// LinkActionInvite generates an invite link
	LinkActionInvite LinkAction = "invite"
	// LinkActionMagicLink generates a magic link
	LinkActionMagicLink LinkAction = "magiclink"
	// LinkActionRecovery generates a password recovery link
	LinkActionRecovery LinkAction = "recovery"
	// LinkActionEmailChange generates an email change confirmation link
	LinkActionEmailChange LinkAction = "email_change"
)

type LinkResponse

type LinkResponse struct {
	Link         string    `json:"link"`
	PKCE         bool      `json:"pkce"`
	UserID       string    `json:"user_id,omitempty"`
	Email        string    `json:"email"`
	GeneratedAt  time.Time `json:"generated_at"`
	ExpiresAt    time.Time `json:"expires_at"`
	RedirectedTo string    `json:"redirected_to,omitempty"`
}

LinkResponse represents a response for a generated link

type ListUsersOptions

type ListUsersOptions struct {
	Page      int    `json:"page,omitempty"`
	PerPage   int    `json:"per_page,omitempty"`
	Filter    string `json:"filter,omitempty"`
	SortBy    string `json:"sort_by,omitempty"`
	SortOrder string `json:"sort_order,omitempty"`
}

ListUsersOptions contains options for listing users

type Session

type Session struct {
	ID           string    `json:"id"`
	UserID       string    `json:"user_id"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	Factor       string    `json:"factor"`
	IPAddress    string    `json:"ip_address"`
	UserAgent    string    `json:"user_agent"`
	LastUsedAt   time.Time `json:"last_used_at"`
	RefreshToken string    `json:"refresh_token"`
	ExpiresAt    time.Time `json:"expires_at"`
}

Session represents a user's active session

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
	User         User   `json:"user"`
}

TokenResponse represents the response from authentication endpoints

type UpdateUserOptions

type UpdateUserOptions struct {
	Email        *string                 `json:"email,omitempty"`
	Phone        *string                 `json:"phone,omitempty"`
	Password     *string                 `json:"password,omitempty"`
	UserMetadata map[string]interface{}  `json:"user_metadata,omitempty"`
	AppMetadata  map[string]interface{}  `json:"app_metadata,omitempty"`
	Banned       *bool                   `json:"banned,omitempty"`
	BanDuration  *string                 `json:"ban_duration,omitempty"`
	Role         *string                 `json:"role,omitempty"`
	Data         *map[string]interface{} `json:"data,omitempty"` // For custom claims
}

UpdateUserOptions contains options for updating a user

type User

type User struct {
	ID                 string                 `json:"id"`
	Aud                string                 `json:"aud"`
	Role               string                 `json:"role"`
	Email              string                 `json:"email"`
	Phone              string                 `json:"phone"`
	EmailConfirmed     *time.Time             `json:"email_confirmed_at,omitempty"`
	PhoneConfirmed     *time.Time             `json:"phone_confirmed_at,omitempty"`
	LastSignInAt       time.Time              `json:"last_sign_in_at,omitempty"`
	AppMetadata        map[string]interface{} `json:"app_metadata"`
	UserMetadata       map[string]interface{} `json:"user_metadata"`
	Identities         []Identity             `json:"identities"`
	CreatedAt          time.Time              `json:"created_at"`
	UpdatedAt          time.Time              `json:"updated_at"`
	IsAnonymous        bool                   `json:"is_anonymous,omitempty"`
	BannedUntil        *time.Time             `json:"banned_until,omitempty"`
	ConfirmedAt        *time.Time             `json:"confirmed_at,omitempty"`
	ConfirmationSentAt *time.Time             `json:"confirmation_sent_at,omitempty"`
	RecoverySentAt     *time.Time             `json:"recovery_sent_at,omitempty"`
	EmailChange        string                 `json:"email_change,omitempty"`
	EmailChangeSentAt  *time.Time             `json:"email_change_sent_at,omitempty"`
	PhoneChange        string                 `json:"phone_change,omitempty"`
	PhoneChangeSentAt  *time.Time             `json:"phone_change_sent_at,omitempty"`
	FactorsVerified    bool                   `json:"factors_confirmed,omitempty"`
}

User represents a Supabase user

type UserList

type UserList struct {
	Users      []User `json:"users"`
	TotalCount int    `json:"total_count"`
	NextPage   int    `json:"next_page,omitempty"`
	PrevPage   int    `json:"prev_page,omitempty"`
}

UserList represents a paginated list of users

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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