Documentation
¶
Overview ¶
Package goten provides composable, self-hosted authentication for Go.
Index ¶
- Variables
- func CoreSchema() map[string]TableSchema
- func DecodeJSON(r *http.Request, dst any) error
- func GetClientIP(r *http.Request, ipHeader string) string
- func SessionFromContext(ctx context.Context) (*models.Session, bool)
- func UserFromContext(ctx context.Context) (*models.User, bool)
- func WithSession(ctx context.Context, sess *models.Session, user *models.User) context.Context
- func WriteError(w http.ResponseWriter, status int, code, message string)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type APIError
- type Account
- type Adapter
- type Auth
- func (a *Auth) Adapter() Adapter
- func (a *Auth) Config() Config
- func (a *Auth) CurrentSession(r *http.Request) (*models.Session, *models.User, error)
- func (a *Auth) Handler() http.Handler
- func (a *Auth) InternalAdapter() *InternalAdapter
- func (a *Auth) IsTrustedOrigin(origin string) bool
- func (a *Auth) Plugins() []Plugin
- func (a *Auth) RequireAuth(next http.Handler) http.Handler
- func (a *Auth) RunSessionCreateHooks(w http.ResponseWriter, r *http.Request, userID string) error
- func (a *Auth) RunUserCreateHooks(data map[string]any) map[string]any
- func (a *Auth) Sessions() *session.Manager
- func (a *Auth) SetSessionCookie(w http.ResponseWriter, sess *models.Session)
- type AuthAware
- type Config
- type CookieConfig
- type EmailPasswordConfig
- type Endpoint
- type EndpointProvider
- type FieldDef
- type Initializer
- type InternalAdapter
- func (ia *InternalAdapter) Adapter() adp.Adapter
- func (ia *InternalAdapter) CreateAccount(ctx context.Context, userID, accountID, providerID string, ...) (*models.Account, error)
- func (ia *InternalAdapter) CreateUser(ctx context.Context, email, name string, emailVerified bool) (*models.User, error)
- func (ia *InternalAdapter) CreateUserWithExtra(ctx context.Context, email, name string, emailVerified bool, ...) (*models.User, error)
- func (ia *InternalAdapter) CreateVerificationValue(ctx context.Context, identifier, value string, expiresAt time.Time) (*models.Verification, error)
- func (ia *InternalAdapter) DeleteUser(ctx context.Context, id string) error
- func (ia *InternalAdapter) DeleteVerificationByIdentifier(ctx context.Context, identifier string) error
- func (ia *InternalAdapter) FindAccountByProviderAndID(ctx context.Context, providerID, accountID string) (*models.Account, error)
- func (ia *InternalAdapter) FindAccountsByUserID(ctx context.Context, userID string) ([]*models.Account, error)
- func (ia *InternalAdapter) FindUserByEmail(ctx context.Context, email string) (*models.User, error)
- func (ia *InternalAdapter) FindUserByID(ctx context.Context, id string) (*models.User, error)
- func (ia *InternalAdapter) FindVerificationValue(ctx context.Context, identifier string) (*models.Verification, error)
- func (ia *InternalAdapter) UpdatePassword(ctx context.Context, userID, hashedPassword string) error
- func (ia *InternalAdapter) UpdateUser(ctx context.Context, id string, data map[string]any) (*models.User, error)
- func (ia *InternalAdapter) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
- type Plugin
- type Query
- type SchemaProvider
- type Session
- type SessionConfig
- type SessionCreateContext
- type SessionCreateHookFn
- type SessionCreateHookProvider
- type TableSchema
- type User
- type UserCreateHookFn
- type UserCreateHookProvider
- type Where
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidToken = &APIError{Code: "INVALID_TOKEN", Message: "invalid session token", Status: 401} ErrInvalidEmail = &APIError{Code: "INVALID_EMAIL", Message: "invalid email", Status: 400} ErrInvalidPassword = &APIError{Code: "INVALID_CREDENTIALS", Message: "invalid email or password", Status: 400} ErrEmailExists = &APIError{Code: "EMAIL_EXISTS", Message: "email already exists", Status: 409} ErrUserNotFound = &APIError{Code: "USER_NOT_FOUND", Message: "user not found", Status: 404} ErrSessionExpired = &APIError{Code: "SESSION_EXPIRED", Message: "session expired", Status: 401} ErrSessionNotFound = &APIError{Code: "SESSION_NOT_FOUND", Message: "session not found", Status: 401} ErrInternal = &APIError{Code: "INTERNAL", Message: "internal server error", Status: 500} ErrNoSession = &APIError{Code: "UNAUTHORIZED", Message: "no session", Status: 401} )
var CoreTableOrder = []string{"users", "sessions", "accounts", "verification"}
CoreTableOrder lists the core tables in dependency order (referenced tables first), so generated models and AllModels() can be emitted/migrated safely.
var EQ = adp.EQ
EQ constructs an equality Where clause.
var ErrHookHandled = errors.New("hook handled the response")
ErrHookHandled signals that a hook already wrote the HTTP response. Callers must not write again; just return.
Functions ¶
func CoreSchema ¶ added in v0.2.0
func CoreSchema() map[string]TableSchema
CoreSchema returns the declarative schema for goten's built-in tables (users, sessions, accounts, verification). It is the source of truth for the `goten generate` CLI, which merges it with each enabled plugin's SchemaProvider.Schema() to emit ORM models. The map-based runtime adapter reads/writes these same column names, kept in sync via this declaration.
func WithSession ¶
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, code, message string)
Types ¶
type APIError ¶
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
}
func (*APIError) WriteJSON ¶
func (e *APIError) WriteJSON(w http.ResponseWriter)
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is the composition root. Create with New() and mount Handler() on your server.
func (*Auth) CurrentSession ¶ added in v0.2.0
CurrentSession resolves the active session and user from the request (session cookie or Bearer token), applying sliding refresh. It is a plugin-friendly helper for endpoints that need the caller's identity without going through the RequireAuth middleware. Returns an error when there is no valid session.
func (*Auth) InternalAdapter ¶
func (a *Auth) InternalAdapter() *InternalAdapter
func (*Auth) IsTrustedOrigin ¶ added in v0.2.0
IsTrustedOrigin reports whether origin matches the configured BaseURL or one of the TrustedOrigins. Exposed so plugins can validate redirect/callback URLs (e.g. to prevent open-redirects in the OAuth flow).
func (*Auth) RequireAuth ¶
RequireAuth middleware validates the session and injects user+session into context. Use this to protect your own application endpoints.
func (*Auth) RunSessionCreateHooks ¶
RunSessionCreateHooks runs all session-create veto hooks. Returns ErrHookHandled if a hook already wrote the response (caller must not write again).
func (*Auth) RunUserCreateHooks ¶
RunUserCreateHooks applies all user-create hooks to data in registration order.
func (*Auth) SetSessionCookie ¶
func (a *Auth) SetSessionCookie(w http.ResponseWriter, sess *models.Session)
SetSessionCookie is a plugin-friendly helper that sets the session cookie using Auth's configured cookie settings. Plugins call this instead of accessing the internal cookieConfig directly.
type AuthAware ¶
type AuthAware interface {
SetAuth(a *Auth)
}
AuthAware — plugin receives a reference to *Auth after New() sets up core state.
type Config ¶
type Config struct {
AppName string
BaseURL string
BasePath string
Secret string
Adapter Adapter
Plugins []Plugin
Session SessionConfig
Cookie CookieConfig
EmailPassword EmailPasswordConfig
TrustedOrigins []string
}
type CookieConfig ¶
type EmailPasswordConfig ¶
type Endpoint ¶
type Endpoint struct {
Method string // "GET", "POST", etc.
Path string // relative path prefixed with BasePath in the router
Handler http.HandlerFunc
}
Endpoint describes a single HTTP endpoint a plugin registers.
type EndpointProvider ¶
type EndpointProvider interface {
Endpoints() []Endpoint
}
EndpointProvider — plugin registers additional HTTP endpoints.
type FieldDef ¶
type FieldDef struct {
Name string
Type string // "text", "boolean", "integer", "timestamp"
Required bool // NOT NULL
Unique bool // unique index
Index bool // non-unique index
PrimaryKey bool // primary key column (e.g. id)
Ref string // foreign key target "table.column" (onDelete CASCADE assumed)
Default string // optional DDL default literal, e.g. "false", "”"
}
FieldDef describes a single column.
type Initializer ¶
type Initializer interface {
Init() error
}
Initializer — plugin needs a one-time init step (validate config, connect to external service, etc.).
type InternalAdapter ¶
type InternalAdapter struct {
// contains filtered or unexported fields
}
InternalAdapter provides typed CRUD methods on top of the raw Adapter interface.
func NewInternalAdapter ¶
func NewInternalAdapter(a adp.Adapter) *InternalAdapter
func (*InternalAdapter) Adapter ¶
func (ia *InternalAdapter) Adapter() adp.Adapter
Adapter returns the raw underlying adapter for plugins that need direct access.
func (*InternalAdapter) CreateAccount ¶
func (*InternalAdapter) CreateUser ¶
func (*InternalAdapter) CreateUserWithExtra ¶
func (*InternalAdapter) CreateVerificationValue ¶ added in v0.2.0
func (ia *InternalAdapter) CreateVerificationValue(ctx context.Context, identifier, value string, expiresAt time.Time) (*models.Verification, error)
CreateVerificationValue stores a key-value record with an expiry, keyed by identifier. Used by the OAuth plugin to persist sign-in state.
func (*InternalAdapter) DeleteUser ¶
func (ia *InternalAdapter) DeleteUser(ctx context.Context, id string) error
func (*InternalAdapter) DeleteVerificationByIdentifier ¶ added in v0.2.0
func (ia *InternalAdapter) DeleteVerificationByIdentifier(ctx context.Context, identifier string) error
DeleteVerificationByIdentifier removes all verification records for the identifier.
func (*InternalAdapter) FindAccountByProviderAndID ¶
func (*InternalAdapter) FindAccountsByUserID ¶
func (*InternalAdapter) FindUserByEmail ¶
func (*InternalAdapter) FindUserByID ¶
func (*InternalAdapter) FindVerificationValue ¶ added in v0.2.0
func (ia *InternalAdapter) FindVerificationValue(ctx context.Context, identifier string) (*models.Verification, error)
FindVerificationValue returns the verification record for the given identifier, or nil.
func (*InternalAdapter) UpdatePassword ¶
func (ia *InternalAdapter) UpdatePassword(ctx context.Context, userID, hashedPassword string) error
func (*InternalAdapter) UpdateUser ¶
func (*InternalAdapter) WithTransaction ¶ added in v0.2.0
func (ia *InternalAdapter) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
WithTransaction runs fn inside a database transaction when the underlying adapter supports it (adp.TxRunner); otherwise fn runs directly (best-effort, e.g. for in-memory test adapters). Calls made with the context passed to fn participate in the same transaction.
type Plugin ¶
type Plugin interface {
ID() string
}
Plugin is the base interface — all plugins must implement at minimum ID().
type SchemaProvider ¶
type SchemaProvider interface {
Schema() map[string]TableSchema
}
SchemaProvider — plugin declares the DB columns/tables it adds. This is the source of truth for the `goten generate` CLI, which merges these with the core schema to emit ORM models (e.g. GORM structs).
type SessionCreateContext ¶
type SessionCreateContext struct {
UserID string
Request *http.Request
Writer http.ResponseWriter
}
SessionCreateContext carries request context for session-create hooks.
type SessionCreateHookFn ¶
type SessionCreateHookFn func(ctx SessionCreateContext) error
SessionCreateHookFn is called before inserting a new session. Return a non-nil error to abort. Return ErrHookHandled if the hook already wrote the response.
type SessionCreateHookProvider ¶
type SessionCreateHookProvider interface {
SessionCreateHooks() []SessionCreateHookFn
}
SessionCreateHookProvider — plugin hooks into session creation.
type TableSchema ¶
type TableSchema struct {
Fields []FieldDef
// UniqueTogether lists composite-unique column groups, e.g.
// {{"provider_id", "account_id"}} for the accounts table.
UniqueTogether [][]string
}
TableSchema describes the columns (and table-level constraints) for a table.
type UserCreateHookFn ¶
UserCreateHookFn is called before inserting a new user. Receives and returns the data map so plugins can add or transform fields.
type UserCreateHookProvider ¶
type UserCreateHookProvider interface {
UserCreateHooks() []UserCreateHookFn
}
UserCreateHookProvider — plugin hooks into user creation.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adapter defines the database adapter interface used by goten core and plugins.
|
Package adapter defines the database adapter interface used by goten core and plugins. |
|
adapters
|
|
|
gorm
module
|
|
|
cmd
|
|
|
goten
module
|
|
|
plugins
|
|
|
admin
module
|
|
|
oauth
module
|
|
|
username
module
|
|
|
Package session provides session lifecycle management and cookie utilities for goten.
|
Package session provides session lifecycle management and cookie utilities for goten. |