limen

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 29 Imported by: 0

README

A modern, composable authentication library for Go, inspired by better-auth.

Documentation · Issues · X (@limenauth)

Go reference GitHub stars

Limen is a modular authentication library for Go that takes a plugin-first approach — the core ships with interfaces, session management, and security primitives, while every authentication method lives in its own importable Go module. You compose exactly the auth stack your application needs without pulling in code/dependencies you don't use.

Out of the box, Limen provides:

  • Credential/password authentication
  • OAuth 2.0
  • Two-factor authentication
  • Session management
  • Optional cache-backed sessions and rate limiting
  • CLI schema export and migration generation
  • ...and more

Bring your own database, bring your own framework — Limen adapts to your stack, not the other way around.

Documentation

Full guides, configuration reference, and plugin documentation are available at ragokan.github.io/limen/docs.

Requirements

  • Go 1.25+

Installation

go get github.com/ragokan/limen

Then add the adapter and plugins your application needs:

go get github.com/ragokan/limen/adapters/gorm
go get github.com/ragokan/limen/plugins/credential-password

Quick Start

package main

import (
	"log"
	"net/http"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"

	"github.com/ragokan/limen"
	gormadapter "github.com/ragokan/limen/adapters/gorm"
	credentialpassword "github.com/ragokan/limen/plugins/credential-password"
)

func main() {
	db, err := gorm.Open(postgres.Open("your-dsn"), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	auth, err := limen.New(&limen.Config{
		BaseURL:  "http://localhost:8080",
		Database: gormadapter.New(db),
		Secret:   []byte("your-32-byte-secret-key-here!!!!"),
		HTTP: limen.NewDefaultHTTPConfig(
			limen.WithHTTPBasePath("/api/auth"),
		),
		Plugins: []limen.Plugin{
			credentialpassword.New(),
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.Handle("/api/auth/", auth.Handler())

	log.Println("listening on :8080")
	log.Fatal(http.ListenAndServe(":8080", mux))
}

Alternatively, set the LIMEN_SECRET environment variable and omit the Secret from the struct.

For a more complete example with OAuth providers, two-factor auth, and Gin integration, see the examples.

For full configuration options, usage, and plugin APIs, visit ragokan.github.io/limen/docs.

Development

This repository is a Go workspace. The checked-in go.work file makes root, adapter, plugin, CLI, and example modules resolve to the current branch.

Run all non-example module tests:

./scripts/test-modules.sh

Run every module outside go.work, including examples:

./scripts/test-standalone-modules.sh --all --local-replace

Run without --local-replace only after release tags are published.

Run benchmark suites and PostgreSQL 18 integration tests:

./scripts/run-benchmarks.sh
./scripts/test-postgres18.sh

PostgreSQL cleanup:

auth, err := limen.New(&limen.Config{
	Database: db,
	Secret:   secret,
	Cleanup:  limen.NewDefaultCleanupConfig(limen.WithCleanupOnInit(true)),
})
err := auth.CleanupExpired(ctx)

Provider behavior, verified-email rules, and Instagram support status are documented in OAuth Providers. PostgreSQL TTL and cleanup details are documented in PostgreSQL Cleanup And TTL. Benchmarking is documented in Benchmarking. OpenAPI and Huma integration are documented in OpenAPI And Huma. API keys are documented in API Keys. Admin APIs are documented in Admin Plugin. Organizations and RBAC are documented in Organizations And RBAC. Account and session management are documented in Accounts And Sessions. Longer-term passkey, SSO, and SCIM sequencing is documented in Protocol Roadmap. Production deployment guidance is documented in Production Setup. Release/versioning rules are documented in Releasing.

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

Security

Found a security issue? Please do not open a public issue. Email security@limenauth.dev instead. See SECURITY.md for full details on our disclosure process.

License

MIT License — see LICENSE for details.

Documentation

Overview

Package limen is the main package for the Limen authentication library.

Index

Constants

View Source
const (
	OpenAPIAuthTag = "Auth"

	OpenAPIAuthUserSchema                         = "AuthUser"
	OpenAPIAuthSessionResponseSchema              = "AuthSessionResponse"
	OpenAPIAuthSessionListItemSchema              = "AuthSessionListItem"
	OpenAPIAuthSessionListResponseSchema          = "AuthSessionListResponse"
	OpenAPIAuthMessageResponseSchema              = "AuthMessageResponse"
	OpenAPIAuthTokensSchema                       = "AuthTokens"
	OpenAPIAuthErrorResponseSchema                = "AuthErrorResponse"
	OpenAPIAuthVerifyEmailRequestSchema           = "AuthVerifyEmailRequest"
	OpenAPIAuthRefreshRequestSchema               = "AuthRefreshRequest"
	OpenAPIAuthCredentialSignInRequestSchema      = "AuthCredentialSignInRequest"
	OpenAPIAuthCredentialSignUpRequestSchema      = "AuthCredentialSignUpRequest"
	OpenAPIAuthPasswordResetEmailRequestSchema    = "AuthPasswordResetEmailRequest"
	OpenAPIAuthPasswordResetRequestSchema         = "AuthPasswordResetRequest"
	OpenAPIAuthPasswordChangeRequestSchema        = "AuthPasswordChangeRequest"
	OpenAPIAuthPasswordSetRequestSchema           = "AuthPasswordSetRequest"
	OpenAPIAuthUsernameCheckRequestSchema         = "AuthUsernameCheckRequest"
	OpenAPIAuthUsernameAvailabilityResponseSchema = "AuthUsernameAvailabilityResponse"
)
View Source
const (
	TrustedProxyHeaderForwarded     = "Forwarded"
	TrustedProxyHeaderXForwardedFor = "X-Forwarded-For"
	TrustedProxyHeaderXRealIP       = "X-Real-IP"
)
View Source
const (
	EmailVerificationAction = "email_verification"
)

Verification Action Names

Variables

View Source
var (
	ErrDatabaseAdapterRequired = errors.New("database adapter is required")
	ErrPluginNotFound          = errors.New("plugin not found")
	ErrPluginAlreadyRegistered = errors.New("plugin already registered")
	ErrInvalidConfiguration    = errors.New("invalid configuration")
	ErrRecordNotFound          = NewLimenError("record not found", http.StatusNotFound, nil)
	ErrEmptyText               = errors.New("text is empty and cannot be encrypted or decrypted")
	ErrMissingConditions       = errors.New("missing query conditions")
	ErrInvalidCondition        = errors.New("invalid query condition")
	ErrEmptyConditionValues    = errors.New("empty query condition values")
)
View Source
var (
	ErrSessionNotFound = errors.New("session not found")
	ErrSessionExpired  = errors.New("session has expired")
	ErrSessionInvalid  = errors.New("session is invalid")
)

Session-specific errors

View Source
var (
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
	ErrRateLimitNotFound = errors.New("rate limit not found")
)

Rate limiting errors

View Source
var (
	ErrEmailAlreadyVerified          = NewLimenError("email already verified", http.StatusConflict, nil)
	ErrEmailVerificationTokenInvalid = NewLimenError("invalid or expired email verification token", http.StatusBadRequest, nil)
)

Email verification errors

View Source
var (
	ErrVerificationTokenInvalid = errors.New("verification token is invalid")
)

Verification errors

Functions

func BuildGroupClause

func BuildGroupClause(group []Where, buildCondition func(Where) (string, []any)) (clause string, args []any)

BuildGroupClause builds a single connector clause from a group of conditions. buildCondition is adapter-specific (e.g. column quoting, placeholder style). Returns combined clause and args; caller may wrap in parens when len(group) > 1 (e.g. for SQL).

func BuildWhereFromGroups

func BuildWhereFromGroups(groups [][]Where, buildGroup func([]Where) (string, []any)) (clause string, args []any)

BuildWhereFromGroups builds a full WHERE expression by joining group clauses with AND. buildGroup turns each group into (clause, args); empty clauses are skipped.

func DecryptXChaCha

func DecryptXChaCha(encoded string, secret, additionalData []byte) (string, error)

Decrypt decrypts the base64-encoded ciphertext using XChaCha20-Poly1305 with the provided key.

func EncryptXChaCha

func EncryptXChaCha(plaintext string, secret, additionalData []byte) (string, error)

Encrypt encrypts the plaintext using XChaCha20-Poly1305 with the provided key (32 bytes).

func ExtractCookieValue

func ExtractCookieValue(headers http.Header, cookieName string) string

ExtractCookieValue extracts the value of a cookie from the Set-Cookie headers. Returns empty string if the cookie is not found.

func GenerateRandomString

func GenerateRandomString(length int, charSetType ...CharSetType) string

func GenerateVerificationAction

func GenerateVerificationAction(action, identifier string) string

func GetFromMap

func GetFromMap[T any](m map[string]any, key string) T

func GetJSONBody

func GetJSONBody(req *http.Request) map[string]any

GetBody extracts the parsed JSON body from the request context

func GetParam

func GetParam(req *http.Request, name string) string

GetParam extracts a specific parameter from the request context

func GetParams

func GetParams(req *http.Request) map[string]string

GetParams extracts parameters from the request context

func GroupConditionsByConnector

func GroupConditionsByConnector(conditions []Where) [][]Where

GroupConditionsByConnector splits conditions into groups: each group is either a single condition (AND) or a run of conditions connected by a connector (AND or OR). Groups are AND'd in order. E.g. [A, B.Or(), C, D] → [[A], [B,C], [D]] meaning (A) AND (B OR C) AND (D). Adapters can use this to build WHERE clauses with consistent OR precedence.

func NewDefaultCleanupConfig added in v0.1.4

func NewDefaultCleanupConfig(opts ...CleanupConfigOption) *cleanupConfig

func NewDefaultEmailConfig

func NewDefaultEmailConfig(opts ...EmailConfigOption) *emailConfig

func NewDefaultEmailVerification

func NewDefaultEmailVerification(opts ...EmailVerificationConfigOption) *emailVerificationConfig

NewDefaultEmailVerification creates a default email verification config.

func NewDefaultHTTPConfig

func NewDefaultHTTPConfig(opts ...HTTPConfigOption) *httpConfig

func NewDefaultSessionConfig

func NewDefaultSessionConfig(opts ...SessionConfigOption) *sessionConfig

func NewTestLimen

func NewTestLimen(t *testing.T, plugins ...Plugin) (*Limen, *LimenCore)

NewTestLimen creates a fully-initialized *Limen backed by an in-memory adapter.

func ParseVerificationAction

func ParseVerificationAction(action string) (string, string)

func SerializeAll

func SerializeAll[T Model](schema Schema, models []T) []map[string]any

SerializeAll serializes a slice of models using the given schema's Serialize method.

func SerializeModel

func SerializeModel(schema Schema, model Model) map[string]any

SerializeModel serializes a model using its schema's Serialize method.

func TryUse

func TryUse[T any](a *Limen, name PluginName) (T, bool)

TryUse retrieves a registered plugin by name and returns it as type T. Returns the zero value of T and false if the plugin is not registered or does not implement T.

Use this when you want to handle missing plugins gracefully instead of panicking. If you want to ensure that the plugin is registered, use the Use() function instead.

For example, if you want to use the credential-password plugin, you can get the API interface like this:

credentialpasswordAPI, ok := limen.TryUse[credentialpassword.API](limen, limen.PluginCredentialPassword)
if !ok {
	return nil, fmt.Errorf("credential password plugin is not registered")
}
credentialpasswordAPI.SignInWithCredentialAndPassword(ctx, "user@example.com", "password")

func Use

func Use[T any](a *Limen, name PluginName) T

Use retrieves a registered plugin by name and returns it as type T. It panics if the plugin is not registered or does not implement T.

T should be gotten from the plugin's API interface. For example, if you want to use the credential-password plugin, you can get the API interface like this:

credentialpasswordAPI := credentialpassword.Use(limen)
credentialpasswordAPI.SignInWithCredentialAndPassword(ctx, "user@example.com", "password")

func ValidateJSON

func ValidateJSON(w http.ResponseWriter, r *http.Request, responder *Responder, validateFunc func(*Validator, map[string]any) *Validator) map[string]any

ValidateJSON decodes the JSON body of the request and validates it using the validateFunc. It returns the decoded data if the validation succeeds, otherwise it returns nil and an error is written to the response.

Types

type Account

type Account struct {
	ID                   any
	UserID               any
	Provider             string
	ProviderAccountID    string
	AccessToken          string
	RefreshToken         string
	AccessTokenExpiresAt *time.Time
	Scope                string
	IDToken              string
	CreatedAt            time.Time
	UpdatedAt            time.Time
	// contains filtered or unexported fields
}

func (*Account) Raw

func (a *Account) Raw() map[string]any

type AccountSchema

type AccountSchema struct {
	BaseSchema
}

func (*AccountSchema) FromStorage

func (s *AccountSchema) FromStorage(data map[string]any) Model

func (*AccountSchema) GetAccessTokenExpiresAtField

func (s *AccountSchema) GetAccessTokenExpiresAtField() string

func (*AccountSchema) GetAccessTokenField

func (s *AccountSchema) GetAccessTokenField() string

func (*AccountSchema) GetCreatedAtField

func (s *AccountSchema) GetCreatedAtField() string

func (*AccountSchema) GetIDTokenField

func (s *AccountSchema) GetIDTokenField() string

func (*AccountSchema) GetProviderAccountIDField

func (s *AccountSchema) GetProviderAccountIDField() string

func (*AccountSchema) GetProviderField

func (s *AccountSchema) GetProviderField() string

func (*AccountSchema) GetRefreshTokenField

func (s *AccountSchema) GetRefreshTokenField() string

func (*AccountSchema) GetScopeField

func (s *AccountSchema) GetScopeField() string

func (*AccountSchema) GetUpdatedAtField

func (s *AccountSchema) GetUpdatedAtField() string

func (*AccountSchema) GetUserIDField

func (s *AccountSchema) GetUserIDField() string

func (*AccountSchema) Introspect

func (s *AccountSchema) Introspect(config *SchemaConfig) SchemaIntrospector

func (*AccountSchema) Serialize

func (s *AccountSchema) Serialize(data Model) map[string]any

func (*AccountSchema) ToStorage

func (s *AccountSchema) ToStorage(data Model) map[string]any

type AdditionalFieldsContext

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

func (*AdditionalFieldsContext) GetBody

func (ctx *AdditionalFieldsContext) GetBody() map[string]any

func (*AdditionalFieldsContext) GetBodyValue

func (ctx *AdditionalFieldsContext) GetBodyValue(key string) any

func (*AdditionalFieldsContext) GetHeader

func (ctx *AdditionalFieldsContext) GetHeader(key string) string

func (*AdditionalFieldsContext) GetHeaders

func (ctx *AdditionalFieldsContext) GetHeaders() http.Header

func (*AdditionalFieldsContext) IsEmpty

func (ctx *AdditionalFieldsContext) IsEmpty(key string) bool

type AdditionalFieldsFunc

type AdditionalFieldsFunc func(ctx *AdditionalFieldsContext) (map[string]any, error)

type AuthenticationResult

type AuthenticationResult struct {
	User *User
}

AuthenticationResult represents the result of an authentication process.

type BaseSchema

type BaseSchema struct {

	// A function to serialize the model to a json object for returning to the client
	Serializer func(data Model) map[string]any
	// contains filtered or unexported fields
}

func (*BaseSchema) GetAdditionalFields

func (b *BaseSchema) GetAdditionalFields() AdditionalFieldsFunc

func (*BaseSchema) GetField

func (b *BaseSchema) GetField(name SchemaField) string

func (*BaseSchema) GetFieldResolver

func (b *BaseSchema) GetFieldResolver() *SchemaResolver

func (*BaseSchema) GetIDField

func (b *BaseSchema) GetIDField() string

func (*BaseSchema) GetSoftDeleteField

func (b *BaseSchema) GetSoftDeleteField() string

func (*BaseSchema) GetTableName

func (b *BaseSchema) GetTableName() SchemaTableName

func (*BaseSchema) Initialize

func (b *BaseSchema) Initialize(schemaInfo *SchemaInfo) error

func (*BaseSchema) Serialize

func (b *BaseSchema) Serialize(data Model) map[string]any

type CLIConfig

type CLIConfig struct {
	Enabled bool
}

CLIConfig contains configuration for CLI tool support When enabled, discovered schemas are serialized to a JSON file that the CLI can read directly

type CacheAdapter

type CacheAdapter interface {
	// Get retrieves the value associated with key.
	// Returns ErrRecordNotFound if the key does not exist or has expired.
	Get(ctx context.Context, key string) ([]byte, error)

	// Set stores value under key with the given TTL.
	// A TTL of 0 means the entry never expires.
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

	// Has reports whether key exists and has not expired.
	Has(ctx context.Context, key string) (bool, error)

	// Delete removes the entry for key. It is a no-op if key does not exist.
	Delete(ctx context.Context, key string) error
}

CacheAdapter is a key-value store with TTL support used by sessions, rate limiting, JWT blacklists, and other features that benefit from a shared cache backend.

The default implementation is MemoryCacheStore (in-process maps).

type CharSetType

type CharSetType int
const (
	CharSetAlphanumeric CharSetType = iota
	CharSetNumeric
)

type CleanupConfigOption added in v0.1.4

type CleanupConfigOption func(*cleanupConfig)

func WithCleanupOnInit added in v0.1.4

func WithCleanupOnInit(enabled bool) CleanupConfigOption

type ColumnDefinition

type ColumnDefinition struct {
	Name         string      // Actual database column name (respects custom field mappings)
	LogicalField SchemaField // Logical field identifier
	Type         ColumnType  // Column type
	IsNullable   bool        // Whether the field can be NULL
	IsPrimaryKey bool        // Whether this is a primary key
	DefaultValue string      // Default value (empty if none)
	Tags         map[string]string
}

ColumnDefinition represents a single field/column in a schema

type ColumnDefinitionOption

type ColumnDefinitionOption func(*ColumnDefinition)

func WithDefaultValue

func WithDefaultValue(defaultValue string) ColumnDefinitionOption

WithDefaultValue sets the default value for the field

func WithLogicalField

func WithLogicalField(logicalField SchemaField) ColumnDefinitionOption

WithLogicalField sets the logical field name (different from column name)

func WithNullable

func WithNullable(nullable bool) ColumnDefinitionOption

WithNullable sets whether the field can be NULL

func WithPrimaryKey

func WithPrimaryKey(pk bool) ColumnDefinitionOption

WithPrimaryKey sets whether this is a primary key

func WithTags

func WithTags(tags map[string]string) ColumnDefinitionOption

WithTags sets tags for the field (JSON, gorm, sql, etc.)

type ColumnType

type ColumnType string

ColumnType represents a Go type for a database column

const (
	// ColumnTypeUUID represents the uuid string type
	ColumnTypeUUID ColumnType = "uuid"
	// ColumnTypeString represents the string (VARCHAR(255)) type
	ColumnTypeString ColumnType = "string"
	// ColumnTypeText represents the text (TEXT) type
	ColumnTypeText ColumnType = "text"
	// ColumnTypeInt represents the int type
	ColumnTypeInt ColumnType = "int"
	// ColumnTypeInt32 represents the int32 type
	ColumnTypeInt32 ColumnType = "int32"
	// ColumnTypeInt64 represents the int64 type
	ColumnTypeInt64 ColumnType = "int64"
	// ColumnTypeBool represents the bool type
	ColumnTypeBool ColumnType = "bool"
	// ColumnTypeTime represents the time.Time type
	ColumnTypeTime ColumnType = "time.Time"
	// ColumnTypeAny represents the any type
	ColumnTypeAny ColumnType = "any"
	// ColumnTypeMapStringAny represents the map[string]any type
	ColumnTypeMapStringAny ColumnType = "map[string]any"
)

type Config

type Config struct {
	BaseURL        string
	Database       DatabaseAdapter
	CacheStore     CacheAdapter
	CacheKeyPrefix string
	Plugins        []Plugin
	Schema         *SchemaConfig
	Session        *sessionConfig
	Cleanup        *cleanupConfig
	HTTP           *httpConfig
	CLI            *CLIConfig
	Email          *emailConfig
	Secret         []byte
}

Config is the main configuration struct for the limen library

type Connector

type Connector string

Connector defines how conditions are joined

const (
	ConnectorAnd Connector = "AND"
	ConnectorOr  Connector = "OR"
)

type DatabaseActionHelper

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

DatabaseActionHelper provides common database operations for plugins.

func (*DatabaseActionHelper) CreateSession

func (h *DatabaseActionHelper) CreateSession(ctx context.Context, data *Session, additionalFields map[string]any) error

func (*DatabaseActionHelper) CreateUser

func (h *DatabaseActionHelper) CreateUser(ctx context.Context, data *User, additionalFields map[string]any) error

func (*DatabaseActionHelper) CreateVerification

func (h *DatabaseActionHelper) CreateVerification(ctx context.Context, action, identifier, token string, expiresIn time.Duration) (*Verification, error)

func (*DatabaseActionHelper) DeleteSessionByToken

func (h *DatabaseActionHelper) DeleteSessionByToken(ctx context.Context, sessionToken string) error

func (*DatabaseActionHelper) DeleteSessionByUserID

func (h *DatabaseActionHelper) DeleteSessionByUserID(ctx context.Context, userID any) error

func (*DatabaseActionHelper) DeleteVerification

func (h *DatabaseActionHelper) DeleteVerification(ctx context.Context, id any) error

func (*DatabaseActionHelper) DeleteVerificationToken

func (h *DatabaseActionHelper) DeleteVerificationToken(ctx context.Context, token string) error

func (*DatabaseActionHelper) FindAccountByProviderAndProviderID

func (h *DatabaseActionHelper) FindAccountByProviderAndProviderID(ctx context.Context, provider string, providerAccountID any) (*Account, error)

func (*DatabaseActionHelper) FindSessionByToken

func (h *DatabaseActionHelper) FindSessionByToken(ctx context.Context, sessionToken string) (*Session, error)

func (*DatabaseActionHelper) FindUser

func (h *DatabaseActionHelper) FindUser(ctx context.Context, conditions []Where) (*User, error)

func (*DatabaseActionHelper) FindUserByEmail

func (h *DatabaseActionHelper) FindUserByEmail(ctx context.Context, email string) (*User, error)

func (*DatabaseActionHelper) FindUserByID

func (h *DatabaseActionHelper) FindUserByID(ctx context.Context, id any) (*User, error)

func (*DatabaseActionHelper) FindValidVerificationByToken

func (h *DatabaseActionHelper) FindValidVerificationByToken(ctx context.Context, token string) (*Verification, error)

func (*DatabaseActionHelper) FindVerificationByAction

func (h *DatabaseActionHelper) FindVerificationByAction(ctx context.Context, action, identifier string) (*Verification, error)

func (*DatabaseActionHelper) ListSessionsByUserID

func (h *DatabaseActionHelper) ListSessionsByUserID(ctx context.Context, userID any) ([]Session, error)

func (*DatabaseActionHelper) UpdateSession

func (h *DatabaseActionHelper) UpdateSession(ctx context.Context, data *Session, conditions []Where) error

func (*DatabaseActionHelper) UpdateUser

func (h *DatabaseActionHelper) UpdateUser(ctx context.Context, updatedUser *User, conditions []Where) error

func (*DatabaseActionHelper) UpdateVerification

func (h *DatabaseActionHelper) UpdateVerification(ctx context.Context, updatedVerification *Verification, conditions []Where) error

func (*DatabaseActionHelper) VerifyVerificationToken

func (h *DatabaseActionHelper) VerifyVerificationToken(ctx context.Context, token, action, identifier string) error

VerifyVerificationToken verifies a verification token for a given action and identifier. Returns an error if the token is invalid or the action and identifier do not match.

Note: This function will delete the verification token after it is verified.

type DatabaseAdapter

type DatabaseAdapter interface {
	Create(ctx context.Context, tableName SchemaTableName, data map[string]any) error
	FindOne(ctx context.Context, tableName SchemaTableName, conditions []Where, orderBy []OrderBy) (map[string]any, error)
	FindMany(ctx context.Context, tableName SchemaTableName, conditions []Where, options *QueryOptions) ([]map[string]any, error)
	Update(ctx context.Context, tableName SchemaTableName, conditions []Where, updates map[string]any) (int64, error)
	Delete(ctx context.Context, tableName SchemaTableName, conditions []Where) error
	Exists(ctx context.Context, tableName SchemaTableName, conditions []Where) (bool, error)
	Count(ctx context.Context, tableName SchemaTableName, conditions []Where) (int64, error)
}

type DatabaseDefaultValue

type DatabaseDefaultValue string

DatabaseDefaultValue represents special default value constants that map to database-specific SQL

const (
	// DefaultValuePrefix prefix for special database default values e.g CURRENT_TIMESTAMP
	DatabaseDefaultValuePrefix = "@"
	// DatabaseDefaultValueNow represents a timestamp default that maps to CURRENT_TIMESTAMP
	DatabaseDefaultValueNow DatabaseDefaultValue = DatabaseDefaultValuePrefix + "now()"
	// DatabaseDefaultValueUUID represents a UUID generation default that maps to uuid_generate_v4() (PostgreSQL) or UUID() (MySQL)
	DatabaseDefaultValueUUID DatabaseDefaultValue = DatabaseDefaultValuePrefix + "uuid()"
)

type DatabaseTx

type DatabaseTx interface {
	DatabaseAdapter
	Commit() error
	Rollback() error
}

DatabaseTx represents a database transaction

type EmailConfigOption

type EmailConfigOption func(*emailConfig)

func WithEmailVerification

func WithEmailVerification(opts ...EmailVerificationConfigOption) EmailConfigOption

type EmailVerificationConfigOption

type EmailVerificationConfigOption func(*emailVerificationConfig)

func WithDisableEmailVerification

func WithDisableEmailVerification() EmailVerificationConfigOption

WithDisableEmailVerification disables email verification.

func WithEmailVerificationExpiration

func WithEmailVerificationExpiration(d time.Duration) EmailVerificationConfigOption

WithEmailVerificationExpiration sets the token expiration duration.

func WithEmailVerificationTokenGenerator

func WithEmailVerificationTokenGenerator(fn func(*User) (string, error)) EmailVerificationConfigOption

WithEmailVerificationTokenGenerator overrides the default random token generator (e.g. to produce TOTP codes or signed JWTs).

func WithSendEmailVerificationMail

func WithSendEmailVerificationMail(fn func(email string, token string)) EmailVerificationConfigOption

WithSendEmailVerificationMail sets the callback invoked to deliver the verification email.

type EnvelopeFields

type EnvelopeFields struct {
	Data    string
	Message string
}

type EnvelopeMode

type EnvelopeMode int
const (
	EnvelopeOff EnvelopeMode = iota
	EnvelopeWrapSuccess
	EnvelopeAlways
)

type Errors

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

func (*Errors) Add

func (e *Errors) Add(field, message string, formatErrorMessage bool)

func (*Errors) Error

func (e *Errors) Error() string

func (*Errors) GetErrors

func (e *Errors) GetErrors() []*ValidationError

func (*Errors) HasErrors

func (e *Errors) HasErrors() bool

type ForeignKeyAction

type ForeignKeyAction string

ForeignKeyAction represents a SQL foreign key action

const (
	// FKActionCascade represents CASCADE action
	FKActionCascade ForeignKeyAction = "CASCADE"
	// FKActionSetNull represents SET NULL action
	FKActionSetNull ForeignKeyAction = "SET NULL"
	// FKActionRestrict represents RESTRICT action
	FKActionRestrict ForeignKeyAction = "RESTRICT"
	// FKActionNoAction represents NO ACTION
	FKActionNoAction ForeignKeyAction = "NO ACTION"
	// FKActionSetDefault represents SET DEFAULT action
	FKActionSetDefault ForeignKeyAction = "SET DEFAULT"
)

type ForeignKeyDefinition

type ForeignKeyDefinition struct {
	Name             string           // Foreign key constraint name
	Column           SchemaField      // Local column name
	ReferencedSchema SchemaName       // Schema name of the referenced schema
	ReferencedField  SchemaField      // Logical field name of the referenced field
	OnDelete         ForeignKeyAction // ON DELETE action (use FKAction constants)
	OnUpdate         ForeignKeyAction // ON UPDATE action (use FKAction constants)
}

ForeignKeyDefinition represents a foreign key relationship During schema discovery, the referenced schema and field are resolved to the actual table name and column name.

type HTTPConfigOption

type HTTPConfigOption func(*httpConfig)

func WithHTTPBasePath

func WithHTTPBasePath(basePath string) HTTPConfigOption

func WithHTTPCSRFProtection

func WithHTTPCSRFProtection(csrfProtection bool) HTTPConfigOption

func WithHTTPCookieCrossDomainEnabled

func WithHTTPCookieCrossDomainEnabled() HTTPConfigOption

func WithHTTPCookieCrossSubdomainEnabled

func WithHTTPCookieCrossSubdomainEnabled(subdomain string) HTTPConfigOption

func WithHTTPCookieHTTPOnly

func WithHTTPCookieHTTPOnly(httpOnly bool) HTTPConfigOption

func WithHTTPCookiePartitioned

func WithHTTPCookiePartitioned(partitioned bool) HTTPConfigOption

func WithHTTPCookiePath

func WithHTTPCookiePath(path string) HTTPConfigOption

func WithHTTPCookieSameSite

func WithHTTPCookieSameSite(sameSite http.SameSite) HTTPConfigOption

func WithHTTPCookieSecure

func WithHTTPCookieSecure(secure bool) HTTPConfigOption

func WithHTTPDisabledPaths

func WithHTTPDisabledPaths(disabledPaths []string) HTTPConfigOption

WithHTTPDisabledPaths adds paths to be disabled by their ID or pattern

func WithHTTPHooks

func WithHTTPHooks(hooks *Hooks) HTTPConfigOption

func WithHTTPMaxBodyBytes added in v0.1.4

func WithHTTPMaxBodyBytes(maxBodyBytes int64) HTTPConfigOption

func WithHTTPMiddleware

func WithHTTPMiddleware(globalMW ...Middleware) HTTPConfigOption

func WithHTTPOpenAPI added in v0.1.6

func WithHTTPOpenAPI(path string, opts ...OpenAPIOption) HTTPConfigOption

func WithHTTPOriginCheck

func WithHTTPOriginCheck(originCheck bool) HTTPConfigOption

func WithHTTPOverrides

func WithHTTPOverrides(overrides map[string]*PluginHTTPOverride) HTTPConfigOption

func WithHTTPRateLimiter

func WithHTTPRateLimiter(opts ...RateLimiterOption) HTTPConfigOption

func WithHTTPResponseEnvelopeFields

func WithHTTPResponseEnvelopeFields(fields EnvelopeFields) HTTPConfigOption

func WithHTTPResponseEnvelopeMode

func WithHTTPResponseEnvelopeMode(mode EnvelopeMode) HTTPConfigOption

func WithHTTPSessionCookieName

func WithHTTPSessionCookieName(name string) HTTPConfigOption

WithHTTPSessionCookieName sets the name of the session cookie

func WithHTTPSessionTransformer

func WithHTTPSessionTransformer(transformer SessionTransformer) HTTPConfigOption

func WithHTTPTrustedOrigins

func WithHTTPTrustedOrigins(trustedOrigins []string) HTTPConfigOption

type HTTPMethod

type HTTPMethod string
const (
	MethodANY     HTTPMethod = "ANY"
	MethodGET     HTTPMethod = "GET"
	MethodPOST    HTTPMethod = "POST"
	MethodPUT     HTTPMethod = "PUT"
	MethodDELETE  HTTPMethod = "DELETE"
	MethodPATCH   HTTPMethod = "PATCH"
	MethodHEAD    HTTPMethod = "HEAD"
	MethodOPTIONS HTTPMethod = "OPTIONS"
)

type Hook

type Hook struct {
	// Run is the function to execute for the hook. It can return false to stop the request from continuing.
	Run HookFunc
	// PathMatcher is a function that returns whether the hook should run for the given context.
	PathMatcher PathMatcherFunc
}

Hook is a function that runs before or after a request and can optionally restrict which requests it runs for.

type HookContext

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

func (*HookContext) DeleteResponseHeader

func (hc *HookContext) DeleteResponseHeader(key string)

DeleteResponseHeader removes a header from the response entirely

func (*HookContext) GetAuthResult

func (hc *HookContext) GetAuthResult() *AuthenticationResult

GetAuthResult returns the AuthenticationResult stored during SessionResponse, if available

func (*HookContext) GetJSONBodyData

func (hc *HookContext) GetJSONBodyData() map[string]any

func (*HookContext) GetJSONBodyValue

func (hc *HookContext) GetJSONBodyValue(key string) any

func (*HookContext) GetResponse

func (hc *HookContext) GetResponse() *ResponseData

GetResponse returns the current response data if available, nil otherwise

func (*HookContext) Method

func (hc *HookContext) Method() string

func (*HookContext) ModifyResponse

func (hc *HookContext) ModifyResponse(status int, payload any)

ModifyResponse allows hooks to modify the response payload and status code

func (*HookContext) Path

func (hc *HookContext) Path() string

func (*HookContext) RemoveResponseCookie

func (hc *HookContext) RemoveResponseCookie(name string)

RemoveResponseCookie removes a specific cookie from the response headers, preventing it from being sent to the client. This is different from DeleteResponseCookie which sends a Set-Cookie header telling the browser to delete the cookie.

func (*HookContext) Request

func (hc *HookContext) Request() *http.Request

func (*HookContext) Response

func (hc *HookContext) Response() http.ResponseWriter

func (*HookContext) RouteID

func (hc *HookContext) RouteID() string

func (*HookContext) RoutePattern

func (hc *HookContext) RoutePattern() string

func (*HookContext) SetBody

func (hc *HookContext) SetBody(data map[string]any)

func (*HookContext) SetResponseCookie

func (hc *HookContext) SetResponseCookie(cookie *http.Cookie)

SetResponseCookie adds a cookie to the response

func (*HookContext) SetResponseHeader

func (hc *HookContext) SetResponseHeader(key, value string)

SetResponseHeader sets a response header

func (*HookContext) StatusCode

func (hc *HookContext) StatusCode() int

func (*HookContext) WriteErrorResponse

func (hc *HookContext) WriteErrorResponse(err error)

WriteErrorResponse writes an error response to the client and should only be used in a before hook when you want to return an error response immediately without waiting for the request to complete.

func (*HookContext) WriteJSONResponse

func (hc *HookContext) WriteJSONResponse(status int, payload any)

WriteResponse writes a response to the client and should only be used in a before hook when you want to return a response immediately without waiting for the request to complete.

type HookFunc

type HookFunc func(ctx *HookContext) bool

type Hooks

type Hooks struct {
	Before []*Hook
	After  []*Hook
}

Hooks is a container for optional before and after hooks to add to the router. Hooks in Before run in order before the request handler; hooks in After run in order after. Any before-hook returning false stops the chain and the request does not continue.

type IDGenerator

type IDGenerator interface {
	Generate(ctx context.Context) (any, error)
	GetColumnType() ColumnType
}

IDGenerator generates IDs for database records.

func NewUUIDv7IDGenerator added in v0.1.8

func NewUUIDv7IDGenerator() IDGenerator

NewUUIDv7IDGenerator returns an ID generator that creates UUIDv7 string IDs.

type IndexDefinition

type IndexDefinition struct {
	Name    string        // Index name
	Columns []SchemaField // Column names in the index
	Unique  bool          // Whether this is a unique index
}

IndexDefinition represents a database index

type Limen

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

func New

func New(config *Config) (*Limen, error)

func (*Limen) CleanupExpired added in v0.1.4

func (a *Limen) CleanupExpired(ctx context.Context) error

func (*Limen) GetSession

func (a *Limen) GetSession(req *http.Request) (*ValidatedSession, error)

func (*Limen) Handler

func (a *Limen) Handler() http.Handler

func (*Limen) ListSessions

func (a *Limen) ListSessions(ctx context.Context, userID any) ([]Session, error)

ListSessions returns all active sessions for the given user.

func (*Limen) OpenAPI added in v0.1.6

func (a *Limen) OpenAPI(opts ...OpenAPIOption) *OpenAPIDocument

func (*Limen) OpenAPIHandler added in v0.1.6

func (a *Limen) OpenAPIHandler(opts ...OpenAPIOption) http.Handler

func (*Limen) OpenAPIJSON added in v0.1.6

func (a *Limen) OpenAPIJSON(opts ...OpenAPIOption) ([]byte, error)

func (*Limen) RequestEmailVerification

func (a *Limen) RequestEmailVerification(ctx context.Context, user *User, shouldSendEmail bool) (*Verification, error)

RequestEmailVerification creates a verification token for the user and optionally sends the verification email. Returns ErrEmailAlreadyVerified when the address is already confirmed.

func (*Limen) RevokeAllSessions

func (a *Limen) RevokeAllSessions(ctx context.Context, userID any) error

RevokeAllSessions revokes every session belonging to the given user.

func (*Limen) RevokeSession

func (a *Limen) RevokeSession(ctx context.Context, token string) error

RevokeSession revokes a single session identified by its token.

func (*Limen) VerifyEmail

func (a *Limen) VerifyEmail(ctx context.Context, token string) error

VerifyEmail validates the token, marks the email as verified, and deletes the consumed token.

type LimenCore

type LimenCore struct {
	DBAction       *DatabaseActionHelper
	Schema         *SchemaConfig
	SessionManager SessionManager
	// contains filtered or unexported fields
}

func (*LimenCore) CacheKeyPrefix

func (c *LimenCore) CacheKeyPrefix() string

CacheKeyPrefix returns the prefix used for all cache keys (sessions, rate limits).

func (*LimenCore) CacheStore

func (c *LimenCore) CacheStore() CacheAdapter

CacheStore returns the global CacheAdapter instance. Plugins should use this as a fallback when no per-feature store is configured.

func (*LimenCore) CleanupExpired added in v0.1.4

func (core *LimenCore) CleanupExpired(ctx context.Context) error

func (*LimenCore) Cookies

func (c *LimenCore) Cookies() *cookieManager

Cookies returns the shared CookieManager that plugins should use for all cookie operations. The returned manager inherits security attributes from the central cookie configuration.

func (*LimenCore) Count

func (core *LimenCore) Count(ctx context.Context, schema Schema, conditions []Where) (int64, error)

func (*LimenCore) Create

func (core *LimenCore) Create(ctx context.Context, schema Schema, data Model, additionalFields map[string]any) error

func (*LimenCore) CreateEmailVerification

func (c *LimenCore) CreateEmailVerification(ctx context.Context, user *User) (*Verification, error)

CreateEmailVerification creates a new verification token for the user.

func (*LimenCore) CreateSession

CreateSession creates a session for the auth result. This should be called instead of SessionManager.CreateSession so that plugins can pass options (e.g. remember_me) via SessionCreateOption.

func (*LimenCore) Delete

func (core *LimenCore) Delete(ctx context.Context, schema Schema, conditions []Where) error

func (*LimenCore) EmailVerificationEnabled

func (c *LimenCore) EmailVerificationEnabled() bool

EmailVerificationEnabled reports whether email verification is enabled.

func (*LimenCore) Exists

func (core *LimenCore) Exists(ctx context.Context, schema Schema, conditions []Where) (bool, error)

func (*LimenCore) FindMany

func (core *LimenCore) FindMany(ctx context.Context, schema Schema, conditions []Where) ([]Model, error)

func (*LimenCore) FindOne

func (core *LimenCore) FindOne(ctx context.Context, schema Schema, conditions []Where, orderBy []OrderBy) (Model, error)

func (*LimenCore) GetBaseURL

func (c *LimenCore) GetBaseURL() string

func (*LimenCore) GetBaseURLWithPluginPath

func (c *LimenCore) GetBaseURLWithPluginPath(pluginName PluginName, pathToJoin string) string

func (*LimenCore) GetFullBaseURL

func (c *LimenCore) GetFullBaseURL() string

func (*LimenCore) GetPlugin

func (c *LimenCore) GetPlugin(name PluginName) (Plugin, bool)

GetPlugin retrieves a plugin by its name from the plugin registry. Returns the plugin and true if found, or nil and false if not found.

func (*LimenCore) RequestEmailVerification

func (c *LimenCore) RequestEmailVerification(ctx context.Context, user *User, shouldSendEmail bool) (*Verification, error)

RequestEmailVerification looks up the user by email, ensures the address is not already verified, creates a verification token and optionally sends the email.

func (*LimenCore) Secret

func (c *LimenCore) Secret() []byte

Secret returns the base signing secret. Plugins that do not configure their own secret can use this for encryption/signing.

func (*LimenCore) SendEmailVerificationMail

func (c *LimenCore) SendEmailVerificationMail(user *User, verification *Verification)

SendEmailVerificationMail dispatches the verification email when a callback is configured.

func (*LimenCore) Update

func (core *LimenCore) Update(ctx context.Context, schema Schema, updatedData Model, conditions []Where) error

func (*LimenCore) UpdateRaw

func (core *LimenCore) UpdateRaw(ctx context.Context, schema Schema, updatedData Model, conditions []Where, removeEmptyValues bool) error

func (*LimenCore) UpdateRawAffected added in v0.1.6

func (core *LimenCore) UpdateRawAffected(ctx context.Context, schema Schema, updatedData Model, conditions []Where, removeEmptyValues bool) (int64, error)

func (*LimenCore) VerifyEmail

func (c *LimenCore) VerifyEmail(ctx context.Context, token string) error

VerifyEmail validates the token, marks the user's email as verified, and deletes the consumed token

func (*LimenCore) WithTransaction

func (core *LimenCore) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error

WithTransaction executes fn within a database transaction. The transaction is automatically available in the context for all database operations within the callback. If the adapter doesn't support transactions, fn runs normally.

type LimenError

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

func NewLimenError

func NewLimenError(message string, status int, details any) *LimenError

func ToLimenError

func ToLimenError(err error) *LimenError

func (*LimenError) Details

func (e *LimenError) Details() any

func (*LimenError) Error

func (e *LimenError) Error() string

func (*LimenError) Status

func (e *LimenError) Status() int

type LimenHTTPCore

type LimenHTTPCore struct {
	Responder *Responder
	// contains filtered or unexported fields
}

func (*LimenHTTPCore) IsTrustedOrigin

func (httpCore *LimenHTTPCore) IsTrustedOrigin(urlStr string) bool

func (*LimenHTTPCore) MiddlewareRequireSession

func (httpCore *LimenHTTPCore) MiddlewareRequireSession() Middleware

MiddlewareRequireSession is a middleware that requires a session to be present in the request context.

When a session is present, it is added to the request context and can be accessed using the GetCurrentSessionFromCtx() function.

func (*LimenHTTPCore) SessionCookieName

func (httpCore *LimenHTTPCore) SessionCookieName() string

type LimitProvider

type LimitProvider func(req *http.Request) (maxRequests int, window time.Duration)

type MemoryCacheStore

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

MemoryCacheStore is the default in-process CacheAdapter implementation. It uses sync.RWMutex-protected maps with lazy expiry on read.

func NewMemoryCacheStore

func NewMemoryCacheStore() *MemoryCacheStore

func (*MemoryCacheStore) Delete

func (m *MemoryCacheStore) Delete(_ context.Context, key string) error

func (*MemoryCacheStore) Get

func (m *MemoryCacheStore) Get(_ context.Context, key string) ([]byte, error)

func (*MemoryCacheStore) Has

func (m *MemoryCacheStore) Has(_ context.Context, key string) (bool, error)

func (*MemoryCacheStore) Set

func (m *MemoryCacheStore) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

type Middleware

type Middleware func(http.Handler) http.Handler

type Model

type Model interface {
	// Raw returns the model raw data as returned from the database
	Raw() map[string]any
}

type OAuthAccountProfile

type OAuthAccountProfile struct {
	Provider             string
	ProviderAccountID    string
	AccessToken          string
	RefreshToken         string
	AccessTokenExpiresAt *time.Time
	Scope                string
	IDToken              string
	Email                string
	EmailVerified        bool
	Name                 string
	AvatarURL            string
	Raw                  map[string]any
}

OAuthAccountProfile holds the data returned by the provider after a successful OAuth authentication.

type OpenAPIComponents added in v0.1.6

type OpenAPIComponents struct {
	SecuritySchemes map[string]OpenAPISecurityScheme `json:"securitySchemes,omitempty"`
	Schemas         map[string]OpenAPISchema         `json:"schemas,omitempty"`
}

type OpenAPIConfig added in v0.1.6

type OpenAPIConfig struct {
	Title           string
	Version         string
	Description     string
	Servers         []OpenAPIServer
	SecuritySchemes map[string]OpenAPISecurityScheme
	Schemas         map[string]OpenAPISchema
}

type OpenAPIDocument added in v0.1.6

type OpenAPIDocument struct {
	OpenAPI    string                 `json:"openapi"`
	Info       OpenAPIInfo            `json:"info"`
	Servers    []OpenAPIServer        `json:"servers,omitempty"`
	Paths      map[string]OpenAPIPath `json:"paths"`
	Components OpenAPIComponents      `json:"components,omitempty"`
}

type OpenAPIInfo added in v0.1.6

type OpenAPIInfo struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

type OpenAPIMediaType added in v0.1.6

type OpenAPIMediaType struct {
	Schema  OpenAPISchema `json:"schema,omitempty"`
	Example any           `json:"example,omitempty"`
}

type OpenAPIOperation added in v0.1.6

type OpenAPIOperation struct {
	OperationID string                       `json:"operationId,omitempty"`
	Summary     string                       `json:"summary,omitempty"`
	Description string                       `json:"description,omitempty"`
	Tags        []string                     `json:"tags,omitempty"`
	Deprecated  bool                         `json:"deprecated,omitempty"`
	Parameters  []OpenAPIParameter           `json:"parameters,omitempty"`
	RequestBody *OpenAPIRequestBody          `json:"requestBody,omitempty"`
	Responses   map[string]OpenAPIResponse   `json:"responses"`
	Security    []OpenAPISecurityRequirement `json:"security,omitempty"`
}

type OpenAPIOption added in v0.1.6

type OpenAPIOption func(*OpenAPIConfig)

func WithOpenAPIDescription added in v0.1.6

func WithOpenAPIDescription(description string) OpenAPIOption

func WithOpenAPISchema added in v0.1.9

func WithOpenAPISchema(name string, schema OpenAPISchema) OpenAPIOption

func WithOpenAPISecurityScheme added in v0.1.6

func WithOpenAPISecurityScheme(name string, scheme OpenAPISecurityScheme) OpenAPIOption

func WithOpenAPIServers added in v0.1.6

func WithOpenAPIServers(servers ...OpenAPIServer) OpenAPIOption

func WithOpenAPITitle added in v0.1.6

func WithOpenAPITitle(title string) OpenAPIOption

func WithOpenAPIVersion added in v0.1.6

func WithOpenAPIVersion(version string) OpenAPIOption

type OpenAPIParameter added in v0.1.6

type OpenAPIParameter struct {
	Name        string        `json:"name"`
	In          string        `json:"in"`
	Description string        `json:"description,omitempty"`
	Required    bool          `json:"required,omitempty"`
	Schema      OpenAPISchema `json:"schema,omitempty"`
}

type OpenAPIPath added in v0.1.6

type OpenAPIPath map[string]OpenAPIOperation

type OpenAPIRequestBody added in v0.1.6

type OpenAPIRequestBody struct {
	Description string                      `json:"description,omitempty"`
	Required    bool                        `json:"required,omitempty"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
}

func OpenAPIJSONRequestBody added in v0.1.9

func OpenAPIJSONRequestBody(schema OpenAPISchema) *OpenAPIRequestBody

type OpenAPIResponse added in v0.1.6

type OpenAPIResponse struct {
	Description string                      `json:"description"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
}

func OpenAPIAuthErrorResponse added in v0.1.10

func OpenAPIAuthErrorResponse(description string) OpenAPIResponse

func OpenAPIJSONResponse added in v0.1.9

func OpenAPIJSONResponse(description string, schema OpenAPISchema) OpenAPIResponse

type OpenAPISchema added in v0.1.6

type OpenAPISchema map[string]any

func OpenAPIArraySchema added in v0.1.9

func OpenAPIArraySchema(items OpenAPISchema) OpenAPISchema

func OpenAPIBooleanSchema added in v0.1.9

func OpenAPIBooleanSchema() OpenAPISchema

func OpenAPIObjectSchema added in v0.1.6

func OpenAPIObjectSchema(properties map[string]OpenAPISchema, required ...string) OpenAPISchema

func OpenAPIRefSchema added in v0.1.9

func OpenAPIRefSchema(name string) OpenAPISchema

func OpenAPIStringSchema added in v0.1.6

func OpenAPIStringSchema() OpenAPISchema

type OpenAPISecurityRequirement added in v0.1.6

type OpenAPISecurityRequirement map[string][]string

type OpenAPISecurityScheme added in v0.1.6

type OpenAPISecurityScheme struct {
	Type         string `json:"type"`
	Description  string `json:"description,omitempty"`
	Name         string `json:"name,omitempty"`
	In           string `json:"in,omitempty"`
	Scheme       string `json:"scheme,omitempty"`
	BearerFormat string `json:"bearerFormat,omitempty"`
}

type OpenAPIServer added in v0.1.6

type OpenAPIServer struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

type Operator

type Operator string

Operator defines the comparison operation

const (
	OpEq         Operator = "eq"          // equals
	OpNe         Operator = "ne"          // not equals
	OpLt         Operator = "lt"          // less than
	OpLte        Operator = "lte"         // less than or equal
	OpGt         Operator = "gt"          // greater than
	OpGte        Operator = "gte"         // greater than or equal
	OpIn         Operator = "in"          // in array
	OpNotIn      Operator = "not_in"      // not in array
	OpContains   Operator = "contains"    // contains substring
	OpStartsWith Operator = "starts_with" // starts with
	OpEndsWith   Operator = "ends_with"   // ends with
	OpIsNull     Operator = "is_null"     // is null
	OpIsNotNull  Operator = "is_not_null" // is not null
)

type OrderBy

type OrderBy struct {
	Column    string
	Direction OrderByDirection
}

type OrderByDirection

type OrderByDirection string
const (
	OrderByAsc  OrderByDirection = "ASC"  // order by ascending i.e oldest at top
	OrderByDesc OrderByDirection = "DESC" // order by descending i.e newest at top
)

type PathMatcherFunc

type PathMatcherFunc func(ctx *HookContext) bool

type Plugin

type Plugin interface {
	// Unique identifier for the plugin.
	Name() PluginName
	// Initialize initializes the plugin.
	Initialize(core *LimenCore) error
	// PluginHTTPConfig returns the configuration for the plugin's HTTP surface.
	PluginHTTPConfig() PluginHTTPConfig
	// RegisterRoutes registers routes for the plugin.
	RegisterRoutes(httpCore *LimenHTTPCore, routeBuilder *RouteBuilder)
}

Plugin is the interface that all plugins must implement.

type PluginHTTPConfig

type PluginHTTPConfig struct {
	// The base path where the plugin's routes will be mounted.
	// This is relative to the Limen base path and can be overridden by the end user.
	BasePath string
	// Middleware to be applied to the plugin's routes.
	Middleware []Middleware
	// Hooks run before/after requests. PathMatcher, when set, restricts which paths trigger the hooks
	Hooks *Hooks
	// Specific rate limit rules to be applied to the plugin's routes.
	// These rules can be overridden by the end user.
	RateLimitRules []*RateLimitRule
}

PluginHTTPConfig is the configuration for the plugin's HTTP surface.

type PluginHTTPOverride

type PluginHTTPOverride struct {
	BasePath string
	// Middleware to be applied to the plugin's routes
	Middleware []Middleware
}

type PluginName

type PluginName string

PluginName represents the name of a plugin/plugin

const (
	PluginCredentialPassword PluginName = "credential-password" // #nosec G101 -- plugin id string, not a secret
	PluginTwoFactor          PluginName = "two-factor"
	PluginOAuth              PluginName = "oauth"
	PluginSessionJWT         PluginName = "session-jwt"
	PluginMagicLink          PluginName = "magic-link"
	PluginAPIKey             PluginName = "api-key"
	PluginAdmin              PluginName = "admin"
	PluginOrganization       PluginName = "organization"
)

Plugin Names

type PluginSchemaConfig

type PluginSchemaConfig struct {
	TableName SchemaTableName        //  override table name
	Fields    map[SchemaField]string // Map of logical field name -> actual column name
}

PluginSchemaConfig represents customization for a plugin schema

type PluginSchemaConfigOption

type PluginSchemaConfigOption func(*PluginSchemaConfig)

func WithPluginFieldName

func WithPluginFieldName(logicalField SchemaField, columnName string) PluginSchemaConfigOption

WithPluginFieldName sets a field name mapping for a plugin schema

func WithPluginTableName

func WithPluginTableName(tableName SchemaTableName) PluginSchemaConfigOption

WithPluginTableName sets the table name for a plugin schema

type QueryOptions

type QueryOptions struct {
	Limit   int
	Offset  int
	OrderBy []OrderBy
}

QueryOptions for additional query parameters

type RateLimit

type RateLimit struct {
	ID            any    `json:"id,omitempty"`
	Key           string `json:"key"`
	Count         int    `json:"count"`
	LastRequestAt int64  `json:"last_request_at"`
	// contains filtered or unexported fields
}

func (RateLimit) Raw

func (r RateLimit) Raw() map[string]any

func (*RateLimit) ResetCounter

func (r *RateLimit) ResetCounter()

func (*RateLimit) Touch

func (r *RateLimit) Touch()

type RateLimitRule

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

func NewRateLimitRule

func NewRateLimitRule(path string, maxRequests int, window time.Duration) *RateLimitRule

func NewRateLimitRuleDisabledForPath

func NewRateLimitRuleDisabledForPath(path string) *RateLimitRule

func NewRateLimitRuleWithLimitProvider

func NewRateLimitRuleWithLimitProvider(path string, limitProvider LimitProvider) *RateLimitRule

type RateLimitSchema

type RateLimitSchema struct {
	BaseSchema
}

func (*RateLimitSchema) FromStorage

func (r *RateLimitSchema) FromStorage(data map[string]any) Model

func (*RateLimitSchema) GetCountField

func (r *RateLimitSchema) GetCountField() string

func (*RateLimitSchema) GetIDField

func (r *RateLimitSchema) GetIDField() string

func (*RateLimitSchema) GetKeyField

func (r *RateLimitSchema) GetKeyField() string

func (*RateLimitSchema) GetLastRequestAtField

func (r *RateLimitSchema) GetLastRequestAtField() string

func (*RateLimitSchema) Introspect

func (r *RateLimitSchema) Introspect(config *SchemaConfig) SchemaIntrospector

func (*RateLimitSchema) ToStorage

func (r *RateLimitSchema) ToStorage(data Model) map[string]any

type RateLimiterConfig

type RateLimiterConfig struct {
	// Enabled: whether the rate limiter is enabled
	Enabled bool
	// MaxRequests: the maximum number of requests allowed within the window
	MaxRequests int
	// Window: the duration of the window
	Window time.Duration
	// Store: the type of store to use
	Store StoreType
	// CustomStore: a custom store to use
	CustomStore RateLimiterStore
	// KeyGenerator: a function to generate the key for the rate limiter
	KeyGenerator RequestExtractorFn
	// contains filtered or unexported fields
}

func NewDefaultRateLimiterConfig

func NewDefaultRateLimiterConfig(opts ...RateLimiterOption) *RateLimiterConfig

type RateLimiterOption

type RateLimiterOption func(*RateLimiterConfig)

func WithRateLimiterCustomRule

func WithRateLimiterCustomRule(path string, maxRequests int, window time.Duration) RateLimiterOption

WithRateLimiterCustomRule sets a custom rule to use for a specific path

func WithRateLimiterCustomRuleWithLimitProvider

func WithRateLimiterCustomRuleWithLimitProvider(path string, limitProvider LimitProvider) RateLimiterOption

WithRateLimiterCustomRuleWithLimitProvider sets a custom rule to use for a specific path with a limit provider this is useful when you need to dynamically determine the limit and window based on the request

func WithRateLimiterCustomStore

func WithRateLimiterCustomStore(store RateLimiterStore) RateLimiterOption

WithRateLimiterCustomStore sets a custom store to use

func WithRateLimiterDisableForPaths

func WithRateLimiterDisableForPaths(paths ...string) RateLimiterOption

WithRateLimiterDisableForPaths disables the rate limiter for specific paths

func WithRateLimiterEnabled

func WithRateLimiterEnabled(enabled bool) RateLimiterOption

WithRateLimiterEnabled sets whether the rate limiter is enabled

func WithRateLimiterKeyGenerator

func WithRateLimiterKeyGenerator(keyGenerator RequestExtractorFn) RateLimiterOption

WithRateLimiterKeyGenerator sets the function to generate the key for the rate limiter

func WithRateLimiterMaxRequests

func WithRateLimiterMaxRequests(maxRequests int) RateLimiterOption

WithRateLimiterMaxRequests sets the maximum number of requests allowed within the window default is 100

func WithRateLimiterStore

func WithRateLimiterStore(store StoreType) RateLimiterOption

WithRateLimiterStore sets the type of store to use. Default is StoreTypeCache.

func WithRateLimiterWindow

func WithRateLimiterWindow(window time.Duration) RateLimiterOption

WithRateLimiterWindow sets the duration of the window default is 1 minute

type RateLimiterStore

type RateLimiterStore interface {
	Get(ctx context.Context, key string) (*RateLimit, error)
	Set(ctx context.Context, key string, value *RateLimit, ttl time.Duration) error
}

RateLimiterStore defines the interface for rate-limit storage backends.

type RegisteredRoute added in v0.1.6

type RegisteredRoute struct {
	Method   HTTPMethod
	Pattern  string
	RouteID  RouteID
	Metadata *RouteMetadata
}

type RequestExtractorFn

type RequestExtractorFn func(request *http.Request) string

func NewTrustedProxyIPExtractor added in v0.1.6

func NewTrustedProxyIPExtractor(opts ...TrustedProxyIPExtractorOption) (RequestExtractorFn, error)

type Responder

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

func (Responder) AddHeader

func (rs Responder) AddHeader(w http.ResponseWriter, key, value string)

AddHeader adds a response header (allows multiple values for same key)

func (Responder) Error

func (rs Responder) Error(w http.ResponseWriter, r *http.Request, err error) error

func (Responder) JSON

func (rs Responder) JSON(w http.ResponseWriter, r *http.Request, status int, payload any) error

func (Responder) Redirect

func (rs Responder) Redirect(w http.ResponseWriter, r *http.Request, redirectURL string, status int)

Redirect sends a redirect response. When the response is deferred (after-hooks in use), the redirect is stored and sent after hooks run so the browser receives a proper 3xx.

func (Responder) RedirectWithSession

func (rs Responder) RedirectWithSession(w http.ResponseWriter, r *http.Request, redirectURL string, sessionResult *SessionResult)

RedirectWithSession sets the session cookie and redirects the client to redirectURL. Used by OAuth callbacks when redirect_uri is provided in the authorize request.

func (Responder) SessionResponse

func (rs Responder) SessionResponse(w http.ResponseWriter, r *http.Request, core *LimenCore, result *AuthenticationResult, sessionResult *SessionResult) error

func (Responder) SetHeader

func (rs Responder) SetHeader(w http.ResponseWriter, key, value string)

SetHeader sets a response header

type ResponseData

type ResponseData struct {
	StatusCode int
	Payload    any
	IsError    bool
	Headers    http.Header
}

ResponseData represents the response data that hooks can read and modify

type RouteBuilder

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

RouteBuilder provides a clean API for plugins to register routes.

func (*RouteBuilder) AddRoute

func (b *RouteBuilder) AddRoute(method HTTPMethod, path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

AddRoute adds a route to the router

func (*RouteBuilder) DELETE

func (b *RouteBuilder) DELETE(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

DELETE registers a DELETE route

func (*RouteBuilder) DELETEWithMetadata added in v0.1.6

func (b *RouteBuilder) DELETEWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) GET

func (b *RouteBuilder) GET(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

GET registers a GET route

func (*RouteBuilder) GETWithMetadata added in v0.1.6

func (b *RouteBuilder) GETWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) PATCH

func (b *RouteBuilder) PATCH(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

PATCH registers a PATCH route

func (*RouteBuilder) PATCHWithMetadata added in v0.1.6

func (b *RouteBuilder) PATCHWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) POST

func (b *RouteBuilder) POST(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

POST registers a POST route

func (*RouteBuilder) POSTWithMetadata added in v0.1.6

func (b *RouteBuilder) POSTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) PUT

func (b *RouteBuilder) PUT(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

PUT registers a PUT route

func (*RouteBuilder) PUTWithMetadata added in v0.1.6

func (b *RouteBuilder) PUTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) ProtectedDELETE

func (b *RouteBuilder) ProtectedDELETE(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

ProtectedDELETE registers a DELETE route with session requirement

func (*RouteBuilder) ProtectedDELETEWithMetadata added in v0.1.6

func (b *RouteBuilder) ProtectedDELETEWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) ProtectedGET

func (b *RouteBuilder) ProtectedGET(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

ProtectedGET registers a GET route with session requirement

func (*RouteBuilder) ProtectedGETWithMetadata added in v0.1.6

func (b *RouteBuilder) ProtectedGETWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) ProtectedPATCH

func (b *RouteBuilder) ProtectedPATCH(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

ProtectedPATCH registers a PATCH route with session requirement

func (*RouteBuilder) ProtectedPATCHWithMetadata added in v0.1.6

func (b *RouteBuilder) ProtectedPATCHWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) ProtectedPOST

func (b *RouteBuilder) ProtectedPOST(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

ProtectedPOST registers a POST route with session requirement

func (*RouteBuilder) ProtectedPOSTWithMetadata added in v0.1.6

func (b *RouteBuilder) ProtectedPOSTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

func (*RouteBuilder) ProtectedPUT

func (b *RouteBuilder) ProtectedPUT(path string, routeID RouteID, handler http.HandlerFunc, middleware ...Middleware)

ProtectedPUT registers a PUT route with session requirement

func (*RouteBuilder) ProtectedPUTWithMetadata added in v0.1.6

func (b *RouteBuilder) ProtectedPUTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, metadata *RouteMetadata, middleware ...Middleware)

type RouteID

type RouteID string

RouteID is a unique identifier for each route

type RouteMetadata

type RouteMetadata struct {
	AllowedContentTypes []string
	OperationID         string
	Summary             string
	Description         string
	Tags                []string
	AuthRequired        bool
	Deprecated          bool
	Parameters          []OpenAPIParameter
	RequestBody         *OpenAPIRequestBody
	Responses           map[int]OpenAPIResponse
	Security            []OpenAPISecurityRequirement
	// contains filtered or unexported fields
}

func NewRouteMetadata added in v0.1.6

func NewRouteMetadata(opts ...RouteMetadataOption) *RouteMetadata

type RouteMetadataOption added in v0.1.6

type RouteMetadataOption func(*RouteMetadata)

func WithRouteAllowedContentTypes added in v0.1.6

func WithRouteAllowedContentTypes(contentTypes ...string) RouteMetadataOption

func WithRouteAuthRequired added in v0.1.6

func WithRouteAuthRequired(required bool) RouteMetadataOption

func WithRouteDeprecated added in v0.1.6

func WithRouteDeprecated(deprecated bool) RouteMetadataOption

func WithRouteDescription added in v0.1.6

func WithRouteDescription(description string) RouteMetadataOption

func WithRouteOperationID added in v0.1.6

func WithRouteOperationID(operationID string) RouteMetadataOption

func WithRouteParameters added in v0.1.6

func WithRouteParameters(parameters ...OpenAPIParameter) RouteMetadataOption

func WithRouteRequestBody added in v0.1.6

func WithRouteRequestBody(body *OpenAPIRequestBody) RouteMetadataOption

func WithRouteResponse added in v0.1.6

func WithRouteResponse(status int, response OpenAPIResponse) RouteMetadataOption

func WithRouteSecurity added in v0.1.6

func WithRouteSecurity(security ...OpenAPISecurityRequirement) RouteMetadataOption

func WithRouteSummary added in v0.1.6

func WithRouteSummary(summary string) RouteMetadataOption

func WithRouteTags added in v0.1.6

func WithRouteTags(tags ...string) RouteMetadataOption

type Schema

type Schema interface {
	GetTableName() SchemaTableName
	GetField(name SchemaField) string
	ToStorage(data Model) map[string]any
	FromStorage(data map[string]any) Model
	Serialize(data Model) map[string]any
	GetSoftDeleteField() string
	GetAdditionalFields() AdditionalFieldsFunc
	GetIDField() string
	Initialize(schemaInfo *SchemaInfo) error
}

type SchemaConfig

type SchemaConfig struct {
	// A function to return a map of global fields to be added to all schemas when creating a record. e.g:
	//  func(ctx context.Context) map[string]any {
	// 		return map[string]any{
	//  		"uuid": uuid.New().String(),
	//  		"created_at": time.Now(),
	//  		"updated_at": time.Now(),
	// 		 }
	//	 }
	// this function will be called during the creation of any schema record.
	// You can also set fields on supported schemas itself.
	AdditionalFields AdditionalFieldsFunc
	// IDGenerator generates IDs for all schemas
	IDGenerator IDGenerator
	// Account schema configuration
	Account *AccountSchema
	// User schema configuration
	User *UserSchema
	// Verification schema configuration
	Verification *VerificationSchema
	// Session schema configuration
	Session *SessionSchema
	// Rate limit schema configuration
	RateLimit *RateLimitSchema
	// contains filtered or unexported fields
}

func NewDefaultSchemaConfig

func NewDefaultSchemaConfig(opts ...SchemaConfigOption) *SchemaConfig

NewDefaultSchemaConfig creates a new SchemaConfig with default values.

func (*SchemaConfig) GetIDColumnType

func (c *SchemaConfig) GetIDColumnType() ColumnType

GetIDColumnType returns the ColumnType for ID fields based on the configured ID generator Returns ColumnTypeInt64 (for auto-increment) if no generator is configured

type SchemaConfigAccountOption

type SchemaConfigAccountOption func(*SchemaConfig, *AccountSchema)

func WithAccountSerializer

func WithAccountSerializer(serializer func(data *Account) map[string]any) SchemaConfigAccountOption

WithAccountSerializer overrides the default account response serializer.

func WithAccountTableName

func WithAccountTableName(tableName SchemaTableName) SchemaConfigAccountOption

type SchemaConfigOption

type SchemaConfigOption func(*SchemaConfig)

func WithPluginSchema

func WithPluginSchema(pluginName PluginName, schemaName SchemaName, opts ...PluginSchemaConfigOption) SchemaConfigOption

WithPluginSchema sets the configuration for a plugin schema

func WithSchemaAccount

func WithSchemaAccount(opts ...SchemaConfigAccountOption) SchemaConfigOption

WithSchemaAccount sets the account schema configuration

func WithSchemaAdditionalFields

func WithSchemaAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigOption

WithSchemaAdditionalFields sets the global additional fields function

func WithSchemaIDGenerator

func WithSchemaIDGenerator(generator IDGenerator) SchemaConfigOption

WithSchemaIDGenerator sets the global ID generator

func WithSchemaRateLimit

func WithSchemaRateLimit(opts ...SchemaConfigRateLimitOption) SchemaConfigOption

WithSchemaRateLimit sets the rate limit schema configuration

func WithSchemaSession

func WithSchemaSession(opts ...SchemaConfigSessionOption) SchemaConfigOption

WithSchemaSession sets the session schema configuration

func WithSchemaUUIDv7IDs added in v0.1.8

func WithSchemaUUIDv7IDs() SchemaConfigOption

WithSchemaUUIDv7IDs configures all schema ID fields to use app-generated UUIDv7 IDs.

func WithSchemaUser

func WithSchemaUser(opts ...SchemaConfigUserOption) SchemaConfigOption

WithSchemaUser sets the user schema configuration

func WithSchemaVerification

func WithSchemaVerification(opts ...SchemaConfigVerificationOption) SchemaConfigOption

WithSchemaVerification sets the verification schema configuration

type SchemaConfigRateLimitOption

type SchemaConfigRateLimitOption func(*SchemaConfig, *RateLimitSchema)

func WithRateLimitFieldCount

func WithRateLimitFieldCount(fieldName string) SchemaConfigRateLimitOption

func WithRateLimitFieldID

func WithRateLimitFieldID(fieldName string) SchemaConfigRateLimitOption

func WithRateLimitFieldKey

func WithRateLimitFieldKey(fieldName string) SchemaConfigRateLimitOption

func WithRateLimitFieldLastRequestAt

func WithRateLimitFieldLastRequestAt(fieldName string) SchemaConfigRateLimitOption

func WithRateLimitTableName

func WithRateLimitTableName(tableName SchemaTableName) SchemaConfigRateLimitOption

type SchemaConfigSessionOption

type SchemaConfigSessionOption func(*SchemaConfig, *SessionSchema)

func WithSessionFieldCreatedAt

func WithSessionFieldCreatedAt(fieldName string) SchemaConfigSessionOption

func WithSessionFieldExpiresAt

func WithSessionFieldExpiresAt(fieldName string) SchemaConfigSessionOption

func WithSessionFieldID

func WithSessionFieldID(fieldName string) SchemaConfigSessionOption

func WithSessionFieldLastAccess

func WithSessionFieldLastAccess(fieldName string) SchemaConfigSessionOption

func WithSessionFieldMetadata

func WithSessionFieldMetadata(fieldName string) SchemaConfigSessionOption

func WithSessionFieldToken

func WithSessionFieldToken(fieldName string) SchemaConfigSessionOption

func WithSessionFieldUserID

func WithSessionFieldUserID(fieldName string) SchemaConfigSessionOption

func WithSessionTableName

func WithSessionTableName(tableName SchemaTableName) SchemaConfigSessionOption

type SchemaConfigUserOption

type SchemaConfigUserOption func(*SchemaConfig, *UserSchema)

func WithUserFieldCreatedAt

func WithUserFieldCreatedAt(fieldName string) SchemaConfigUserOption

func WithUserFieldEmail

func WithUserFieldEmail(fieldName string) SchemaConfigUserOption

func WithUserFieldEmailVerifiedAt

func WithUserFieldEmailVerifiedAt(fieldName string) SchemaConfigUserOption

func WithUserFieldID

func WithUserFieldID(fieldName string) SchemaConfigUserOption

func WithUserFieldPassword

func WithUserFieldPassword(fieldName string) SchemaConfigUserOption

func WithUserFieldSoftDelete

func WithUserFieldSoftDelete(fieldName string) SchemaConfigUserOption

func WithUserFieldUpdatedAt

func WithUserFieldUpdatedAt(fieldName string) SchemaConfigUserOption

func WithUserFirstNameField

func WithUserFirstNameField(fieldName string) SchemaConfigUserOption

func WithUserIncludeNameFields

func WithUserIncludeNameFields(include bool) SchemaConfigUserOption

func WithUserLastNameField

func WithUserLastNameField(fieldName string) SchemaConfigUserOption

func WithUserSerializer

func WithUserSerializer(serializer func(data *User) map[string]any) SchemaConfigUserOption

WithUserSerializer overrides the default user response serializer.

func WithUserTableName

func WithUserTableName(tableName SchemaTableName) SchemaConfigUserOption

type SchemaConfigVerificationOption

type SchemaConfigVerificationOption func(*SchemaConfig, *VerificationSchema)

func WithVerificationFieldCreatedAt

func WithVerificationFieldCreatedAt(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldExpiresAt

func WithVerificationFieldExpiresAt(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldID

func WithVerificationFieldID(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldSoftDelete

func WithVerificationFieldSoftDelete(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldSubject

func WithVerificationFieldSubject(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldUpdatedAt

func WithVerificationFieldUpdatedAt(fieldName string) SchemaConfigVerificationOption

func WithVerificationFieldValue

func WithVerificationFieldValue(fieldName string) SchemaConfigVerificationOption

func WithVerificationTableName

func WithVerificationTableName(tableName SchemaTableName) SchemaConfigVerificationOption

type SchemaDefinition

type SchemaDefinition struct {
	TableName   SchemaTableName
	Columns     []ColumnDefinition
	Indexes     []IndexDefinition
	ForeignKeys []ForeignKeyDefinition
	SchemaName  SchemaName // Name of the schema
	Extends     SchemaName // If extending a core schema (e.g., CoreSchemaUsers), nil for new tables
	PluginName  string     // Name of the plugin that owns this schema, empty for core schemas
	Schema      Schema     `json:"-"` // Schema instance (excluded from JSON serialization for CLI)
}

SchemaDefinition represents a complete schema definition.

func NewSchemaDefinitionForExtension

func NewSchemaDefinitionForExtension(schemaName SchemaName, modifiedSchema Schema, opts ...SchemaDefinitionOption) *SchemaDefinition

NewSchemaDefinitionForExtension creates a new SchemaDefinition for extending a core schema

func NewSchemaDefinitionForTable

func NewSchemaDefinitionForTable(schemaName SchemaName, tableName SchemaTableName, schema Schema, opts ...SchemaDefinitionOption) *SchemaDefinition

NewSchemaDefinitionForTable creates a new SchemaDefinition for a new table

func (*SchemaDefinition) GetColumns

func (d *SchemaDefinition) GetColumns() []ColumnDefinition

func (*SchemaDefinition) GetExtends

func (d *SchemaDefinition) GetExtends() SchemaName

func (*SchemaDefinition) GetForeignKeys

func (d *SchemaDefinition) GetForeignKeys() []ForeignKeyDefinition

func (*SchemaDefinition) GetIndexes

func (d *SchemaDefinition) GetIndexes() []IndexDefinition

func (*SchemaDefinition) GetSchema

func (d *SchemaDefinition) GetSchema() Schema

func (*SchemaDefinition) GetSchemaName

func (d *SchemaDefinition) GetSchemaName() SchemaName

func (*SchemaDefinition) GetTableName

func (d *SchemaDefinition) GetTableName() SchemaTableName

For extensions, it uses the SchemaName as a temporary table name. The actual table name will be resolved during schema discovery from the core schema.

type SchemaDefinitionMap

type SchemaDefinitionMap map[SchemaName]SchemaDefinition

type SchemaDefinitionOption

type SchemaDefinitionOption func(*SchemaDefinition)

func WithSchemaField

func WithSchemaField(name string, columnType ColumnType, opts ...ColumnDefinitionOption) SchemaDefinitionOption

WithSchemaField adds a field to the schema. If the logical field name is not provided, it will be set to the name parameter.

func WithSchemaForeignKey

func WithSchemaForeignKey(foreignKey ForeignKeyDefinition) SchemaDefinitionOption

WithSchemaForeignKey adds a foreign key to the schema

func WithSchemaIDField

func WithSchemaIDField(config *SchemaConfig) SchemaDefinitionOption

func WithSchemaIndex

func WithSchemaIndex(name string, columns []SchemaField) SchemaDefinitionOption

WithSchemaIndex adds an index to the schema

func WithSchemaUniqueIndex

func WithSchemaUniqueIndex(name string, columns []SchemaField) SchemaDefinitionOption

WithSchemaIndex adds an index to the schema

type SchemaField

type SchemaField string

SchemaField represents a logical field name in a schema

const (
	// Common schema fields
	SchemaIDField         SchemaField = "id"
	SchemaCreatedAtField  SchemaField = "created_at"
	SchemaUpdatedAtField  SchemaField = "updated_at"
	SchemaSoftDeleteField SchemaField = "deleted_at"

	// User schema fields
	UserSchemaFirstNameField       SchemaField = "first_name"
	UserSchemaLastNameField        SchemaField = "last_name"
	UserSchemaEmailField           SchemaField = "email"
	UserSchemaPasswordField        SchemaField = "password"
	UserSchemaEmailVerifiedAtField SchemaField = "email_verified_at"

	// Verification schema fields
	VerificationSchemaSubjectField   SchemaField = "subject"
	VerificationSchemaValueField     SchemaField = "value"
	VerificationSchemaExpiresAtField SchemaField = "expires_at"

	// Session schema fields
	SessionSchemaUserIDField     SchemaField = "user_id"
	SessionSchemaTokenField      SchemaField = "token"
	SessionSchemaCreatedAtField  SchemaField = "created_at"
	SessionSchemaExpiresAtField  SchemaField = "expires_at"
	SessionSchemaLastAccessField SchemaField = "last_access"
	SessionSchemaMetadataField   SchemaField = "metadata"

	// Rate limit schema fields
	RateLimitSchemaKeyField           SchemaField = "key"
	RateLimitSchemaCountField         SchemaField = "count"
	RateLimitSchemaLastRequestAtField SchemaField = "last_request_at"

	// Account schema fields (OAuth)
	AccountSchemaUserIDField               SchemaField = "user_id"
	AccountSchemaProviderField             SchemaField = "provider"
	AccountSchemaProviderAccountIDField    SchemaField = "provider_account_id"
	AccountSchemaAccessTokenField          SchemaField = "access_token"
	AccountSchemaRefreshTokenField         SchemaField = "refresh_token"
	AccountSchemaAccessTokenExpiresAtField SchemaField = "access_token_expires_at"
	AccountSchemaScopeField                SchemaField = "scope"
	AccountSchemaIDTokenField              SchemaField = "id_token"
)

Schema Field Names

type SchemaInfo

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

SchemaInfo is a convenience struct that provides resolved schema information to schemas and wraps the SchemaResolver to make specific schema field lookups easier.

func (*SchemaInfo) GetField

func (m *SchemaInfo) GetField(logicalField SchemaField) string

GetField returns the resolved column name for a logical field.

type SchemaIntrospector

type SchemaIntrospector interface {
	// GetTableName returns the table name for this schema
	GetTableName() SchemaTableName
	// GetColumns returns all column definitions for this schema
	GetColumns() []ColumnDefinition
	// GetIndexes returns all index definitions for this schema
	GetIndexes() []IndexDefinition
	// GetForeignKeys returns all foreign key definitions for this schema
	GetForeignKeys() []ForeignKeyDefinition
	// GetExtends returns the name of the core schema this extends, or empty string if none
	GetExtends() SchemaName
	// GetSchemaName returns the name of the logical schema name
	GetSchemaName() SchemaName
	// GetSchema returns the schema instance
	GetSchema() Schema
}

SchemaIntrospector provides introspection capabilities for a schema

type SchemaName

type SchemaName string

SchemaName represents the logical name of a schema

const (
	// CoreSchemaUsers is the name of the users core schema
	CoreSchemaUsers SchemaName = "users"
	// CoreSchemaSessions is the name of the sessions core schema
	CoreSchemaSessions SchemaName = "sessions"
	// CoreSchemaVerifications is the name of the verifications core schema
	CoreSchemaVerifications SchemaName = "verifications"
	// CoreSchemaRateLimits is the name of the rate_limits core schema
	CoreSchemaRateLimits SchemaName = "rate_limits"
	// CoreSchemaAccounts is the name of the accounts core schema (OAuth linked accounts)
	CoreSchemaAccounts SchemaName = "accounts"
)

Core Schema Names

type SchemaProvider

type SchemaProvider interface {
	// GetSchemas returns all schemas provided by this plugin.
	// Returns a map of schema name to SchemaIntrospector.
	// Plugins can extend core schemas by setting Extends field, or create new tables.
	// If a plugin extends a core schema, it should return a schema with the same name
	// and set Extends to the core schema name (e.g., "users").
	GetSchemas(schema *SchemaConfig) []SchemaIntrospector
}

SchemaProvider is an optional interface that plugins can implement to contribute or modify database schemas.

type SchemaResolver

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

SchemaResolver resolves logical field names to concrete column names using the discovered schema map.

func (*SchemaResolver) GetField

func (r *SchemaResolver) GetField(schemaName SchemaName, logicalField SchemaField) string

GetField returns the concrete column name for a logical field within a schema.

func (*SchemaResolver) GetFields

func (r *SchemaResolver) GetFields(schemaName SchemaName) map[SchemaField]string

func (*SchemaResolver) GetTableName

func (r *SchemaResolver) GetTableName(schemaName SchemaName) SchemaTableName

type SchemaTableName

type SchemaTableName string

SchemaTableName represents the actual database table name

const (
	UserSchemaTableName         SchemaTableName = "users"
	VerificationSchemaTableName SchemaTableName = "verifications"
	SessionSchemaTableName      SchemaTableName = "sessions"
	RateLimitSchemaTableName    SchemaTableName = "rate_limits"
	AccountSchemaTableName      SchemaTableName = "accounts"
)

Schema Table Names

type Session

type Session struct {
	ID         any            `json:"id,omitempty"`
	Token      string         `json:"token"`
	UserID     any            `json:"user_id"`
	CreatedAt  time.Time      `json:"created_at"`
	ExpiresAt  time.Time      `json:"expires_at"`
	LastAccess time.Time      `json:"last_access"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

func (*Session) IsExpired

func (s *Session) IsExpired(idleTimeout time.Duration) bool

IsExpired checks if the session has expired

func (Session) Raw

func (s Session) Raw() map[string]any

Raw returns the session raw data as returned from the database

func (*Session) ShouldExtendExpiration

func (s *Session) ShouldExtendExpiration(expiresIn, updateAge time.Duration) bool

ShouldExtendExpiration checks if the session should be extended

type SessionConfigOption

type SessionConfigOption func(*sessionConfig)

func WithBearerEnabled

func WithBearerEnabled() SessionConfigOption

WithBearerEnabled enables Bearer token support for opaque sessions. When enabled, the session manager accepts Authorization: Bearer <token> in addition to cookies, and session responses include the token in Set-Auth-Token / Set-Refresh-Token headers. Use when the client or API does not support cookies or requires Bearer token authentication.

func WithCustomSessionStore

func WithCustomSessionStore(store SessionStore) SessionConfigOption

func WithSessionActivityCheckInterval

func WithSessionActivityCheckInterval(activityCheckInterval time.Duration) SessionConfigOption

func WithSessionDuration

func WithSessionDuration(duration time.Duration) SessionConfigOption

func WithSessionIPAddressExtractor

func WithSessionIPAddressExtractor(ipAddressExtractor func(request *http.Request) string) SessionConfigOption

func WithSessionIdleTimeout

func WithSessionIdleTimeout(idleTimeout time.Duration) SessionConfigOption

func WithSessionShortDuration

func WithSessionShortDuration(d time.Duration) SessionConfigOption

WithSessionShortDuration sets the short TTL for non-remembered sessions. Must be less than global session Duration. 0 = remember-me plugin disabled.

func WithSessionStoreType

func WithSessionStoreType(storeType StoreType) SessionConfigOption

func WithSessionUpdateAge

func WithSessionUpdateAge(updateAge time.Duration) SessionConfigOption

func WithSessionUserAgentExtractor

func WithSessionUserAgentExtractor(userAgentExtractor func(request *http.Request) string) SessionConfigOption

type SessionCreateOption

type SessionCreateOption func(*SessionCreateOptions)

func WithShortSession

func WithShortSession(shortSession bool) SessionCreateOption

WithShortSession sets the short session flag for the session.

type SessionCreateOptions

type SessionCreateOptions struct {
	ShortSession bool
}

type SessionManager

type SessionManager interface {
	CreateSession(ctx context.Context, r *http.Request, auth *AuthenticationResult, shortSession bool) (*SessionResult, error)
	ValidateSession(ctx context.Context, r *http.Request) (*ValidatedSession, error)
	RevokeSession(ctx context.Context, token string) error
	RevokeAllSessions(ctx context.Context, userID any) error
	ListSessions(ctx context.Context, userID any) ([]Session, error)
}

SessionManager defines the interface for session lifecycle management.

type SessionManagerProvider

type SessionManagerProvider interface {
	SessionManager() SessionManager
}

SessionManagerProvider is an optional interface that plugins can implement to provide an alternative SessionManager. The core detects this during initialization and wires the session manager automatically.

type SessionResult

type SessionResult struct {
	Token        string       `json:"token,omitzero"`
	RefreshToken string       `json:"refreshToken,omitzero"`
	Cookie       *http.Cookie `json:"-"`
	// ShortSession indicates if the session is a short session i.e expires in less than the global session duration
	// This is typically when "remember me" is not checked.
	ShortSession *bool
	// ExtraCookies holds additional cookies that session managers or plugins need to
	// deliver alongside the main session cookie (e.g. refresh tokens).
	ExtraCookies []*http.Cookie `json:"-"`
}

SessionResult contains token and delivery information for a session.

func SeedTestSession

func SeedTestSession(t *testing.T, l *Limen, userID any, email string) *SessionResult

SeedTestSession creates a session via the real SessionManager and returns the SessionResult. The user must already exist.

type SessionSchema

type SessionSchema struct {
	BaseSchema
}

func (*SessionSchema) FromStorage

func (s *SessionSchema) FromStorage(data map[string]any) Model

func (*SessionSchema) GetCreatedAtField

func (s *SessionSchema) GetCreatedAtField() string

func (*SessionSchema) GetExpiresAtField

func (s *SessionSchema) GetExpiresAtField() string

func (*SessionSchema) GetLastAccessField

func (s *SessionSchema) GetLastAccessField() string

func (*SessionSchema) GetMetadataField

func (s *SessionSchema) GetMetadataField() string

func (*SessionSchema) GetSoftDeleteField

func (s *SessionSchema) GetSoftDeleteField() string

func (*SessionSchema) GetTokenField

func (s *SessionSchema) GetTokenField() string

func (*SessionSchema) GetUserIDField

func (s *SessionSchema) GetUserIDField() string

func (*SessionSchema) Introspect

func (s *SessionSchema) Introspect(config *SchemaConfig) SchemaIntrospector

func (*SessionSchema) ToStorage

func (s *SessionSchema) ToStorage(data Model) map[string]any

type SessionStore

type SessionStore interface {
	Get(ctx context.Context, token string) (*Session, error)
	Set(ctx context.Context, session *Session) error
	Delete(ctx context.Context, token string) error
	DeleteByUserID(ctx context.Context, userID any) error
	ListByUserID(ctx context.Context, userID any) ([]Session, error)
}

SessionStore defines the interface for session storage backends.

type SessionTransformer

type SessionTransformer func(user map[string]any, sessionResult *SessionResult) (map[string]any, error)

SessionTransformer customizes the session response payload.

type StoreType

type StoreType string

StoreType selects the storage backend for features like sessions and rate limiting.

const (
	// StoreTypeDatabase stores data in the primary database via the DatabaseAdapter.
	StoreTypeDatabase StoreType = "database"
	// StoreTypeCache stores data in the shared CacheAdapter.
	StoreTypeCache StoreType = "cache_store"
)

type TransactionalAdapter

type TransactionalAdapter interface {
	BeginTx(ctx context.Context) (DatabaseTx, error)
}

TransactionalAdapter is implemented by adapters that support transactions

type TrustedProxyIPExtractorOption added in v0.1.6

type TrustedProxyIPExtractorOption func(*trustedProxyIPExtractorConfig)

func WithTrustedProxyCIDRs added in v0.1.6

func WithTrustedProxyCIDRs(cidrs ...string) TrustedProxyIPExtractorOption

func WithTrustedProxyHeaders added in v0.1.6

func WithTrustedProxyHeaders(headers ...string) TrustedProxyIPExtractorOption

func WithTrustedProxyIPv6Prefix added in v0.1.6

func WithTrustedProxyIPv6Prefix(bits int) TrustedProxyIPExtractorOption

type User

type User struct {
	ID              any        `json:"id"`
	Email           string     `json:"email"`
	Password        *string    `json:"-"`
	EmailVerifiedAt *time.Time `json:"email_verified_at"`
	// contains filtered or unexported fields
}

func SeedTestUser

func SeedTestUser(t *testing.T, l *Limen, email string) *User

SeedTestUser inserts a user directly into the in-memory DB and returns the full *User. The Limen instance must have been created with NewTestLimen.

func (User) Raw

func (u User) Raw() map[string]any

Raw returns the user raw data as returned from the database

func (User) TableName

func (c User) TableName() string

type UserSchema

type UserSchema struct {
	BaseSchema
	// contains filtered or unexported fields
}

func (*UserSchema) FromStorage

func (u *UserSchema) FromStorage(data map[string]any) Model

func (*UserSchema) GetEmailField

func (u *UserSchema) GetEmailField() string

func (*UserSchema) GetEmailVerifiedAtField

func (u *UserSchema) GetEmailVerifiedAtField() string

func (*UserSchema) GetPasswordField

func (u *UserSchema) GetPasswordField() string

func (*UserSchema) Introspect

func (u *UserSchema) Introspect(config *SchemaConfig) SchemaIntrospector

func (*UserSchema) Serialize

func (u *UserSchema) Serialize(data Model) map[string]any

func (*UserSchema) ToStorage

func (u *UserSchema) ToStorage(data Model) map[string]any

type ValidatedSession

type ValidatedSession struct {
	User      *User
	Session   *Session
	Refreshed *SessionResult // Set if session was extended during validation
}

ValidatedSession is the result of a session validation.

func GetCurrentSessionFromCtx

func GetCurrentSessionFromCtx(r *http.Request) (*ValidatedSession, error)

type ValidationError

type ValidationError struct {
	Field   string
	Message string
	// contains filtered or unexported fields
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Validator

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

func NewValidator

func NewValidator() *Validator

func (*Validator) Contains

func (v *Validator) Contains(field, value, substr string) *Validator

func (*Validator) ContainsAny

func (v *Validator) ContainsAny(field, value, chars string) *Validator

func (*Validator) Custom

func (v *Validator) Custom(field string, fn func() error, formatErrorMessage bool) *Validator

func (*Validator) Email

func (v *Validator) Email(field string, value any) *Validator

func (*Validator) In

func (v *Validator) In(field, value string, allowed []string) *Validator

func (*Validator) Length

func (v *Validator) Length(field, value string, length int) *Validator

func (*Validator) Matches

func (v *Validator) Matches(field, value, pattern string) *Validator

func (*Validator) MaxLength

func (v *Validator) MaxLength(field, value string, maxLen int) *Validator

func (*Validator) MinLength

func (v *Validator) MinLength(field, value string, minLen int) *Validator

func (*Validator) NotContains

func (v *Validator) NotContains(field, value, substr string) *Validator

func (*Validator) RequiredString

func (v *Validator) RequiredString(field string, value any) *Validator

func (*Validator) URL

func (v *Validator) URL(field, value string) *Validator

func (*Validator) Validate

func (v *Validator) Validate() error

type Verification

type Verification struct {
	ID        any
	Subject   string
	Value     string
	ExpiresAt time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
	// contains filtered or unexported fields
}

func (Verification) Raw

func (v Verification) Raw() map[string]any

type VerificationSchema

type VerificationSchema struct {
	BaseSchema
}

func (*VerificationSchema) FromStorage

func (v *VerificationSchema) FromStorage(data map[string]any) Model

func (*VerificationSchema) GetCreatedAtField

func (v *VerificationSchema) GetCreatedAtField() string

func (*VerificationSchema) GetExpiresAtField

func (v *VerificationSchema) GetExpiresAtField() string

func (*VerificationSchema) GetSubjectField

func (v *VerificationSchema) GetSubjectField() string

func (*VerificationSchema) GetUpdatedAtField

func (v *VerificationSchema) GetUpdatedAtField() string

func (*VerificationSchema) GetValueField

func (v *VerificationSchema) GetValueField() string

func (*VerificationSchema) Introspect

func (v *VerificationSchema) Introspect(config *SchemaConfig) SchemaIntrospector

func (*VerificationSchema) ToStorage

func (v *VerificationSchema) ToStorage(data Model) map[string]any

type Where

type Where struct {
	Column    string    `json:"column"`
	Operator  Operator  `json:"operator"`  // "eq" by default
	Value     any       `json:"value"`     // string | number | boolean | []string | []number | time.Time | nil
	Connector Connector `json:"connector"` // "AND" by default, "OR" for multiple conditions
}

Where represents a typed condition for database queries

func Contains

func Contains(column, value string) Where

Contains creates a contains substring condition

func EndsWith

func EndsWith(column, value string) Where

EndsWith creates an ends-with condition

func Eq

func Eq(column string, value any) Where

Eq creates an equality condition

func Gt

func Gt(column string, value any) Where

Gt creates a greater-than condition

func Gte

func Gte(column string, value any) Where

Gte creates a greater-than-or-equal condition

func In

func In(column string, values []any) Where

In creates an IN condition

func IsNotNull

func IsNotNull(column string) Where

IsNotNull creates an IS NOT NULL condition

func IsNull

func IsNull(column string) Where

IsNull creates an IS NULL condition

func Lt

func Lt(column string, value any) Where

Lt creates a less-than condition

func Lte

func Lte(column string, value any) Where

Lte creates a less-than-or-equal condition

func Ne

func Ne(column string, value any) Where

Ne creates a not-equals condition

func NotIn

func NotIn(column string, values []any) Where

NotIn creates a NOT IN condition

func StartsWith

func StartsWith(column, value string) Where

StartsWith creates a starts-with condition

func (Where) Or

func (w Where) Or() Where

Or modifier to change connector to OR

Directories

Path Synopsis
adapters
sql module
cmd
limen module
integrations
huma module
plugins
magic-link module
oauth module
oauth-apple module
oauth-discord module
oauth-generic module
oauth-github module
oauth-google module
oauth-spotify module
oauth-twitch module
oauth-twitter module
session-jwt module

Jump to

Keyboard shortcuts

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