Documentation
¶
Overview ¶
Package auth provides a comprehensive SDK for Supabase Authentication.
Index ¶
- Variables
- func BuildFilter(field, operator, value string) string
- func GetRoleFromToken(token string) (string, error)
- func GetUserIDFromToken(token string) (string, error)
- func IsAuthenticationError(err error) bool
- func IsAuthorizationError(err error) bool
- func IsConflictError(err error) bool
- func IsNotFoundError(err error) bool
- func IsRateLimitError(err error) bool
- func IsServerError(err error) bool
- func IsTokenExpired(token string) (bool, error)
- type APIError
- type Client
- func (c *Client) CreateAuthProvider(ctx context.Context, provider string, options map[string]interface{}) error
- func (c *Client) CreateManyUsers(ctx context.Context, users []*CreateUserOptions) ([]interface{}, error)
- func (c *Client) CreateUser(ctx context.Context, options *CreateUserOptions) (*User, error)
- func (c *Client) DeleteAuthProvider(ctx context.Context, provider string) error
- func (c *Client) DeleteUser(ctx context.Context, userID string) error
- func (c *Client) DeleteUserSessions(ctx context.Context, userID string) error
- func (c *Client) GenerateLink(ctx context.Context, action LinkAction, options *GenerateLinkOptions) (*LinkResponse, error)
- func (c *Client) GenerateUserMigration(ctx context.Context, userID string, options map[string]interface{}) (map[string]interface{}, error)
- func (c *Client) GetAuthSettings(ctx context.Context) (map[string]interface{}, error)
- func (c *Client) GetSession() (accessToken, refreshToken string, expiry time.Time)
- func (c *Client) GetUser(ctx context.Context, userID string) (*User, error)
- func (c *Client) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (c *Client) InviteUserByEmail(ctx context.Context, email string, options *InviteOptions) (*User, error)
- func (c *Client) ListAuditLogs(ctx context.Context, options map[string]string) ([]map[string]interface{}, error)
- func (c *Client) ListFactors(ctx context.Context, userID string) ([]Factor, error)
- func (c *Client) ListUserSessions(ctx context.Context, userID string) ([]Session, error)
- func (c *Client) ListUsers(ctx context.Context, options *ListUsersOptions) (*UserList, error)
- func (c *Client) RefreshSession(ctx context.Context) error
- func (c *Client) ResetPasswordForEmail(ctx context.Context, email string) error
- func (c *Client) SetSession(accessToken, refreshToken string, expiresIn int)
- func (c *Client) SetUserRole(ctx context.Context, userID, role string) (*User, error)
- func (c *Client) SignIn(ctx context.Context, email, password string) (*TokenResponse, error)
- func (c *Client) SignOut(ctx context.Context) error
- func (c *Client) SignUp(ctx context.Context, email, password string, userData map[string]interface{}) (*TokenResponse, error)
- func (c *Client) UpdateAuthProvider(ctx context.Context, provider string, options map[string]interface{}) error
- func (c *Client) UpdateAuthSettings(ctx context.Context, settings map[string]interface{}) error
- func (c *Client) UpdateUser(ctx context.Context, userID string, options *UpdateUserOptions) (*User, error)
- func (c *Client) VerifyJWT(token, jwtSecret string, issuer string) (*JWTPayload, error)
- func (c *Client) VerifyTokenWithAPI(ctx context.Context, token string) (*User, error)
- func (c *Client) WithConfig(config *Config) *Client
- func (c *Client) WithHTTPClient(httpClient *http.Client) *Client
- type Config
- type CreateUserOptions
- type ErrorResponse
- type Factor
- type GenerateLinkOptions
- type Identity
- type InviteOptions
- type JWTPayload
- type LinkAction
- type LinkResponse
- type ListUsersOptions
- type Session
- type TokenResponse
- type UpdateUserOptions
- type User
- type UserList
Constants ¶
This section is empty.
Variables ¶
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 ¶
BuildFilter creates a filter string for user queries
func GetRoleFromToken ¶
GetRoleFromToken extracts the role from a JWT token
func GetUserIDFromToken ¶
GetUserIDFromToken extracts the user ID from a JWT token
func IsAuthenticationError ¶
IsAuthenticationError checks if an error is an authentication error
func IsAuthorizationError ¶
IsAuthorizationError checks if an error is an authorization error
func IsConflictError ¶
IsConflictError checks if an error is a conflict error (e.g., email already taken)
func IsNotFoundError ¶
IsNotFoundError checks if an error is a not found error
func IsRateLimitError ¶
IsRateLimitError checks if an error is a rate limit error
func IsServerError ¶
IsServerError checks if an error is a server error
func IsTokenExpired ¶
IsTokenExpired checks if a JWT token has expired
Types ¶
type APIError ¶
APIError represents an error returned by the Supabase API
func NewAPIError ¶
NewAPIError creates a new APIError
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a Supabase client that handles both user and admin operations
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 ¶
CreateUser creates a new user with the specified properties
func (*Client) DeleteAuthProvider ¶
DeleteAuthProvider disables an auth provider
func (*Client) DeleteUser ¶
DeleteUser deletes a user by their ID
func (*Client) DeleteUserSessions ¶
DeleteUserSessions invalidates all sessions for a user
func (*Client) GenerateLink ¶
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 ¶
GetAuthSettings gets the auth settings for the project
func (*Client) GetSession ¶
GetSession returns the current session tokens
func (*Client) GetUserByEmail ¶ added in v0.1.1
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 ¶
ListFactors lists all MFA factors for a user
func (*Client) ListUserSessions ¶
ListUserSessions lists all active sessions for a user
func (*Client) RefreshSession ¶
RefreshSession refreshes the access token using the refresh token
func (*Client) ResetPasswordForEmail ¶
ResetPasswordForEmail sends a password reset email
func (*Client) SetSession ¶
SetSession sets the current session tokens
func (*Client) SetUserRole ¶
SetUserRole updates a user's role
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 ¶
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
VerifyTokenWithAPI validates a JWT token by calling the Supabase API and returns the user information
func (*Client) WithConfig ¶
WithConfig returns a client with a custom configuration
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 ¶
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