Documentation
¶
Overview ¶
Package limen is the main package for the Limen authentication library.
Index ¶
- Constants
- Variables
- func BuildGroupClause(group []Where, buildCondition func(Where) (string, []any)) (clause string, args []any)
- func BuildWhereFromGroups(groups [][]Where, buildGroup func([]Where) (string, []any)) (clause string, args []any)
- func DecryptXChaCha(encoded string, secret, additionalData []byte) (string, error)
- func EncryptXChaCha(plaintext string, secret, additionalData []byte) (string, error)
- func ExtractCookieValue(headers http.Header, cookieName string) string
- func GenerateRandomString(length int, charSetType ...CharSetType) string
- func GenerateVerificationAction(action, identifier string) string
- func GetFromMap[T any](m map[string]any, key string) T
- func GetJSONBody(req *http.Request) map[string]any
- func GetParam(req *http.Request, name string) string
- func GetParams(req *http.Request) map[string]string
- func GroupConditionsByConnector(conditions []Where) [][]Where
- func NewDefaultCleanupConfig(opts ...CleanupConfigOption) *cleanupConfig
- func NewDefaultEmailConfig(opts ...EmailConfigOption) *emailConfig
- func NewDefaultEmailVerification(opts ...EmailVerificationConfigOption) *emailVerificationConfig
- func NewDefaultHTTPConfig(opts ...HTTPConfigOption) *httpConfig
- func NewDefaultSessionConfig(opts ...SessionConfigOption) *sessionConfig
- func NewTestLimen(t *testing.T, plugins ...Plugin) (*Limen, *LimenCore)
- func ParseVerificationAction(action string) (string, string)
- func SerializeAll[T Model](schema Schema, models []T) []map[string]any
- func SerializeModel(schema Schema, model Model) map[string]any
- func TryUse[T any](a *Limen, name PluginName) (T, bool)
- func Use[T any](a *Limen, name PluginName) T
- func ValidateJSON(w http.ResponseWriter, r *http.Request, responder *Responder, ...) map[string]any
- type Account
- type AccountSchema
- func (s *AccountSchema) FromStorage(data map[string]any) Model
- func (s *AccountSchema) GetAccessTokenExpiresAtField() string
- func (s *AccountSchema) GetAccessTokenField() string
- func (s *AccountSchema) GetCreatedAtField() string
- func (s *AccountSchema) GetIDTokenField() string
- func (s *AccountSchema) GetProviderAccountIDField() string
- func (s *AccountSchema) GetProviderField() string
- func (s *AccountSchema) GetRefreshTokenField() string
- func (s *AccountSchema) GetScopeField() string
- func (s *AccountSchema) GetUpdatedAtField() string
- func (s *AccountSchema) GetUserIDField() string
- func (s *AccountSchema) Introspect(config *SchemaConfig) SchemaIntrospector
- func (s *AccountSchema) Serialize(data Model) map[string]any
- func (s *AccountSchema) ToStorage(data Model) map[string]any
- type AdditionalFieldsContext
- func (ctx *AdditionalFieldsContext) GetBody() map[string]any
- func (ctx *AdditionalFieldsContext) GetBodyValue(key string) any
- func (ctx *AdditionalFieldsContext) GetHeader(key string) string
- func (ctx *AdditionalFieldsContext) GetHeaders() http.Header
- func (ctx *AdditionalFieldsContext) IsEmpty(key string) bool
- type AdditionalFieldsFunc
- type AuthenticationResult
- type BaseSchema
- func (b *BaseSchema) GetAdditionalFields() AdditionalFieldsFunc
- func (b *BaseSchema) GetField(name SchemaField) string
- func (b *BaseSchema) GetFieldResolver() *SchemaResolver
- func (b *BaseSchema) GetIDField() string
- func (b *BaseSchema) GetSoftDeleteField() string
- func (b *BaseSchema) GetTableName() SchemaTableName
- func (b *BaseSchema) Initialize(schemaInfo *SchemaInfo) error
- func (b *BaseSchema) Serialize(data Model) map[string]any
- type CLIConfig
- type CacheAdapter
- type CharSetType
- type CleanupConfigOption
- type ColumnDefinition
- type ColumnDefinitionOption
- func WithDefaultValue(defaultValue string) ColumnDefinitionOption
- func WithLogicalField(logicalField SchemaField) ColumnDefinitionOption
- func WithNullable(nullable bool) ColumnDefinitionOption
- func WithPrimaryKey(pk bool) ColumnDefinitionOption
- func WithTags(tags map[string]string) ColumnDefinitionOption
- type ColumnType
- type Config
- type Connector
- type DatabaseActionHelper
- func (h *DatabaseActionHelper) CreateSession(ctx context.Context, data *Session, additionalFields map[string]any) error
- func (h *DatabaseActionHelper) CreateUser(ctx context.Context, data *User, additionalFields map[string]any) error
- func (h *DatabaseActionHelper) CreateVerification(ctx context.Context, action, identifier, token string, expiresIn time.Duration) (*Verification, error)
- func (h *DatabaseActionHelper) DeleteSessionByToken(ctx context.Context, sessionToken string) error
- func (h *DatabaseActionHelper) DeleteSessionByUserID(ctx context.Context, userID any) error
- func (h *DatabaseActionHelper) DeleteVerification(ctx context.Context, id any) error
- func (h *DatabaseActionHelper) DeleteVerificationToken(ctx context.Context, token string) error
- func (h *DatabaseActionHelper) FindAccountByProviderAndProviderID(ctx context.Context, provider string, providerAccountID any) (*Account, error)
- func (h *DatabaseActionHelper) FindSessionByToken(ctx context.Context, sessionToken string) (*Session, error)
- func (h *DatabaseActionHelper) FindUser(ctx context.Context, conditions []Where) (*User, error)
- func (h *DatabaseActionHelper) FindUserByEmail(ctx context.Context, email string) (*User, error)
- func (h *DatabaseActionHelper) FindUserByID(ctx context.Context, id any) (*User, error)
- func (h *DatabaseActionHelper) FindValidVerificationByToken(ctx context.Context, token string) (*Verification, error)
- func (h *DatabaseActionHelper) FindVerificationByAction(ctx context.Context, action, identifier string) (*Verification, error)
- func (h *DatabaseActionHelper) ListSessionsByUserID(ctx context.Context, userID any) ([]Session, error)
- func (h *DatabaseActionHelper) UpdateSession(ctx context.Context, data *Session, conditions []Where) error
- func (h *DatabaseActionHelper) UpdateUser(ctx context.Context, updatedUser *User, conditions []Where) error
- func (h *DatabaseActionHelper) UpdateVerification(ctx context.Context, updatedVerification *Verification, conditions []Where) error
- func (h *DatabaseActionHelper) VerifyVerificationToken(ctx context.Context, token, action, identifier string) error
- type DatabaseAdapter
- type DatabaseDefaultValue
- type DatabaseTx
- type EmailConfigOption
- type EmailVerificationConfigOption
- func WithDisableEmailVerification() EmailVerificationConfigOption
- func WithEmailVerificationExpiration(d time.Duration) EmailVerificationConfigOption
- func WithEmailVerificationTokenGenerator(fn func(*User) (string, error)) EmailVerificationConfigOption
- func WithSendEmailVerificationMail(fn func(email string, token string)) EmailVerificationConfigOption
- type EnvelopeFields
- type EnvelopeMode
- type Errors
- type ForeignKeyAction
- type ForeignKeyDefinition
- type HTTPConfigOption
- func WithHTTPBasePath(basePath string) HTTPConfigOption
- func WithHTTPCSRFProtection(csrfProtection bool) HTTPConfigOption
- func WithHTTPCookieCrossDomainEnabled() HTTPConfigOption
- func WithHTTPCookieCrossSubdomainEnabled(subdomain string) HTTPConfigOption
- func WithHTTPCookieHTTPOnly(httpOnly bool) HTTPConfigOption
- func WithHTTPCookiePartitioned(partitioned bool) HTTPConfigOption
- func WithHTTPCookiePath(path string) HTTPConfigOption
- func WithHTTPCookieSameSite(sameSite http.SameSite) HTTPConfigOption
- func WithHTTPCookieSecure(secure bool) HTTPConfigOption
- func WithHTTPDisabledPaths(disabledPaths []string) HTTPConfigOption
- func WithHTTPHooks(hooks *Hooks) HTTPConfigOption
- func WithHTTPMaxBodyBytes(maxBodyBytes int64) HTTPConfigOption
- func WithHTTPMiddleware(globalMW ...Middleware) HTTPConfigOption
- func WithHTTPOpenAPI(path string, opts ...OpenAPIOption) HTTPConfigOption
- func WithHTTPOriginCheck(originCheck bool) HTTPConfigOption
- func WithHTTPOverrides(overrides map[string]*PluginHTTPOverride) HTTPConfigOption
- func WithHTTPRateLimiter(opts ...RateLimiterOption) HTTPConfigOption
- func WithHTTPResponseEnvelopeFields(fields EnvelopeFields) HTTPConfigOption
- func WithHTTPResponseEnvelopeMode(mode EnvelopeMode) HTTPConfigOption
- func WithHTTPSessionCookieName(name string) HTTPConfigOption
- func WithHTTPSessionTransformer(transformer SessionTransformer) HTTPConfigOption
- func WithHTTPTrustedOrigins(trustedOrigins []string) HTTPConfigOption
- type HTTPMethod
- type Hook
- type HookContext
- func (hc *HookContext) DeleteResponseHeader(key string)
- func (hc *HookContext) GetAuthResult() *AuthenticationResult
- func (hc *HookContext) GetJSONBodyData() map[string]any
- func (hc *HookContext) GetJSONBodyValue(key string) any
- func (hc *HookContext) GetResponse() *ResponseData
- func (hc *HookContext) Method() string
- func (hc *HookContext) ModifyResponse(status int, payload any)
- func (hc *HookContext) Path() string
- func (hc *HookContext) RemoveResponseCookie(name string)
- func (hc *HookContext) Request() *http.Request
- func (hc *HookContext) Response() http.ResponseWriter
- func (hc *HookContext) RouteID() string
- func (hc *HookContext) RoutePattern() string
- func (hc *HookContext) SetBody(data map[string]any)
- func (hc *HookContext) SetResponseCookie(cookie *http.Cookie)
- func (hc *HookContext) SetResponseHeader(key, value string)
- func (hc *HookContext) StatusCode() int
- func (hc *HookContext) WriteErrorResponse(err error)
- func (hc *HookContext) WriteJSONResponse(status int, payload any)
- type HookFunc
- type Hooks
- type IDGenerator
- type IndexDefinition
- type Limen
- func (a *Limen) CleanupExpired(ctx context.Context) error
- func (a *Limen) GetSession(req *http.Request) (*ValidatedSession, error)
- func (a *Limen) Handler() http.Handler
- func (a *Limen) ListSessions(ctx context.Context, userID any) ([]Session, error)
- func (a *Limen) OpenAPI(opts ...OpenAPIOption) *OpenAPIDocument
- func (a *Limen) OpenAPIHandler(opts ...OpenAPIOption) http.Handler
- func (a *Limen) OpenAPIJSON(opts ...OpenAPIOption) ([]byte, error)
- func (a *Limen) RequestEmailVerification(ctx context.Context, user *User, shouldSendEmail bool) (*Verification, error)
- func (a *Limen) RevokeAllSessions(ctx context.Context, userID any) error
- func (a *Limen) RevokeSession(ctx context.Context, token string) error
- func (a *Limen) VerifyEmail(ctx context.Context, token string) error
- type LimenCore
- func (c *LimenCore) CacheKeyPrefix() string
- func (c *LimenCore) CacheStore() CacheAdapter
- func (core *LimenCore) CleanupExpired(ctx context.Context) error
- func (c *LimenCore) Cookies() *cookieManager
- func (core *LimenCore) Count(ctx context.Context, schema Schema, conditions []Where) (int64, error)
- func (core *LimenCore) Create(ctx context.Context, schema Schema, data Model, ...) error
- func (c *LimenCore) CreateEmailVerification(ctx context.Context, user *User) (*Verification, error)
- func (c *LimenCore) CreateSession(ctx context.Context, r *http.Request, w http.ResponseWriter, ...) (*SessionResult, error)
- func (core *LimenCore) Delete(ctx context.Context, schema Schema, conditions []Where) error
- func (c *LimenCore) EmailVerificationEnabled() bool
- func (core *LimenCore) Exists(ctx context.Context, schema Schema, conditions []Where) (bool, error)
- func (core *LimenCore) FindMany(ctx context.Context, schema Schema, conditions []Where) ([]Model, error)
- func (core *LimenCore) FindOne(ctx context.Context, schema Schema, conditions []Where, orderBy []OrderBy) (Model, error)
- func (c *LimenCore) GetBaseURL() string
- func (c *LimenCore) GetBaseURLWithPluginPath(pluginName PluginName, pathToJoin string) string
- func (c *LimenCore) GetFullBaseURL() string
- func (c *LimenCore) GetPlugin(name PluginName) (Plugin, bool)
- func (c *LimenCore) RequestEmailVerification(ctx context.Context, user *User, shouldSendEmail bool) (*Verification, error)
- func (c *LimenCore) Secret() []byte
- func (c *LimenCore) SendEmailVerificationMail(user *User, verification *Verification)
- func (core *LimenCore) Update(ctx context.Context, schema Schema, updatedData Model, conditions []Where) error
- func (core *LimenCore) UpdateRaw(ctx context.Context, schema Schema, updatedData Model, conditions []Where, ...) error
- func (core *LimenCore) UpdateRawAffected(ctx context.Context, schema Schema, updatedData Model, conditions []Where, ...) (int64, error)
- func (c *LimenCore) VerifyEmail(ctx context.Context, token string) error
- func (core *LimenCore) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
- type LimenError
- type LimenHTTPCore
- type LimitProvider
- type MemoryCacheStore
- func (m *MemoryCacheStore) Delete(_ context.Context, key string) error
- func (m *MemoryCacheStore) Get(_ context.Context, key string) ([]byte, error)
- func (m *MemoryCacheStore) Has(_ context.Context, key string) (bool, error)
- func (m *MemoryCacheStore) Set(_ context.Context, key string, value []byte, ttl time.Duration) error
- type Middleware
- type Model
- type OAuthAccountProfile
- type OpenAPIComponents
- type OpenAPIConfig
- type OpenAPIDocument
- type OpenAPIInfo
- type OpenAPIMediaType
- type OpenAPIOperation
- type OpenAPIOption
- func WithOpenAPIDescription(description string) OpenAPIOption
- func WithOpenAPISchema(name string, schema OpenAPISchema) OpenAPIOption
- func WithOpenAPISecurityScheme(name string, scheme OpenAPISecurityScheme) OpenAPIOption
- func WithOpenAPIServers(servers ...OpenAPIServer) OpenAPIOption
- func WithOpenAPITitle(title string) OpenAPIOption
- func WithOpenAPIVersion(version string) OpenAPIOption
- type OpenAPIParameter
- type OpenAPIPath
- type OpenAPIRequestBody
- type OpenAPIResponse
- type OpenAPISchema
- type OpenAPISecurityRequirement
- type OpenAPISecurityScheme
- type OpenAPIServer
- type Operator
- type OrderBy
- type OrderByDirection
- type PathMatcherFunc
- type Plugin
- type PluginHTTPConfig
- type PluginHTTPOverride
- type PluginName
- type PluginSchemaConfig
- type PluginSchemaConfigOption
- type QueryOptions
- type RateLimit
- type RateLimitRule
- type RateLimitSchema
- func (r *RateLimitSchema) FromStorage(data map[string]any) Model
- func (r *RateLimitSchema) GetCountField() string
- func (r *RateLimitSchema) GetIDField() string
- func (r *RateLimitSchema) GetKeyField() string
- func (r *RateLimitSchema) GetLastRequestAtField() string
- func (r *RateLimitSchema) Introspect(config *SchemaConfig) SchemaIntrospector
- func (r *RateLimitSchema) ToStorage(data Model) map[string]any
- type RateLimiterConfig
- type RateLimiterOption
- func WithRateLimiterCustomRule(path string, maxRequests int, window time.Duration) RateLimiterOption
- func WithRateLimiterCustomRuleWithLimitProvider(path string, limitProvider LimitProvider) RateLimiterOption
- func WithRateLimiterCustomStore(store RateLimiterStore) RateLimiterOption
- func WithRateLimiterDisableForPaths(paths ...string) RateLimiterOption
- func WithRateLimiterEnabled(enabled bool) RateLimiterOption
- func WithRateLimiterKeyGenerator(keyGenerator RequestExtractorFn) RateLimiterOption
- func WithRateLimiterMaxRequests(maxRequests int) RateLimiterOption
- func WithRateLimiterStore(store StoreType) RateLimiterOption
- func WithRateLimiterWindow(window time.Duration) RateLimiterOption
- type RateLimiterStore
- type RegisteredRoute
- type RequestExtractorFn
- type Responder
- func (rs Responder) AddHeader(w http.ResponseWriter, key, value string)
- func (rs Responder) Error(w http.ResponseWriter, r *http.Request, err error) error
- func (rs Responder) JSON(w http.ResponseWriter, r *http.Request, status int, payload any) error
- func (rs Responder) Redirect(w http.ResponseWriter, r *http.Request, redirectURL string, status int)
- func (rs Responder) RedirectWithSession(w http.ResponseWriter, r *http.Request, redirectURL string, ...)
- func (rs Responder) SessionResponse(w http.ResponseWriter, r *http.Request, core *LimenCore, ...) error
- func (rs Responder) SetHeader(w http.ResponseWriter, key, value string)
- type ResponseData
- type RouteBuilder
- func (b *RouteBuilder) AddRoute(method HTTPMethod, path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) DELETE(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) DELETEWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) GET(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) GETWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) PATCH(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) PATCHWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) POST(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) POSTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) PUT(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) PUTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedDELETE(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedDELETEWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedGET(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedGETWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPATCH(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPATCHWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPOST(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPOSTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPUT(path string, routeID RouteID, handler http.HandlerFunc, ...)
- func (b *RouteBuilder) ProtectedPUTWithMetadata(path string, routeID RouteID, handler http.HandlerFunc, ...)
- type RouteID
- type RouteMetadata
- type RouteMetadataOption
- func WithRouteAllowedContentTypes(contentTypes ...string) RouteMetadataOption
- func WithRouteAuthRequired(required bool) RouteMetadataOption
- func WithRouteDeprecated(deprecated bool) RouteMetadataOption
- func WithRouteDescription(description string) RouteMetadataOption
- func WithRouteOperationID(operationID string) RouteMetadataOption
- func WithRouteParameters(parameters ...OpenAPIParameter) RouteMetadataOption
- func WithRouteRequestBody(body *OpenAPIRequestBody) RouteMetadataOption
- func WithRouteResponse(status int, response OpenAPIResponse) RouteMetadataOption
- func WithRouteSecurity(security ...OpenAPISecurityRequirement) RouteMetadataOption
- func WithRouteSummary(summary string) RouteMetadataOption
- func WithRouteTags(tags ...string) RouteMetadataOption
- type Schema
- type SchemaConfig
- type SchemaConfigAccountOption
- type SchemaConfigOption
- func WithPluginSchema(pluginName PluginName, schemaName SchemaName, opts ...PluginSchemaConfigOption) SchemaConfigOption
- func WithSchemaAccount(opts ...SchemaConfigAccountOption) SchemaConfigOption
- func WithSchemaAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigOption
- func WithSchemaIDGenerator(generator IDGenerator) SchemaConfigOption
- func WithSchemaRateLimit(opts ...SchemaConfigRateLimitOption) SchemaConfigOption
- func WithSchemaSession(opts ...SchemaConfigSessionOption) SchemaConfigOption
- func WithSchemaUUIDv7IDs() SchemaConfigOption
- func WithSchemaUser(opts ...SchemaConfigUserOption) SchemaConfigOption
- func WithSchemaVerification(opts ...SchemaConfigVerificationOption) SchemaConfigOption
- type SchemaConfigRateLimitOption
- func WithRateLimitFieldCount(fieldName string) SchemaConfigRateLimitOption
- func WithRateLimitFieldID(fieldName string) SchemaConfigRateLimitOption
- func WithRateLimitFieldKey(fieldName string) SchemaConfigRateLimitOption
- func WithRateLimitFieldLastRequestAt(fieldName string) SchemaConfigRateLimitOption
- func WithRateLimitTableName(tableName SchemaTableName) SchemaConfigRateLimitOption
- type SchemaConfigSessionOption
- func WithSessionAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigSessionOption
- func WithSessionFieldCreatedAt(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldExpiresAt(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldID(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldLastAccess(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldMetadata(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldToken(fieldName string) SchemaConfigSessionOption
- func WithSessionFieldUserID(fieldName string) SchemaConfigSessionOption
- func WithSessionTableName(tableName SchemaTableName) SchemaConfigSessionOption
- type SchemaConfigUserOption
- func WithUserAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigUserOption
- func WithUserFieldCreatedAt(fieldName string) SchemaConfigUserOption
- func WithUserFieldEmail(fieldName string) SchemaConfigUserOption
- func WithUserFieldEmailVerifiedAt(fieldName string) SchemaConfigUserOption
- func WithUserFieldID(fieldName string) SchemaConfigUserOption
- func WithUserFieldPassword(fieldName string) SchemaConfigUserOption
- func WithUserFieldSoftDelete(fieldName string) SchemaConfigUserOption
- func WithUserFieldUpdatedAt(fieldName string) SchemaConfigUserOption
- func WithUserFirstNameField(fieldName string) SchemaConfigUserOption
- func WithUserIncludeNameFields(include bool) SchemaConfigUserOption
- func WithUserLastNameField(fieldName string) SchemaConfigUserOption
- func WithUserSerializer(serializer func(data *User) map[string]any) SchemaConfigUserOption
- func WithUserTableName(tableName SchemaTableName) SchemaConfigUserOption
- type SchemaConfigVerificationOption
- func WithVerificationAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigVerificationOption
- func WithVerificationFieldCreatedAt(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldExpiresAt(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldID(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldSoftDelete(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldSubject(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldUpdatedAt(fieldName string) SchemaConfigVerificationOption
- func WithVerificationFieldValue(fieldName string) SchemaConfigVerificationOption
- func WithVerificationTableName(tableName SchemaTableName) SchemaConfigVerificationOption
- type SchemaDefinition
- func (d *SchemaDefinition) GetColumns() []ColumnDefinition
- func (d *SchemaDefinition) GetExtends() SchemaName
- func (d *SchemaDefinition) GetForeignKeys() []ForeignKeyDefinition
- func (d *SchemaDefinition) GetIndexes() []IndexDefinition
- func (d *SchemaDefinition) GetSchema() Schema
- func (d *SchemaDefinition) GetSchemaName() SchemaName
- func (d *SchemaDefinition) GetTableName() SchemaTableName
- type SchemaDefinitionMap
- type SchemaDefinitionOption
- func WithSchemaField(name string, columnType ColumnType, opts ...ColumnDefinitionOption) SchemaDefinitionOption
- func WithSchemaForeignKey(foreignKey ForeignKeyDefinition) SchemaDefinitionOption
- func WithSchemaIDField(config *SchemaConfig) SchemaDefinitionOption
- func WithSchemaIndex(name string, columns []SchemaField) SchemaDefinitionOption
- func WithSchemaUniqueIndex(name string, columns []SchemaField) SchemaDefinitionOption
- type SchemaField
- type SchemaInfo
- type SchemaIntrospector
- type SchemaName
- type SchemaProvider
- type SchemaResolver
- type SchemaTableName
- type Session
- type SessionConfigOption
- func WithBearerEnabled() SessionConfigOption
- func WithCustomSessionStore(store SessionStore) SessionConfigOption
- func WithSessionActivityCheckInterval(activityCheckInterval time.Duration) SessionConfigOption
- func WithSessionDuration(duration time.Duration) SessionConfigOption
- func WithSessionIPAddressExtractor(ipAddressExtractor func(request *http.Request) string) SessionConfigOption
- func WithSessionIdleTimeout(idleTimeout time.Duration) SessionConfigOption
- func WithSessionShortDuration(d time.Duration) SessionConfigOption
- func WithSessionStoreType(storeType StoreType) SessionConfigOption
- func WithSessionUpdateAge(updateAge time.Duration) SessionConfigOption
- func WithSessionUserAgentExtractor(userAgentExtractor func(request *http.Request) string) SessionConfigOption
- type SessionCreateOption
- type SessionCreateOptions
- type SessionManager
- type SessionManagerProvider
- type SessionResult
- type SessionSchema
- func (s *SessionSchema) FromStorage(data map[string]any) Model
- func (s *SessionSchema) GetCreatedAtField() string
- func (s *SessionSchema) GetExpiresAtField() string
- func (s *SessionSchema) GetLastAccessField() string
- func (s *SessionSchema) GetMetadataField() string
- func (s *SessionSchema) GetSoftDeleteField() string
- func (s *SessionSchema) GetTokenField() string
- func (s *SessionSchema) GetUserIDField() string
- func (s *SessionSchema) Introspect(config *SchemaConfig) SchemaIntrospector
- func (s *SessionSchema) ToStorage(data Model) map[string]any
- type SessionStore
- type SessionTransformer
- type StoreType
- type TransactionalAdapter
- type TrustedProxyIPExtractorOption
- type User
- type UserSchema
- func (u *UserSchema) FromStorage(data map[string]any) Model
- func (u *UserSchema) GetEmailField() string
- func (u *UserSchema) GetEmailVerifiedAtField() string
- func (u *UserSchema) GetPasswordField() string
- func (u *UserSchema) Introspect(config *SchemaConfig) SchemaIntrospector
- func (u *UserSchema) Serialize(data Model) map[string]any
- func (u *UserSchema) ToStorage(data Model) map[string]any
- type ValidatedSession
- type ValidationError
- type Validator
- func (v *Validator) Contains(field, value, substr string) *Validator
- func (v *Validator) ContainsAny(field, value, chars string) *Validator
- func (v *Validator) Custom(field string, fn func() error, formatErrorMessage bool) *Validator
- func (v *Validator) Email(field string, value any) *Validator
- func (v *Validator) In(field, value string, allowed []string) *Validator
- func (v *Validator) Length(field, value string, length int) *Validator
- func (v *Validator) Matches(field, value, pattern string) *Validator
- func (v *Validator) MaxLength(field, value string, maxLen int) *Validator
- func (v *Validator) MinLength(field, value string, minLen int) *Validator
- func (v *Validator) NotContains(field, value, substr string) *Validator
- func (v *Validator) RequiredString(field string, value any) *Validator
- func (v *Validator) URL(field, value string) *Validator
- func (v *Validator) Validate() error
- type Verification
- type VerificationSchema
- func (v *VerificationSchema) FromStorage(data map[string]any) Model
- func (v *VerificationSchema) GetCreatedAtField() string
- func (v *VerificationSchema) GetExpiresAtField() string
- func (v *VerificationSchema) GetSubjectField() string
- func (v *VerificationSchema) GetUpdatedAtField() string
- func (v *VerificationSchema) GetValueField() string
- func (v *VerificationSchema) Introspect(config *SchemaConfig) SchemaIntrospector
- func (v *VerificationSchema) ToStorage(data Model) map[string]any
- type Where
- func Contains(column, value string) Where
- func EndsWith(column, value string) Where
- func Eq(column string, value any) Where
- func Gt(column string, value any) Where
- func Gte(column string, value any) Where
- func In(column string, values []any) Where
- func IsNotNull(column string) Where
- func IsNull(column string) Where
- func Lt(column string, value any) Where
- func Lte(column string, value any) Where
- func Ne(column string, value any) Where
- func NotIn(column string, values []any) Where
- func StartsWith(column, value string) Where
Constants ¶
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" )
const ( TrustedProxyHeaderForwarded = "Forwarded" TrustedProxyHeaderXForwardedFor = "X-Forwarded-For" TrustedProxyHeaderXRealIP = "X-Real-IP" )
const (
EmailVerificationAction = "email_verification"
)
Verification Action Names
Variables ¶
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") )
var ( ErrSessionNotFound = errors.New("session not found") ErrSessionExpired = errors.New("session has expired") ErrSessionInvalid = errors.New("session is invalid") )
Session-specific errors
var ( ErrRateLimitExceeded = errors.New("rate limit exceeded") ErrRateLimitNotFound = errors.New("rate limit not found") )
Rate limiting errors
var ( ErrEmailAlreadyVerified = NewLimenError("email already verified", http.StatusConflict, nil) ErrEmailVerificationTokenInvalid = NewLimenError("invalid or expired email verification token", http.StatusBadRequest, nil) )
Email verification errors
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 ¶
Decrypt decrypts the base64-encoded ciphertext using XChaCha20-Poly1305 with the provided key.
func EncryptXChaCha ¶
Encrypt encrypts the plaintext using XChaCha20-Poly1305 with the provided key (32 bytes).
func ExtractCookieValue ¶
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 GetJSONBody ¶
GetBody extracts the parsed JSON body from the request context
func GroupConditionsByConnector ¶
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 ¶
NewTestLimen creates a fully-initialized *Limen backed by an in-memory adapter.
func ParseVerificationAction ¶
func SerializeAll ¶
SerializeAll serializes a slice of models using the given schema's Serialize method.
func SerializeModel ¶
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 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
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
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 DatabaseActionHelper ¶
type DatabaseActionHelper struct {
// contains filtered or unexported fields
}
DatabaseActionHelper provides common database operations for plugins.
func (*DatabaseActionHelper) CreateSession ¶
func (*DatabaseActionHelper) CreateUser ¶
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 (*DatabaseActionHelper) FindSessionByToken ¶
func (*DatabaseActionHelper) FindUserByEmail ¶
func (*DatabaseActionHelper) FindUserByID ¶
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 (*DatabaseActionHelper) UpdateSession ¶
func (*DatabaseActionHelper) UpdateUser ¶
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 EnvelopeMode ¶
type EnvelopeMode int
const ( EnvelopeOff EnvelopeMode = iota EnvelopeWrapSuccess EnvelopeAlways )
type Errors ¶
type Errors struct {
// contains filtered or unexported fields
}
func (*Errors) GetErrors ¶
func (e *Errors) GetErrors() []*ValidationError
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 ¶
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 (*Limen) CleanupExpired ¶ added in v0.1.4
func (*Limen) GetSession ¶
func (a *Limen) GetSession(req *http.Request) (*ValidatedSession, error)
func (*Limen) ListSessions ¶
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 ¶
RevokeAllSessions revokes every session belonging to the given user.
func (*Limen) RevokeSession ¶
RevokeSession revokes a single session identified by its token.
type LimenCore ¶
type LimenCore struct {
DBAction *DatabaseActionHelper
Schema *SchemaConfig
SessionManager SessionManager
// contains filtered or unexported fields
}
func (*LimenCore) CacheKeyPrefix ¶
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 (*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) CreateEmailVerification ¶
CreateEmailVerification creates a new verification token for the user.
func (*LimenCore) CreateSession ¶
func (c *LimenCore) CreateSession(ctx context.Context, r *http.Request, w http.ResponseWriter, auth *AuthenticationResult, opts ...SessionCreateOption) (*SessionResult, error)
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) EmailVerificationEnabled ¶
EmailVerificationEnabled reports whether email verification is enabled.
func (*LimenCore) GetBaseURL ¶
func (*LimenCore) GetBaseURLWithPluginPath ¶
func (c *LimenCore) GetBaseURLWithPluginPath(pluginName PluginName, pathToJoin string) string
func (*LimenCore) GetFullBaseURL ¶
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 ¶
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) UpdateRawAffected ¶ added in v0.1.6
func (*LimenCore) VerifyEmail ¶
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 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
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 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
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 OpenAPISecurityScheme ¶ added in v0.1.6
type OpenAPIServer ¶ added in v0.1.6
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 ¶
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) ResetCounter ¶
func (r *RateLimit) ResetCounter()
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
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 ¶
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) 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
type ResponseData ¶
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 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 WithSessionAdditionalFields ¶
func WithSessionAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigSessionOption
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 WithUserAdditionalFields ¶
func WithUserAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigUserOption
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 WithVerificationAdditionalFields ¶
func WithVerificationAdditionalFields(fn AdditionalFieldsFunc) SchemaConfigVerificationOption
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
}
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 ¶
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
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.
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 ¶
SeedTestUser inserts a user directly into the in-memory DB and returns the full *User. The Limen instance must have been created with NewTestLimen.
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
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) ContainsAny ¶
func (*Validator) NotContains ¶
func (*Validator) RequiredString ¶
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
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 StartsWith ¶
StartsWith creates a starts-with condition
Source Files
¶
- account.go
- account_introspect.go
- account_schema.go
- cache_adapter.go
- cache_adapter_memory.go
- cleanup.go
- cli_config.go
- config.go
- constants.go
- context_additional_fields.go
- context_transaction.go
- cookie_manager.go
- crypto.go
- database.go
- database_actions.go
- database_helper.go
- email_verification.go
- email_verification_config.go
- errors.go
- hook.go
- http_config.go
- http_utils.go
- id_generator.go
- limen.go
- limen_core.go
- limen_handlers.go
- limen_http_core.go
- lock_stripes.go
- middlewares.go
- openapi.go
- plugin.go
- rate_limit.go
- rate_limit_introspect.go
- rate_limit_rule.go
- rate_limiter.go
- rate_limiter_config.go
- rate_limiter_store_cache.go
- rate_limiter_store_database.go
- response.go
- response_writer.go
- route_builder.go
- route_metadata.go
- router.go
- schema.go
- schema_config.go
- schema_definition.go
- schema_discovery.go
- schema_info.go
- schema_introspection.go
- schema_options.go
- schema_resolver.go
- session.go
- session_config.go
- session_introspect.go
- session_manager.go
- session_store_cache.go
- session_store_database.go
- testing_support.go
- trusted_proxy.go
- types.go
- user.go
- user_introspect.go
- utils.go
- validator.go
- verification.go
- verification_introspect.go
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
sql
module
|
|
|
cmd
|
|
|
limen
module
|
|
|
integrations
|
|
|
huma
module
|
|
|
plugins
|
|
|
credential-password
module
|
|
|
magic-link
module
|
|
|
oauth
module
|
|
|
oauth-apple
module
|
|
|
oauth-consentkeys
module
|
|
|
oauth-discord
module
|
|
|
oauth-facebook
module
|
|
|
oauth-generic
module
|
|
|
oauth-github
module
|
|
|
oauth-google
module
|
|
|
oauth-linkedin
module
|
|
|
oauth-microsoft
module
|
|
|
oauth-spotify
module
|
|
|
oauth-twitch
module
|
|
|
oauth-twitter
module
|
|
|
session-jwt
module
|