core

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultSessionDataName = "kuta.session_data"
View Source
const DefaultSessionTokenName = "kuta.session_token"

Variables

View Source
var (
	// User errors
	ErrUserExists         = errors.New("user already exists")       // 409 Conflict
	ErrUserNotFound       = errors.New("user not found")            // 404 Not Found
	ErrInvalidCredentials = errors.New("invalid email or password") // 401 Unauthorized
)

Authentication Related Errors

View Source
var (
	ErrMissingAuthHeader = errors.New("missing authorization header") // 401
	ErrInvalidToken      = errors.New("invalid session token")        // 401
	ErrSessionNotFound   = errors.New("session not found")            // 401
	ErrSessionExpired    = errors.New("session expired")              // 401
	ErrCacheNotFound     = errors.New("session not found in cache")
)

Session errors

View Source
var (
	ErrInvalidAuthHeader  = errors.New("invalid authorization format, expected 'Bearer <token>'")                       // 401
	ErrEmailRequired      = errors.New("email is required")                                                             // 400
	ErrPasswordRequired   = errors.New("password is required")                                                          // 400
	ErrPasswordTooShort   = errors.New("password is too short")                                                         // 400
	ErrPasswordTooLong    = errors.New("password is too long")                                                          // 400
	ErrPasswordComplexity = errors.New("password must contain at least one uppercase letter and one special character") // 400
	ErrInvalidEmail       = errors.New("invalid email format")                                                          // 400
)

Validation errors (client input)

View Source
var (
	ErrDBAdapterRequired   = errors.New("database adapter is required") // 500
	ErrHTTPAdapterRequired = errors.New("adapter is required")          // 500
	ErrSecretRequired      = errors.New("secret is required")           // 500
	ErrSecretTooShort      = errors.New("secret too short")             // 500
)

Config errors (server-side configuration)

View Source
var (
	ErrNotImplemented     = errors.New("not implemented")      // 501
	ErrInvalidRequestBody = errors.New("invalid request body") // 400
)

Functions

This section is empty.

Types

type Account

type Account struct {
	ID           string     `json:"id"`
	UserID       string     `json:"userId"`
	ProviderID   string     `json:"providerId"` // "credential", "google", "github"
	AccountID    string     `json:"accountId"`
	Password     *string    `json:"-"` // Never expose in JSON
	AccessToken  *string    `json:"-"` // Never expose in JSON
	RefreshToken *string    `json:"-"` // Never expose in JSON
	ExpiresAt    *time.Time `json:"expiresAt,omitempty"`
	CreatedAt    time.Time  `json:"createdAt"`
	UpdatedAt    time.Time  `json:"updatedAt"`
}

Account represents an authentication method

This is the "credential" - how someone proves who they are

type AccountStorage

type AccountStorage interface {
	CreateAccount(a *Account) error
	GetAccountByID(id string) (*Account, error)
	GetAccountByUserAndProvider(userID, providerID string) ([]*Account, error)
	UpdateAccount(a *Account) error
	DeleteAccount(id string) error
}

AccountStorage defines account-related database operations

type AuthProvider

type AuthProvider interface {
	SignUp(input SignUpInput, ipAddress, userAgent string) (*SignUpResult, error)
	SignIn(input SignInInput, ipAddress, userAgent string) (*SignInResult, error)
	SignOut(token string) error
	GetSession(token string) (*SessionData, error)
	Refresh(token string) (*RefreshResult, error)
}

AuthProvider provides authentication operations for HTTP adapters

type Cache

type Cache interface {
	Get(tokenHash string) (*Session, error)
	Set(tokenHash string, session *Session) error
	Delete(tokenHash string) error
	Clear() error
}

Cache defines session caching operations

type CacheConfig

type CacheConfig struct {
	TTL     time.Duration
	MaxSize int
}

CacheConfig configures cache behavior

type CacheStats

type CacheStats struct {
	Hits      int64         `json:"hits"`
	Misses    int64         `json:"misses"`
	Sets      int64         `json:"sets"`
	Deletes   int64         `json:"deletes"`
	Evictions int64         `json:"evictions"`
	Size      int           `json:"size"`
	TTL       time.Duration `json:"ttl"`
}

CacheStats tracks cache performance metrics

type CacheWithStats

type CacheWithStats interface {
	Cache
	Stats() CacheStats
}

CacheWithStats extends Cache with statistics tracking

type CookieAction added in v0.1.3

type CookieAction struct {
	Action string // "set" or "clear"
	Name   string
	Value  string // only for "set"
}

CookieAction instructs the adapter to set or clear a cookie after the handler completes.

type CookieCacheConfig added in v0.1.2

type CookieCacheConfig struct {
	Enabled   bool
	MaxAge    time.Duration
	UpdateAge time.Duration
}

CookieCacheConfig defines behavior for client-side session caching in cookies

type CookieConfig added in v0.1.2

type CookieConfig struct {
	SessionToken      SessionToken
	SessionDataCookie SessionDataCookie
}

CookieConfig defines how session tokens are stored in cookies

func DefaultCookieConfig added in v0.1.2

func DefaultCookieConfig() *CookieConfig

type CoreAuthHandlers added in v0.1.3

type CoreAuthHandlers struct {
	Provider   AuthProvider
	SessionCfg *SessionConfig
}

CoreAuthHandlers provides the built-in auth endpoint handlers. These are framework-agnostic and work with RequestContext.

func (*CoreAuthHandlers) GetCoreEndpoints added in v0.1.3

func (h *CoreAuthHandlers) GetCoreEndpoints() []PluginEndpoint

GetCoreEndpoints returns the built-in auth endpoints (signUp, signIn, etc.). These are registered automatically by the adapter.

type CreateSessionResult

type CreateSessionResult struct {
	Session *Session `json:"session"`
	Token   string   `json:"token"`
}

type Endpoint

type Endpoint struct {
	Path     string
	Method   string
	Handler  func(ctx *RequestContext) error
	Metadata EndpointMetadata
}

type EndpointMetadata

type EndpointMetadata struct {
	OperationID string
	Description string
	RequestBody any // for validation
	Responses   map[int]any
}

type EndpointProvider

type EndpointProvider interface {
	GetEndpoints() []Endpoint
}

EndpointProvider provides a list of endpoints to register dynamically

type ErrorResponse

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

ErrorResponse represents an error response structure

type HTTPProvider

type HTTPProvider interface {
	// RegisterRoutes registers the core auth endpoints under basePath.
	RegisterRoutes(handler AuthProvider, basePath string, sessionConfig *SessionConfig) error

	// RegisterPluginEndpoints registers a plugin's self-contained endpoints.
	// The adapter wraps each PluginEndpoint handler into a framework-specific
	// route handler, applying authentication when RequireSession is true.
	RegisterPluginEndpoints(basePath string, pluginID string, endpoints []PluginEndpoint) error

	// BuildProtectedMiddleware returns a framework-specific middleware value
	// that validates auth tokens and populates user/session in context.
	BuildProtectedMiddleware(authProvider AuthProvider) any
}

type Plugin added in v0.1.3

type Plugin interface {
	// ID returns a unique identifier for the plugin
	ID() string

	// Init is called when the plugin is registered, before routes are set up
	// It receives the core dependencies and can return an error if initialization fails
	Init(deps PluginDependencies) error
}

Plugin defines the interface that all Kuta plugins must implement

type PluginDependencies added in v0.1.3

type PluginDependencies struct {
	Storage       StorageProvider
	Auth          AuthProvider
	Passwords     crypto.PasswordHandler
	Secret        string
	SessionConfig *SessionConfig
}

PluginDependencies provides core services to plugins during initialization

type PluginEndpoint added in v0.1.3

type PluginEndpoint struct {
	// Path is the route path relative to the plugin's namespace.
	// Example: "/set-role" — the adapter prepends basePath + "/admin".
	Path   string
	Method string // "GET", "POST", "PUT", "PATCH", "DELETE"

	// Handler is the framework-agnostic handler function.
	Handler func(ctx *RequestContext) error

	// RequireSession indicates the adapter must authenticate the request
	// and populate ctx.Session before calling Handler. If the request is
	// unauthenticated the adapter should return 401 without calling Handler.
	RequireSession bool

	// Metadata for OpenAPI generation.
	Metadata EndpointMetadata
}

PluginEndpoint defines a single HTTP endpoint contributed by a plugin. The handler receives a fully populated RequestContext and writes its response to the same context. Middleware booleans control what the HTTP adapter should do before invoking the handler.

type PluginWithEndpoints added in v0.1.3

type PluginWithEndpoints interface {
	Plugin

	// Endpoints returns the plugin's endpoint definitions.
	// Paths are relative to the plugin namespace (basePath + "/" + plugin.ID()).
	Endpoints() []PluginEndpoint
}

PluginWithEndpoints is an optional interface that plugins can implement to contribute self-contained HTTP endpoints. The adapter automatically registers these — no adapter-side handler code is needed per plugin.

type PluginWithHooks added in v0.1.3

type PluginWithHooks interface {
	Plugin

	// BeforeSignIn is called before a user signs in
	BeforeSignIn(userID string) error

	// AfterSignIn is called after a user successfully signs in
	AfterSignIn(userID string) error

	// BeforeSignUp is called before a user signs up
	BeforeSignUp(email string) error

	// AfterSignUp is called after a user successfully signs up
	AfterSignUp(userID string) error
}

PluginWithHooks is an optional interface for plugins that need to hook into the authentication lifecycle

type RefreshResult

type RefreshResult struct {
	Session *Session `json:"session"`
	Token   string   `json:"token"` // The raw token (not the hash)
}

type RequestContext

type RequestContext struct {

	// Body is the raw JSON request body.
	Body json.RawMessage

	// Session is the authenticated session data (nil if unauthenticated).
	Session *SessionData

	// Token is the raw session token extracted from Authorization header or cookie.
	Token string

	// PathParams holds named path parameters (e.g. {"userId": "abc123"}).
	PathParams map[string]string

	// QueryParams holds query string parameters.
	QueryParams map[string]string

	// Headers provides access to request headers (lowercase keys).
	Headers map[string]string

	// IP is the client's IP address.
	IP string

	// UserAgent is the client's User-Agent string.
	UserAgent string

	// StatusCode is the HTTP status to send. 0 defaults to 200.
	StatusCode int

	// Response is the value to serialize as the JSON response body.
	Response any
}

RequestContext is a framework-agnostic context for plugin endpoint handlers. HTTP adapters populate this before calling the plugin handler, and read the result fields after the handler returns.

func (*RequestContext) Bind added in v0.1.3

func (ctx *RequestContext) Bind(target any) error

Bind decodes the JSON body into the target struct.

func (*RequestContext) JSON added in v0.1.3

func (ctx *RequestContext) JSON(status int, body any)

JSON sets the response status code and body.

type Session

type Session struct {
	ID        string    `json:"id"`
	UserID    string    `json:"userId"`
	TokenHash string    `json:"-"` // Never expose in JSON (security!)
	IPAddress string    `json:"ipAddress"`
	UserAgent string    `json:"userAgent"`
	ExpiresAt time.Time `json:"expiresAt"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Session represents an active login session

type SessionConfig

type SessionConfig struct {
	ExpiresIn    time.Duration
	UpdateAge    time.Duration
	CookieConfig *CookieConfig
	CookieCache  *CookieCacheConfig
}

SessionConfig defines session lifetime and refresh behavior

func DefaultSessionConfig added in v0.1.2

func DefaultSessionConfig() *SessionConfig

type SessionData

type SessionData struct {
	User    *User    `json:"user"`
	Session *Session `json:"session"`
}

SessionData combines user and session info The model returned to clients

type SessionDataCookie added in v0.1.2

type SessionDataCookie struct {
	Name        string
	SessionData SessionData
}

type SessionStorage

type SessionStorage interface {
	CreateSession(session *Session) error
	GetSessionByHash(tokenHash string) (*Session, error)
	GetSessionByID(id string) (*Session, error)
	GetUserSessions(userID string) ([]*Session, error)
	UpdateSession(session *Session) error
	DeleteSessionByID(id string) error
	DeleteSessionByHash(tokenHash string) error
	DeleteUserSessions(userID string) (int, error)
	DeleteExpiredSessions() (int, error)
}

SessionStorage defines session-related database operations

type SessionToken added in v0.1.2

type SessionToken struct {
	Name       string
	Attributes SessionTokenAttributes
}

type SessionTokenAttributes added in v0.1.2

type SessionTokenAttributes struct {
	HTTPOnly bool
	Secure   bool
	SameSite string
	Path     string
}

type SignInInput

type SignInInput struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type SignInResult

type SignInResult struct {
	User    *User    `json:"user"`
	Session *Session `json:"session"`
	Token   string   `json:"token"` // The raw token (not the hash)
}

type SignUpInput

type SignUpInput struct {
	Email    string  `json:"email"`
	Password string  `json:"password"`
	Name     string  `json:"name"`
	Image    *string `json:"image,omitempty"`
}

type SignUpResult

type SignUpResult struct {
	User    *User    `json:"user"`
	Session *Session `json:"session"`
	Token   string   `json:"token"` // The raw token (not the hash)
}

type StorageProvider

type StorageProvider interface {
	UserStorage
	AccountStorage
	SessionStorage
}

type User

type User struct {
	ID            string    `json:"id"`
	Email         string    `json:"email"`
	EmailVerified bool      `json:"emailVerified"`
	Name          string    `json:"name"`
	Image         *string   `json:"image,omitempty"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

User represents a user account in the system

This is the "identity" - who someone is

type UserStorage

type UserStorage interface {
	CreateUser(u *User) error
	GetUserByID(id string) (*User, error)
	GetUserByEmail(email string) (*User, error)
	UpdateUser(u *User) error
	DeleteUser(id string) error
}

UserStorage defines user-related database operations

Jump to

Keyboard shortcuts

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