Documentation
¶
Index ¶
- Constants
- func ApplyColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error
- func ApplyRowSecurity(secCtx SecurityContext, securityList *SecurityList) error
- func CheckModelAuthAllowed(secCtx SecurityContext, operation string) error
- func CheckModelDeleteAllowed(secCtx SecurityContext) error
- func CheckModelUpdateAllowed(secCtx SecurityContext) error
- func ClearSessionCookie(w http.ResponseWriter, opts ...SessionCookieOptions)
- func ExampleOAuth2AllProviders()
- func ExampleOAuth2Complete()
- func ExampleOAuth2Custom()
- func ExampleOAuth2GitHub()
- func ExampleOAuth2Google()
- func ExampleOAuth2Logout()
- func ExampleOAuth2MultiProvider()
- func ExampleOAuth2TokenRefresh()
- func GenerateBackupCodes(count int) ([]string, error)
- func GetModelRulesFromContext(ctx context.Context) (modelregistry.ModelRules, bool)
- func GetRemoteID(ctx context.Context) (string, bool)
- func GetSessionCookie(r *http.Request, opts ...SessionCookieOptions) string
- func GetSessionID(ctx context.Context) (string, bool)
- func GetSessionRID(ctx context.Context) (int64, bool)
- func GetUserEmail(ctx context.Context) (string, bool)
- func GetUserID(ctx context.Context) (int, bool)
- func GetUserLevel(ctx context.Context) (int, bool)
- func GetUserMeta(ctx context.Context) (map[string]any, bool)
- func GetUserName(ctx context.Context) (string, bool)
- func GetUserRoles(ctx context.Context) ([]string, bool)
- func LoadSecurityRules(secCtx SecurityContext, securityList *SecurityList) error
- func LogDataAccess(secCtx SecurityContext) error
- func NewAuthHandler(securityList *SecurityList, next http.Handler) http.Handler
- func NewAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
- func NewModelAuthMiddleware(securityList *SecurityList, modelName string) func(http.Handler) http.Handler
- func NewOptionalAuthHandler(securityList *SecurityList, next http.Handler) http.Handler
- func NewOptionalAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
- func OptionalAuth(ctx context.Context) context.Context
- func PasskeyAuthenticationExample()
- func PasskeyClientSideExample() string
- func PasskeyHTTPHandlersExample(auth *DatabaseAuthenticator)
- func SetSecurityMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
- func SetSessionCookie(w http.ResponseWriter, loginResp *LoginResponse, opts ...SessionCookieOptions)
- func SkipAuth(ctx context.Context) context.Context
- func ValidateKeyStoreSQLNames(names *KeyStoreSQLNames) error
- func ValidateSQLNames(names *SQLNames) error
- func WithAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
- func WithAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
- func WithOptionalAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
- func WithOptionalAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
- func WithSecurityContext(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
- type Authenticator
- type CONTEXT_KEY
- type Cacheable
- type ColumnSecurity
- type ColumnSecurityProvider
- type CompositeSecurityProvider
- func (c *CompositeSecurityProvider) Authenticate(r *http.Request) (*UserContext, error)
- func (c *CompositeSecurityProvider) ClearCache(ctx context.Context, userID int, schema, table string) error
- func (c *CompositeSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
- func (c *CompositeSecurityProvider) GetRowSecurity(ctx context.Context, userID int, schema, table string) (RowSecurity, error)
- func (c *CompositeSecurityProvider) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) Logout(ctx context.Context, req LogoutRequest) error
- func (c *CompositeSecurityProvider) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) ValidateToken(ctx context.Context, token string) (bool, error)
- type ConfigColumnSecurityProvider
- type ConfigKeyStore
- func (s *ConfigKeyStore) CreateKey(_ context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
- func (s *ConfigKeyStore) DeleteKey(_ context.Context, userID int, keyID int64) error
- func (s *ConfigKeyStore) GetUserKeys(_ context.Context, userID int, keyType KeyType) ([]UserKey, error)
- func (s *ConfigKeyStore) ValidateKey(_ context.Context, rawKey string, keyType KeyType) (*UserKey, error)
- type ConfigRowSecurityProvider
- type CreateKeyRequest
- type CreateKeyResponse
- type DatabaseAuthenticator
- func NewDatabaseAuthenticator(db *sql.DB) *DatabaseAuthenticator
- func NewDatabaseAuthenticatorWithOptions(db *sql.DB, opts DatabaseAuthenticatorOptions) *DatabaseAuthenticator
- func NewFacebookAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
- func NewGitHubAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
- func NewGoogleAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
- func NewMicrosoftAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
- func NewMultiProviderAuthenticator(db *sql.DB, configs map[string]OAuth2Config) *DatabaseAuthenticator
- func (a *DatabaseAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
- func (a *DatabaseAuthenticator) BeginPasskeyAuthentication(ctx context.Context, req PasskeyBeginAuthenticationRequest) (*PasskeyAuthenticationOptions, error)
- func (a *DatabaseAuthenticator) BeginPasskeyRegistration(ctx context.Context, req PasskeyBeginRegistrationRequest) (*PasskeyRegistrationOptions, error)
- func (a *DatabaseAuthenticator) ClearCache(token string) error
- func (a *DatabaseAuthenticator) ClearUserCache(userID int) error
- func (a *DatabaseAuthenticator) CompletePasskeyRegistration(ctx context.Context, req PasskeyRegisterRequest) (*PasskeyCredential, error)
- func (a *DatabaseAuthenticator) DeletePasskeyCredential(ctx context.Context, userID int, credentialID string) error
- func (a *DatabaseAuthenticator) GetPasskeyCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)
- func (a *DatabaseAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) LoginWithPasskey(ctx context.Context, req PasskeyLoginRequest) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
- func (a *DatabaseAuthenticator) OAuth2GenerateState() (string, error)
- func (a *DatabaseAuthenticator) OAuth2GetAuthURL(providerName, state string) (string, error)
- func (a *DatabaseAuthenticator) OAuth2GetProviders() []string
- func (a *DatabaseAuthenticator) OAuth2HandleCallback(ctx context.Context, providerName, code, state string) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) OAuth2RefreshToken(ctx context.Context, refreshToken, providerName string) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) OAuthExchangeCode(ctx context.Context, code string) (*OAuthCode, error)
- func (a *DatabaseAuthenticator) OAuthGetClient(ctx context.Context, clientID string) (*OAuthServerClient, error)
- func (a *DatabaseAuthenticator) OAuthIntrospectToken(ctx context.Context, token string) (*OAuthTokenInfo, error)
- func (a *DatabaseAuthenticator) OAuthRegisterClient(ctx context.Context, client *OAuthServerClient) (*OAuthServerClient, error)
- func (a *DatabaseAuthenticator) OAuthRevokeToken(ctx context.Context, token string) error
- func (a *DatabaseAuthenticator) OAuthSaveCode(ctx context.Context, code *OAuthCode) error
- func (a *DatabaseAuthenticator) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) Register(ctx context.Context, req RegisterRequest) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) UpdatePasskeyCredentialName(ctx context.Context, userID int, credentialID string, name string) error
- func (a *DatabaseAuthenticator) WithOAuth2(cfg OAuth2Config) *DatabaseAuthenticator
- func (a *DatabaseAuthenticator) WithPasskey(provider PasskeyProvider) *DatabaseAuthenticator
- type DatabaseAuthenticatorExample
- func (a *DatabaseAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)
- func (a *DatabaseAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (a *DatabaseAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error
- func (a *DatabaseAuthenticatorExample) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
- type DatabaseAuthenticatorOptions
- type DatabaseColumnSecurityProvider
- type DatabaseKeyStore
- func (ks *DatabaseKeyStore) CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
- func (ks *DatabaseKeyStore) DeleteKey(ctx context.Context, userID int, keyID int64) error
- func (ks *DatabaseKeyStore) GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)
- func (ks *DatabaseKeyStore) ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)
- type DatabaseKeyStoreOptions
- type DatabasePasskeyProvider
- func (p *DatabasePasskeyProvider) BeginAuthentication(ctx context.Context, username string) (*PasskeyAuthenticationOptions, error)
- func (p *DatabasePasskeyProvider) BeginRegistration(ctx context.Context, userID int, username, displayName string) (*PasskeyRegistrationOptions, error)
- func (p *DatabasePasskeyProvider) CompleteAuthentication(ctx context.Context, response PasskeyAuthenticationResponse, ...) (int, error)
- func (p *DatabasePasskeyProvider) CompleteRegistration(ctx context.Context, userID int, response PasskeyRegistrationResponse, ...) (*PasskeyCredential, error)
- func (p *DatabasePasskeyProvider) DeleteCredential(ctx context.Context, userID int, credentialID string) error
- func (p *DatabasePasskeyProvider) GetCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)
- func (p *DatabasePasskeyProvider) UpdateCredentialName(ctx context.Context, userID int, credentialID string, name string) error
- type DatabasePasskeyProviderOptions
- type DatabaseRowSecurityProvider
- type DatabaseTwoFactorProvider
- func (p *DatabaseTwoFactorProvider) Disable2FA(userID int) error
- func (p *DatabaseTwoFactorProvider) Enable2FA(userID int, secret string, backupCodes []string) error
- func (p *DatabaseTwoFactorProvider) Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)
- func (p *DatabaseTwoFactorProvider) GenerateBackupCodes(userID int, count int) ([]string, error)
- func (p *DatabaseTwoFactorProvider) Get2FASecret(userID int) (string, error)
- func (p *DatabaseTwoFactorProvider) Get2FAStatus(userID int) (bool, error)
- func (p *DatabaseTwoFactorProvider) Validate2FACode(secret string, code string) (bool, error)
- func (p *DatabaseTwoFactorProvider) ValidateBackupCode(userID int, code string) (bool, error)
- type HeaderAuthenticator
- type HeaderAuthenticatorExample
- type JWTAuthenticator
- func (a *JWTAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
- func (a *JWTAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (a *JWTAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
- func (a *JWTAuthenticator) WithDBFactory(factory func() (*sql.DB, error)) *JWTAuthenticator
- type JWTAuthenticatorExample
- type KeyStore
- type KeyStoreAuthenticator
- type KeyStoreSQLNames
- type KeyType
- type LoginRequest
- type LoginResponse
- type LogoutRequest
- type MemoryTwoFactorProvider
- func (m *MemoryTwoFactorProvider) Disable2FA(userID int) error
- func (m *MemoryTwoFactorProvider) Enable2FA(userID int, secret string, backupCodes []string) error
- func (m *MemoryTwoFactorProvider) Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)
- func (m *MemoryTwoFactorProvider) GenerateBackupCodes(userID int, count int) ([]string, error)
- func (m *MemoryTwoFactorProvider) Get2FASecret(userID int) (string, error)
- func (m *MemoryTwoFactorProvider) Get2FAStatus(userID int) (bool, error)
- func (m *MemoryTwoFactorProvider) Validate2FACode(secret string, code string) (bool, error)
- func (m *MemoryTwoFactorProvider) ValidateBackupCode(userID int, code string) (bool, error)
- type OAuth2Config
- type OAuth2Provider
- type OAuthCode
- type OAuthServer
- type OAuthServerClient
- type OAuthServerConfig
- type OAuthTokenInfo
- type PasskeyAuthenticationOptions
- type PasskeyAuthenticationResponse
- type PasskeyAuthenticatorAssertionResponse
- type PasskeyAuthenticatorAttestationResponse
- type PasskeyAuthenticatorSelection
- type PasskeyBeginAuthenticationRequest
- type PasskeyBeginRegistrationRequest
- type PasskeyCredential
- type PasskeyCredentialDescriptor
- type PasskeyCredentialParam
- type PasskeyLoginRequest
- type PasskeyProvider
- type PasskeyRegisterRequest
- type PasskeyRegistrationOptions
- type PasskeyRegistrationResponse
- type PasskeyRelyingParty
- type PasskeyUser
- type Refreshable
- type RegisterRequest
- type Registrable
- type RowSecurity
- type RowSecurityProvider
- type SQLNames
- type SecurityContext
- type SecurityList
- func (m *SecurityList) ApplyColumnSecurity(records reflect.Value, modelType reflect.Type, pUserID int, ...) (reflect.Value, error)
- func (m *SecurityList) ClearSecurity(pUserID int, pSchema, pTablename string) error
- func (m *SecurityList) ColumSecurityApplyOnRecord(prevRecord reflect.Value, newRecord reflect.Value, modelType reflect.Type, ...) ([]string, error)
- func (m *SecurityList) GetRowSecurityTemplate(pUserID int, pSchema, pTablename string) (RowSecurity, error)
- func (m *SecurityList) LoadColumnSecurity(ctx context.Context, pUserID int, pSchema, pTablename string, pOverwrite bool) error
- func (m *SecurityList) LoadRowSecurity(ctx context.Context, pUserID int, pSchema, pTablename string, pOverwrite bool) (RowSecurity, error)
- func (m *SecurityList) Provider() SecurityProvider
- type SecurityProvider
- type SessionCookieOptions
- type TOTPGenerator
- func (t *TOTPGenerator) GenerateCode(secret string, timestamp time.Time) (string, error)
- func (t *TOTPGenerator) GenerateQRCodeURL(secret, issuer, accountName string) string
- func (t *TOTPGenerator) GenerateSecret() (string, error)
- func (t *TOTPGenerator) ValidateCode(secret, code string) (bool, error)
- type TwoFactorAuthProvider
- type TwoFactorAuthenticator
- func (t *TwoFactorAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
- func (t *TwoFactorAuthenticator) Disable2FA(userID int) error
- func (t *TwoFactorAuthenticator) Enable2FA(userID int, secret, verificationCode string) error
- func (t *TwoFactorAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (t *TwoFactorAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
- func (t *TwoFactorAuthenticator) RegenerateBackupCodes(userID int, count int) ([]string, error)
- func (t *TwoFactorAuthenticator) Setup2FA(userID int, issuer, accountName string) (*TwoFactorSecret, error)
- type TwoFactorConfig
- type TwoFactorSecret
- type UserContext
- type UserKey
- type Validatable
Constants ¶
const ( // Context keys for user information UserIDKey contextKey = "user_id" UserNameKey contextKey = "user_name" UserLevelKey contextKey = "user_level" SessionIDKey contextKey = "session_id" SessionRIDKey contextKey = "session_rid" RemoteIDKey contextKey = "remote_id" UserRolesKey contextKey = "user_roles" UserEmailKey contextKey = "user_email" UserContextKey contextKey = "user_context" UserMetaKey contextKey = "user_meta" SkipAuthKey contextKey = "skip_auth" OptionalAuthKey contextKey = "optional_auth" ModelRulesKey contextKey = "model_rules" )
Variables ¶
This section is empty.
Functions ¶
func ApplyColumnSecurity ¶ added in v0.0.63
func ApplyColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error
ApplyColumnSecurity is a public wrapper for applyColumnSecurity that accepts a SecurityContext This allows other packages to apply column-level security using the generic interface
func ApplyRowSecurity ¶ added in v0.0.63
func ApplyRowSecurity(secCtx SecurityContext, securityList *SecurityList) error
ApplyRowSecurity is a public wrapper for applyRowSecurity that accepts a SecurityContext This allows other packages to apply row-level security using the generic interface
func CheckModelAuthAllowed ¶ added in v1.0.56
func CheckModelAuthAllowed(secCtx SecurityContext, operation string) error
CheckModelAuthAllowed checks whether the requested operation is permitted based on model rules and the current user's authentication state. It is intended for use in a BeforeHandle hook, fired after model resolution.
Logic:
- Load model rules from context (set by NewModelAuthMiddleware) or fall back to registry.
- SecurityDisabled → allow.
- operation == "read" && CanPublicRead → allow.
- operation == "create" && CanPublicCreate → allow.
- operation == "update" && CanPublicUpdate → allow.
- operation == "delete" && CanPublicDelete → allow.
- Guest (UserID == 0) → return "authentication required".
- Authenticated user → allow (operation-specific checks remain in BeforeUpdate/BeforeDelete).
func CheckModelDeleteAllowed ¶ added in v1.0.55
func CheckModelDeleteAllowed(secCtx SecurityContext) error
CheckModelDeleteAllowed is the public wrapper for checkModelDeleteAllowed.
func CheckModelUpdateAllowed ¶ added in v1.0.55
func CheckModelUpdateAllowed(secCtx SecurityContext) error
CheckModelUpdateAllowed is the public wrapper for checkModelUpdateAllowed.
func ClearSessionCookie ¶ added in v1.0.64
func ClearSessionCookie(w http.ResponseWriter, opts ...SessionCookieOptions)
ClearSessionCookie expires the session_token cookie, effectively logging the user out on the browser side. Call this after a successful Authenticator.Logout() call.
Example:
err := auth.Logout(r.Context(), req)
if err != nil { ... }
security.ClearSessionCookie(w)
func ExampleOAuth2AllProviders ¶ added in v1.0.48
func ExampleOAuth2AllProviders()
Example: All OAuth2 Providers at Once
func ExampleOAuth2Complete ¶ added in v1.0.48
func ExampleOAuth2Complete()
Example: Complete OAuth2 Integration with Database Setup
func ExampleOAuth2Custom ¶ added in v1.0.48
func ExampleOAuth2Custom()
Example: Custom OAuth2 Provider
func ExampleOAuth2GitHub ¶ added in v1.0.48
func ExampleOAuth2GitHub()
Example: OAuth2 Authentication with GitHub
func ExampleOAuth2Google ¶ added in v1.0.48
func ExampleOAuth2Google()
Example: OAuth2 Authentication with Google
func ExampleOAuth2MultiProvider ¶ added in v1.0.48
func ExampleOAuth2MultiProvider()
Example: Multi-Provider OAuth2 with Security Integration
func ExampleOAuth2TokenRefresh ¶ added in v1.0.48
func ExampleOAuth2TokenRefresh()
Example: OAuth2 with Token Refresh
func GenerateBackupCodes ¶ added in v1.0.48
GenerateBackupCodes creates random backup codes
func GetModelRulesFromContext ¶ added in v1.0.55
func GetModelRulesFromContext(ctx context.Context) (modelregistry.ModelRules, bool)
GetModelRulesFromContext extracts ModelRules stored by NewModelAuthMiddleware
func GetRemoteID ¶ added in v0.0.63
GetRemoteID extracts the remote ID from context
func GetSessionCookie ¶ added in v1.0.64
func GetSessionCookie(r *http.Request, opts ...SessionCookieOptions) string
GetSessionCookie returns the session token value from the request cookie, or empty string if not present.
Example:
token := security.GetSessionCookie(r)
func GetSessionID ¶ added in v0.0.63
GetSessionID extracts the session ID from context
func GetSessionRID ¶ added in v0.0.81
GetSessionID extracts the session ID from context
func GetUserEmail ¶ added in v0.0.63
GetUserEmail extracts user email from context
func GetUserLevel ¶ added in v0.0.63
GetUserLevel extracts the user level from context
func GetUserMeta ¶ added in v0.0.64
GetUserMeta extracts user metadata from context
func GetUserName ¶ added in v0.0.63
GetUserName extracts the user name from context
func GetUserRoles ¶
GetUserRoles extracts user roles from context
func LoadSecurityRules ¶ added in v0.0.63
func LoadSecurityRules(secCtx SecurityContext, securityList *SecurityList) error
LoadSecurityRules is a public wrapper for loadSecurityRules that accepts a SecurityContext This allows other packages to load security rules using the generic interface
func LogDataAccess ¶ added in v0.0.63
func LogDataAccess(secCtx SecurityContext) error
LogDataAccess is a public wrapper for logDataAccess that accepts a SecurityContext This allows other packages to use the audit logging functionality
func NewAuthHandler ¶ added in v0.0.64
func NewAuthHandler(securityList *SecurityList, next http.Handler) http.Handler
NewAuthHandler creates an authentication handler that can be used standalone This handler performs authentication and returns 401 if authentication fails Use this when you need authentication logic without middleware wrapping
func NewAuthMiddleware ¶ added in v0.0.63
func NewAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
NewAuthMiddleware creates an authentication middleware with the given security list This middleware extracts user authentication from the request and adds it to context Routes can skip authentication by setting SkipAuthKey context value (use SkipAuth helper) Routes can use optional authentication by setting OptionalAuthKey context value (use OptionalAuth helper) When authentication is skipped or fails with optional auth, a guest user context is set instead
func NewModelAuthMiddleware ¶ added in v1.0.55
func NewModelAuthMiddleware(securityList *SecurityList, modelName string) func(http.Handler) http.Handler
NewModelAuthMiddleware creates authentication middleware that respects ModelRules for the given model name. It first checks if ModelRules are set for the model:
- If SecurityDisabled is true, authentication is skipped and a guest context is set.
- Otherwise, all checks from NewAuthMiddleware apply (SkipAuthKey, provider check, OptionalAuthKey, Authenticate).
If the model is not found in any registry, the middleware falls back to standard NewAuthMiddleware behaviour.
func NewOptionalAuthHandler ¶ added in v0.0.64
func NewOptionalAuthHandler(securityList *SecurityList, next http.Handler) http.Handler
NewOptionalAuthHandler creates an optional authentication handler that can be used standalone This handler tries to authenticate but falls back to guest context if authentication fails Use this for routes that should show personalized content for authenticated users but still work for guests
func NewOptionalAuthMiddleware ¶ added in v1.0.56
func NewOptionalAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
NewOptionalAuthMiddleware creates authentication middleware that always continues. On auth failure, a guest user context is set instead of returning 401. Intended for spec routes where auth enforcement is deferred to a BeforeHandle hook after model resolution.
func OptionalAuth ¶ added in v0.0.64
OptionalAuth returns a context with optional auth flag set to true Use this to mark routes that should try to authenticate, but fall back to guest if authentication fails
func PasskeyAuthenticationExample ¶ added in v1.0.48
func PasskeyAuthenticationExample()
PasskeyAuthenticationExample demonstrates passkey (WebAuthn/FIDO2) authentication
func PasskeyClientSideExample ¶ added in v1.0.48
func PasskeyClientSideExample() string
PasskeyClientSideExample shows the client-side JavaScript code needed
func PasskeyHTTPHandlersExample ¶ added in v1.0.48
func PasskeyHTTPHandlersExample(auth *DatabaseAuthenticator)
PasskeyHTTPHandlersExample shows HTTP handlers for passkey authentication
func SetSecurityMiddleware ¶
func SetSecurityMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
SetSecurityMiddleware adds security context to requests This middleware should be applied after AuthMiddleware
func SetSessionCookie ¶ added in v1.0.64
func SetSessionCookie(w http.ResponseWriter, loginResp *LoginResponse, opts ...SessionCookieOptions)
SetSessionCookie writes the session_token cookie to the response after a successful login. Call this immediately after a successful Authenticator.Login() call.
Example:
resp, err := auth.Login(r.Context(), req)
if err != nil { ... }
security.SetSessionCookie(w, resp)
json.NewEncoder(w).Encode(resp)
func SkipAuth ¶ added in v0.0.64
SkipAuth returns a context with skip auth flag set to true Use this to mark routes that should bypass authentication middleware
func ValidateKeyStoreSQLNames ¶ added in v1.0.78
func ValidateKeyStoreSQLNames(names *KeyStoreSQLNames) error
ValidateKeyStoreSQLNames checks that all non-empty procedure names are valid SQL identifiers.
func ValidateSQLNames ¶ added in v1.0.73
ValidateSQLNames checks that all non-empty fields in names are valid SQL identifiers. Returns an error if any field contains invalid characters.
func WithAuth ¶ added in v0.0.83
func WithAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
WithAuth wraps an HTTPFuncType handler with required authentication This function performs authentication and returns 401 if authentication fails Use this for handlers that require authenticated users
Usage:
handler := funcspec.NewHandler(db)
wrappedHandler := security.WithAuth(handler.SqlQueryList("SELECT * FROM orders WHERE user_id = [rid_user]", false, false, false), securityList)
router.HandleFunc("/api/orders", wrappedHandler)
func WithAuthAndSecurity ¶ added in v0.0.83
func WithAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
WithAuthAndSecurity wraps an HTTPFuncType handler with both authentication and security context This is a convenience function that combines WithAuth and WithSecurityContext Use this when you need both authentication and security context for a handler
Usage:
handler := funcspec.NewHandler(db)
wrappedHandler := security.WithAuthAndSecurity(handler.SqlQueryList("SELECT * FROM users", false, false, false), securityList)
router.HandleFunc("/api/users", wrappedHandler)
func WithOptionalAuth ¶ added in v0.0.83
func WithOptionalAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
WithOptionalAuth wraps an HTTPFuncType handler with optional authentication This function tries to authenticate but falls back to guest context if authentication fails Use this for handlers that should show personalized content for authenticated users but still work for guests
Usage:
handler := funcspec.NewHandler(db)
wrappedHandler := security.WithOptionalAuth(handler.SqlQueryList("SELECT * FROM products", false, false, false), securityList)
router.HandleFunc("/api/products", wrappedHandler)
func WithOptionalAuthAndSecurity ¶ added in v0.0.83
func WithOptionalAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
WithOptionalAuthAndSecurity wraps an HTTPFuncType handler with optional authentication and security context This is a convenience function that combines WithOptionalAuth and WithSecurityContext Use this when you want optional authentication and security context for a handler
Usage:
handler := funcspec.NewHandler(db)
wrappedHandler := security.WithOptionalAuthAndSecurity(handler.SqlQueryList("SELECT * FROM products", false, false, false), securityList)
router.HandleFunc("/api/products", wrappedHandler)
func WithSecurityContext ¶ added in v0.0.83
func WithSecurityContext(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)
WithSecurityContext wraps an HTTPFuncType handler with security context This function allows you to add security context to specific handler functions without needing to apply middleware globally
Usage:
handler := funcspec.NewHandler(db)
wrappedHandler := security.WithSecurityContext(handler.SqlQueryList("SELECT * FROM users", false, false, false), securityList)
router.HandleFunc("/api/users", wrappedHandler)
Types ¶
type Authenticator ¶ added in v0.0.63
type Authenticator interface {
// Login authenticates credentials and returns a token
Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
// Logout invalidates a user's session/token
Logout(ctx context.Context, req LogoutRequest) error
// Authenticate extracts and validates user from HTTP request
// Returns UserContext or error if authentication fails
Authenticate(r *http.Request) (*UserContext, error)
}
Authenticator handles user authentication operations
type CONTEXT_KEY ¶ added in v0.0.20
type CONTEXT_KEY string
const SECURITY_CONTEXT_KEY CONTEXT_KEY = "SecurityList"
type Cacheable ¶ added in v0.0.63
type Cacheable interface {
// ClearCache clears cached security rules for a user/entity
ClearCache(ctx context.Context, userID int, schema, table string) error
}
Cacheable allows providers to support caching of security rules
type ColumnSecurity ¶
type ColumnSecurity struct {
Schema string `json:"schema"`
Tablename string `json:"tablename"`
Path []string `json:"path"`
ExtraFilters map[string]string `json:"extra_filters"`
UserID int `json:"user_id"`
Accesstype string `json:"accesstype"`
MaskStart int `json:"mask_start"`
MaskEnd int `json:"mask_end"`
MaskInvert bool `json:"mask_invert"`
MaskChar string `json:"mask_char"`
Control string `json:"control"`
ID int `json:"id"`
}
type ColumnSecurityProvider ¶ added in v0.0.63
type ColumnSecurityProvider interface {
// GetColumnSecurity loads column security rules for a user and entity
GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
}
ColumnSecurityProvider handles column-level security (masking/hiding)
type CompositeSecurityProvider ¶ added in v0.0.63
type CompositeSecurityProvider struct {
// contains filtered or unexported fields
}
CompositeSecurityProvider combines multiple security providers Allows separating authentication, column security, and row security concerns
func NewCompositeSecurityProvider ¶ added in v0.0.63
func NewCompositeSecurityProvider( auth Authenticator, colSec ColumnSecurityProvider, rowSec RowSecurityProvider, ) (*CompositeSecurityProvider, error)
NewCompositeSecurityProvider creates a composite provider All parameters are required
func (*CompositeSecurityProvider) Authenticate ¶ added in v0.0.63
func (c *CompositeSecurityProvider) Authenticate(r *http.Request) (*UserContext, error)
Authenticate delegates to the authenticator
func (*CompositeSecurityProvider) ClearCache ¶ added in v0.0.63
func (c *CompositeSecurityProvider) ClearCache(ctx context.Context, userID int, schema, table string) error
ClearCache implements Cacheable if any provider supports it
func (*CompositeSecurityProvider) GetColumnSecurity ¶ added in v0.0.63
func (c *CompositeSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
GetColumnSecurity delegates to the column security provider
func (*CompositeSecurityProvider) GetRowSecurity ¶ added in v0.0.63
func (c *CompositeSecurityProvider) GetRowSecurity(ctx context.Context, userID int, schema, table string) (RowSecurity, error)
GetRowSecurity delegates to the row security provider
func (*CompositeSecurityProvider) Login ¶ added in v0.0.63
func (c *CompositeSecurityProvider) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
Login delegates to the authenticator
func (*CompositeSecurityProvider) Logout ¶ added in v0.0.63
func (c *CompositeSecurityProvider) Logout(ctx context.Context, req LogoutRequest) error
Logout delegates to the authenticator
func (*CompositeSecurityProvider) RefreshToken ¶ added in v0.0.63
func (c *CompositeSecurityProvider) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
RefreshToken implements Refreshable if the authenticator supports it
func (*CompositeSecurityProvider) ValidateToken ¶ added in v0.0.63
ValidateToken implements Validatable if the authenticator supports it
type ConfigColumnSecurityProvider ¶ added in v0.0.63
type ConfigColumnSecurityProvider struct {
// contains filtered or unexported fields
}
ConfigColumnSecurityProvider provides static column security configuration
func NewConfigColumnSecurityProvider ¶ added in v0.0.63
func NewConfigColumnSecurityProvider(rules map[string][]ColumnSecurity) *ConfigColumnSecurityProvider
func (*ConfigColumnSecurityProvider) GetColumnSecurity ¶ added in v0.0.63
func (p *ConfigColumnSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
type ConfigKeyStore ¶ added in v1.0.78
type ConfigKeyStore struct {
// contains filtered or unexported fields
}
ConfigKeyStore is an in-memory keystore backed by a static slice of UserKey values. It is designed for config-file driven setups (e.g. service accounts defined in YAML) with a small, bounded number of keys. For large or dynamic key sets use DatabaseKeyStore.
Pre-existing entries must have KeyHash set to the SHA-256 hex of the intended raw key. Keys created at runtime via CreateKey are held in memory only and lost on restart.
func NewConfigKeyStore ¶ added in v1.0.78
func NewConfigKeyStore(keys []UserKey) *ConfigKeyStore
NewConfigKeyStore creates a ConfigKeyStore seeded with the provided keys. Pass nil or an empty slice to start with no pre-loaded keys. Zero-value entries (CreatedAt is zero) are treated as active and assigned the current time.
func (*ConfigKeyStore) CreateKey ¶ added in v1.0.78
func (s *ConfigKeyStore) CreateKey(_ context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
CreateKey generates a new raw key, stores its SHA-256 hash, and returns the raw key once.
func (*ConfigKeyStore) DeleteKey ¶ added in v1.0.78
DeleteKey soft-deletes a key by setting IsActive to false after ownership verification.
func (*ConfigKeyStore) GetUserKeys ¶ added in v1.0.78
func (s *ConfigKeyStore) GetUserKeys(_ context.Context, userID int, keyType KeyType) ([]UserKey, error)
GetUserKeys returns all active, non-expired keys for the given user. Pass an empty KeyType to return all types.
func (*ConfigKeyStore) ValidateKey ¶ added in v1.0.78
func (s *ConfigKeyStore) ValidateKey(_ context.Context, rawKey string, keyType KeyType) (*UserKey, error)
ValidateKey hashes the raw key and finds a matching, active, non-expired entry. Uses constant-time comparison to prevent timing side-channels. Pass an empty KeyType to accept any type.
type ConfigRowSecurityProvider ¶ added in v0.0.63
type ConfigRowSecurityProvider struct {
// contains filtered or unexported fields
}
ConfigRowSecurityProvider provides static row security configuration
func NewConfigRowSecurityProvider ¶ added in v0.0.63
func NewConfigRowSecurityProvider(templates map[string]string, blocked map[string]bool) *ConfigRowSecurityProvider
func (*ConfigRowSecurityProvider) GetRowSecurity ¶ added in v0.0.63
func (p *ConfigRowSecurityProvider) GetRowSecurity(ctx context.Context, userID int, schema, table string) (RowSecurity, error)
type CreateKeyRequest ¶ added in v1.0.78
type CreateKeyRequest struct {
UserID int
KeyType KeyType
Name string
Scopes []string
Meta map[string]any
ExpiresAt *time.Time
}
CreateKeyRequest specifies the parameters for a new key.
type CreateKeyResponse ¶ added in v1.0.78
type CreateKeyResponse struct {
Key UserKey
RawKey string // crypto/rand 32 bytes, base64url-encoded
}
CreateKeyResponse is returned exactly once when a key is created. The caller is responsible for persisting RawKey; it is not stored anywhere.
type DatabaseAuthenticator ¶ added in v0.0.63
type DatabaseAuthenticator struct {
// contains filtered or unexported fields
}
DatabaseAuthenticator provides session-based authentication with database storage All database operations go through stored procedures for security and consistency Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults) See database_schema.sql for procedure definitions Also supports multiple OAuth2 providers configured with WithOAuth2() Also supports passkey authentication configured with WithPasskey()
func NewDatabaseAuthenticator ¶ added in v0.0.63
func NewDatabaseAuthenticator(db *sql.DB) *DatabaseAuthenticator
func NewDatabaseAuthenticatorWithOptions ¶ added in v0.0.86
func NewDatabaseAuthenticatorWithOptions(db *sql.DB, opts DatabaseAuthenticatorOptions) *DatabaseAuthenticator
func NewFacebookAuthenticator ¶ added in v1.0.48
func NewFacebookAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
NewFacebookAuthenticator creates a DatabaseAuthenticator configured for Facebook OAuth2
func NewGitHubAuthenticator ¶ added in v1.0.48
func NewGitHubAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
NewGitHubAuthenticator creates a DatabaseAuthenticator configured for GitHub OAuth2
func NewGoogleAuthenticator ¶ added in v1.0.48
func NewGoogleAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
NewGoogleAuthenticator creates a DatabaseAuthenticator configured for Google OAuth2
func NewMicrosoftAuthenticator ¶ added in v1.0.48
func NewMicrosoftAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator
NewMicrosoftAuthenticator creates a DatabaseAuthenticator configured for Microsoft OAuth2
func NewMultiProviderAuthenticator ¶ added in v1.0.48
func NewMultiProviderAuthenticator(db *sql.DB, configs map[string]OAuth2Config) *DatabaseAuthenticator
NewMultiProviderAuthenticator creates a DatabaseAuthenticator with all major OAuth2 providers configured
func (*DatabaseAuthenticator) Authenticate ¶ added in v0.0.63
func (a *DatabaseAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
func (*DatabaseAuthenticator) BeginPasskeyAuthentication ¶ added in v1.0.48
func (a *DatabaseAuthenticator) BeginPasskeyAuthentication(ctx context.Context, req PasskeyBeginAuthenticationRequest) (*PasskeyAuthenticationOptions, error)
BeginPasskeyAuthentication initiates passkey authentication
func (*DatabaseAuthenticator) BeginPasskeyRegistration ¶ added in v1.0.48
func (a *DatabaseAuthenticator) BeginPasskeyRegistration(ctx context.Context, req PasskeyBeginRegistrationRequest) (*PasskeyRegistrationOptions, error)
BeginPasskeyRegistration initiates passkey registration for a user
func (*DatabaseAuthenticator) ClearCache ¶ added in v0.0.86
func (a *DatabaseAuthenticator) ClearCache(token string) error
ClearCache removes a specific token from the cache or clears all cache if token is empty
func (*DatabaseAuthenticator) ClearUserCache ¶ added in v0.0.86
func (a *DatabaseAuthenticator) ClearUserCache(userID int) error
ClearUserCache removes all cache entries for a specific user ID
func (*DatabaseAuthenticator) CompletePasskeyRegistration ¶ added in v1.0.48
func (a *DatabaseAuthenticator) CompletePasskeyRegistration(ctx context.Context, req PasskeyRegisterRequest) (*PasskeyCredential, error)
CompletePasskeyRegistration completes passkey registration
func (*DatabaseAuthenticator) DeletePasskeyCredential ¶ added in v1.0.48
func (a *DatabaseAuthenticator) DeletePasskeyCredential(ctx context.Context, userID int, credentialID string) error
DeletePasskeyCredential removes a passkey credential
func (*DatabaseAuthenticator) GetPasskeyCredentials ¶ added in v1.0.48
func (a *DatabaseAuthenticator) GetPasskeyCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)
GetPasskeyCredentials returns all passkey credentials for a user
func (*DatabaseAuthenticator) Login ¶ added in v0.0.63
func (a *DatabaseAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*DatabaseAuthenticator) LoginWithPasskey ¶ added in v1.0.48
func (a *DatabaseAuthenticator) LoginWithPasskey(ctx context.Context, req PasskeyLoginRequest) (*LoginResponse, error)
LoginWithPasskey authenticates a user using a passkey and creates a session
func (*DatabaseAuthenticator) Logout ¶ added in v0.0.63
func (a *DatabaseAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
func (*DatabaseAuthenticator) OAuth2GenerateState ¶ added in v1.0.48
func (a *DatabaseAuthenticator) OAuth2GenerateState() (string, error)
OAuth2GenerateState generates a random state string for CSRF protection
func (*DatabaseAuthenticator) OAuth2GetAuthURL ¶ added in v1.0.48
func (a *DatabaseAuthenticator) OAuth2GetAuthURL(providerName, state string) (string, error)
OAuth2GetAuthURL returns the OAuth2 authorization URL for redirecting users
func (*DatabaseAuthenticator) OAuth2GetProviders ¶ added in v1.0.48
func (a *DatabaseAuthenticator) OAuth2GetProviders() []string
OAuth2GetProviders returns list of configured OAuth2 provider names
func (*DatabaseAuthenticator) OAuth2HandleCallback ¶ added in v1.0.48
func (a *DatabaseAuthenticator) OAuth2HandleCallback(ctx context.Context, providerName, code, state string) (*LoginResponse, error)
OAuth2HandleCallback handles the OAuth2 callback and exchanges code for token
func (*DatabaseAuthenticator) OAuth2RefreshToken ¶ added in v1.0.48
func (a *DatabaseAuthenticator) OAuth2RefreshToken(ctx context.Context, refreshToken, providerName string) (*LoginResponse, error)
OAuth2RefreshToken refreshes an expired OAuth2 access token using the refresh token Takes the refresh token and returns a new LoginResponse with updated tokens
func (*DatabaseAuthenticator) OAuthExchangeCode ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthExchangeCode(ctx context.Context, code string) (*OAuthCode, error)
OAuthExchangeCode retrieves and deletes an authorization code (single use).
func (*DatabaseAuthenticator) OAuthGetClient ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthGetClient(ctx context.Context, clientID string) (*OAuthServerClient, error)
OAuthGetClient retrieves a registered client by ID.
func (*DatabaseAuthenticator) OAuthIntrospectToken ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthIntrospectToken(ctx context.Context, token string) (*OAuthTokenInfo, error)
OAuthIntrospectToken validates a token and returns its metadata (RFC 7662).
func (*DatabaseAuthenticator) OAuthRegisterClient ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthRegisterClient(ctx context.Context, client *OAuthServerClient) (*OAuthServerClient, error)
OAuthRegisterClient persists an OAuth2 client registration.
func (*DatabaseAuthenticator) OAuthRevokeToken ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthRevokeToken(ctx context.Context, token string) error
OAuthRevokeToken revokes a token by deleting the session (RFC 7009).
func (*DatabaseAuthenticator) OAuthSaveCode ¶ added in v1.0.78
func (a *DatabaseAuthenticator) OAuthSaveCode(ctx context.Context, code *OAuthCode) error
OAuthSaveCode persists an authorization code.
func (*DatabaseAuthenticator) RefreshToken ¶ added in v0.0.63
func (a *DatabaseAuthenticator) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
RefreshToken implements Refreshable interface
func (*DatabaseAuthenticator) Register ¶ added in v1.0.48
func (a *DatabaseAuthenticator) Register(ctx context.Context, req RegisterRequest) (*LoginResponse, error)
Register implements Registrable interface
func (*DatabaseAuthenticator) UpdatePasskeyCredentialName ¶ added in v1.0.48
func (a *DatabaseAuthenticator) UpdatePasskeyCredentialName(ctx context.Context, userID int, credentialID string, name string) error
UpdatePasskeyCredentialName updates the friendly name of a credential
func (*DatabaseAuthenticator) WithOAuth2 ¶ added in v1.0.48
func (a *DatabaseAuthenticator) WithOAuth2(cfg OAuth2Config) *DatabaseAuthenticator
WithOAuth2 configures OAuth2 support for the DatabaseAuthenticator Can be called multiple times to add multiple OAuth2 providers Returns the same DatabaseAuthenticator instance for method chaining
func (*DatabaseAuthenticator) WithPasskey ¶ added in v1.0.48
func (a *DatabaseAuthenticator) WithPasskey(provider PasskeyProvider) *DatabaseAuthenticator
WithPasskey configures the DatabaseAuthenticator with a passkey provider
type DatabaseAuthenticatorExample ¶ added in v0.0.63
type DatabaseAuthenticatorExample struct {
// contains filtered or unexported fields
}
func NewDatabaseAuthenticatorExample ¶ added in v0.0.63
func NewDatabaseAuthenticatorExample(db *gorm.DB) *DatabaseAuthenticatorExample
func (*DatabaseAuthenticatorExample) Authenticate ¶ added in v0.0.63
func (a *DatabaseAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)
func (*DatabaseAuthenticatorExample) Login ¶ added in v0.0.63
func (a *DatabaseAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*DatabaseAuthenticatorExample) Logout ¶ added in v0.0.63
func (a *DatabaseAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error
func (*DatabaseAuthenticatorExample) RefreshToken ¶ added in v0.0.63
func (a *DatabaseAuthenticatorExample) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
Optional: Implement Refreshable interface
type DatabaseAuthenticatorOptions ¶ added in v0.0.86
type DatabaseAuthenticatorOptions struct {
// CacheTTL is the duration to cache user contexts
// Default: 5 minutes
CacheTTL time.Duration
// Cache is an optional cache instance. If nil, uses the default cache
Cache *cache.Cache
// PasskeyProvider is an optional passkey provider for WebAuthn/FIDO2 authentication
PasskeyProvider PasskeyProvider
// SQLNames provides custom SQL procedure/function names. If nil, uses DefaultSQLNames().
// Partial overrides are supported: only set the fields you want to change.
SQLNames *SQLNames
// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.
// If nil, reconnection is disabled.
DBFactory func() (*sql.DB, error)
}
DatabaseAuthenticatorOptions configures the database authenticator
type DatabaseColumnSecurityProvider ¶ added in v0.0.63
type DatabaseColumnSecurityProvider struct {
// contains filtered or unexported fields
}
DatabaseColumnSecurityProvider loads column security from database All database operations go through stored procedures Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults)
func NewDatabaseColumnSecurityProvider ¶ added in v0.0.63
func NewDatabaseColumnSecurityProvider(db *sql.DB, names ...*SQLNames) *DatabaseColumnSecurityProvider
func (*DatabaseColumnSecurityProvider) GetColumnSecurity ¶ added in v0.0.63
func (p *DatabaseColumnSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
func (*DatabaseColumnSecurityProvider) WithDBFactory ¶ added in v1.0.78
func (p *DatabaseColumnSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseColumnSecurityProvider
type DatabaseKeyStore ¶ added in v1.0.78
type DatabaseKeyStore struct {
// contains filtered or unexported fields
}
DatabaseKeyStore is a KeyStore backed by PostgreSQL stored procedures. All DB operations go through configurable procedure names; the raw key is never passed to the database.
See keystore_schema.sql for the required table and procedure definitions.
Note: DeleteKey invalidates the cache entry for the deleted key. Due to the cache TTL, a deleted key may continue to authenticate for up to CacheTTL (default 2 minutes) if the cache entry cannot be invalidated.
func NewDatabaseKeyStore ¶ added in v1.0.78
func NewDatabaseKeyStore(db *sql.DB, opts ...DatabaseKeyStoreOptions) *DatabaseKeyStore
NewDatabaseKeyStore creates a DatabaseKeyStore with optional configuration.
func (*DatabaseKeyStore) CreateKey ¶ added in v1.0.78
func (ks *DatabaseKeyStore) CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
CreateKey generates a raw key, stores its SHA-256 hash via the create procedure, and returns the raw key once.
func (*DatabaseKeyStore) DeleteKey ¶ added in v1.0.78
DeleteKey soft-deletes a key after verifying ownership and invalidates its cache entry. The delete procedure returns the key_hash so no separate lookup is needed. Note: cache invalidation is best-effort; a cached entry may persist for up to CacheTTL.
func (*DatabaseKeyStore) GetUserKeys ¶ added in v1.0.78
func (ks *DatabaseKeyStore) GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)
GetUserKeys returns all active, non-expired keys for the given user. Pass an empty KeyType to return all types.
func (*DatabaseKeyStore) ValidateKey ¶ added in v1.0.78
func (ks *DatabaseKeyStore) ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)
ValidateKey hashes the raw key and calls the validate procedure. Results are cached for CacheTTL to reduce DB load on hot paths.
type DatabaseKeyStoreOptions ¶ added in v1.0.78
type DatabaseKeyStoreOptions struct {
// Cache is an optional cache instance. If nil, uses the default cache.
Cache *cache.Cache
// CacheTTL is the duration to cache ValidateKey results.
// Default: 2 minutes.
CacheTTL time.Duration
// SQLNames provides custom procedure names. If nil, uses DefaultKeyStoreSQLNames().
SQLNames *KeyStoreSQLNames
// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.
// If nil, reconnection is disabled.
DBFactory func() (*sql.DB, error)
}
DatabaseKeyStoreOptions configures DatabaseKeyStore.
type DatabasePasskeyProvider ¶ added in v1.0.48
type DatabasePasskeyProvider struct {
// contains filtered or unexported fields
}
DatabasePasskeyProvider implements PasskeyProvider using database storage Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults)
func NewDatabasePasskeyProvider ¶ added in v1.0.48
func NewDatabasePasskeyProvider(db *sql.DB, opts DatabasePasskeyProviderOptions) *DatabasePasskeyProvider
NewDatabasePasskeyProvider creates a new database-backed passkey provider
func (*DatabasePasskeyProvider) BeginAuthentication ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) BeginAuthentication(ctx context.Context, username string) (*PasskeyAuthenticationOptions, error)
BeginAuthentication creates authentication options for passkey login
func (*DatabasePasskeyProvider) BeginRegistration ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) BeginRegistration(ctx context.Context, userID int, username, displayName string) (*PasskeyRegistrationOptions, error)
BeginRegistration creates registration options for a new passkey
func (*DatabasePasskeyProvider) CompleteAuthentication ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) CompleteAuthentication(ctx context.Context, response PasskeyAuthenticationResponse, expectedChallenge []byte) (int, error)
CompleteAuthentication verifies a passkey assertion and returns the user ID NOTE: This is a simplified implementation. In production, you should use a WebAuthn library like github.com/go-webauthn/webauthn to properly verify the assertion signature.
func (*DatabasePasskeyProvider) CompleteRegistration ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) CompleteRegistration(ctx context.Context, userID int, response PasskeyRegistrationResponse, expectedChallenge []byte) (*PasskeyCredential, error)
CompleteRegistration verifies and stores a new passkey credential NOTE: This is a simplified implementation. In production, you should use a WebAuthn library like github.com/go-webauthn/webauthn to properly verify attestation and parse credentials.
func (*DatabasePasskeyProvider) DeleteCredential ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) DeleteCredential(ctx context.Context, userID int, credentialID string) error
DeleteCredential removes a passkey credential
func (*DatabasePasskeyProvider) GetCredentials ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) GetCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)
GetCredentials returns all passkey credentials for a user
func (*DatabasePasskeyProvider) UpdateCredentialName ¶ added in v1.0.48
func (p *DatabasePasskeyProvider) UpdateCredentialName(ctx context.Context, userID int, credentialID string, name string) error
UpdateCredentialName updates the friendly name of a credential
type DatabasePasskeyProviderOptions ¶ added in v1.0.48
type DatabasePasskeyProviderOptions struct {
// RPID is the Relying Party ID (typically your domain, e.g., "example.com")
RPID string
// RPName is the display name for your relying party
RPName string
// RPOrigin is the expected origin (e.g., "https://example.com")
RPOrigin string
// Timeout is the timeout for operations in milliseconds (default: 60000)
Timeout int64
// SQLNames provides custom SQL procedure/function names. If nil, uses DefaultSQLNames().
SQLNames *SQLNames
// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.
// If nil, reconnection is disabled.
DBFactory func() (*sql.DB, error)
}
DatabasePasskeyProviderOptions configures the passkey provider
type DatabaseRowSecurityProvider ¶ added in v0.0.63
type DatabaseRowSecurityProvider struct {
// contains filtered or unexported fields
}
DatabaseRowSecurityProvider loads row security from database All database operations go through stored procedures Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults)
func NewDatabaseRowSecurityProvider ¶ added in v0.0.63
func NewDatabaseRowSecurityProvider(db *sql.DB, names ...*SQLNames) *DatabaseRowSecurityProvider
func (*DatabaseRowSecurityProvider) GetRowSecurity ¶ added in v0.0.63
func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userID int, schema, table string) (RowSecurity, error)
func (*DatabaseRowSecurityProvider) WithDBFactory ¶ added in v1.0.78
func (p *DatabaseRowSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseRowSecurityProvider
type DatabaseTwoFactorProvider ¶ added in v1.0.48
type DatabaseTwoFactorProvider struct {
// contains filtered or unexported fields
}
DatabaseTwoFactorProvider implements TwoFactorAuthProvider using PostgreSQL stored procedures Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults) See totp_database_schema.sql for procedure definitions
func NewDatabaseTwoFactorProvider ¶ added in v1.0.48
func NewDatabaseTwoFactorProvider(db *sql.DB, config *TwoFactorConfig, names ...*SQLNames) *DatabaseTwoFactorProvider
NewDatabaseTwoFactorProvider creates a new database-backed 2FA provider
func (*DatabaseTwoFactorProvider) Disable2FA ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Disable2FA(userID int) error
Disable2FA deactivates 2FA for a user
func (*DatabaseTwoFactorProvider) Enable2FA ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Enable2FA(userID int, secret string, backupCodes []string) error
Enable2FA activates 2FA for a user
func (*DatabaseTwoFactorProvider) Generate2FASecret ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)
Generate2FASecret creates a new secret for a user
func (*DatabaseTwoFactorProvider) GenerateBackupCodes ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) GenerateBackupCodes(userID int, count int) ([]string, error)
GenerateBackupCodes creates backup codes for 2FA
func (*DatabaseTwoFactorProvider) Get2FASecret ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Get2FASecret(userID int) (string, error)
Get2FASecret retrieves the user's 2FA secret
func (*DatabaseTwoFactorProvider) Get2FAStatus ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Get2FAStatus(userID int) (bool, error)
Get2FAStatus checks if user has 2FA enabled
func (*DatabaseTwoFactorProvider) Validate2FACode ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) Validate2FACode(secret string, code string) (bool, error)
Validate2FACode verifies a TOTP code
func (*DatabaseTwoFactorProvider) ValidateBackupCode ¶ added in v1.0.48
func (p *DatabaseTwoFactorProvider) ValidateBackupCode(userID int, code string) (bool, error)
ValidateBackupCode checks and consumes a backup code
type HeaderAuthenticator ¶ added in v0.0.63
type HeaderAuthenticator struct{}
HeaderAuthenticator provides simple header-based authentication Expects: X-User-ID, X-User-Name, X-User-Level, X-Session-ID, X-Remote-ID, X-User-Roles, X-User-Email
func NewHeaderAuthenticator ¶ added in v0.0.63
func NewHeaderAuthenticator() *HeaderAuthenticator
func (*HeaderAuthenticator) Authenticate ¶ added in v0.0.63
func (a *HeaderAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
func (*HeaderAuthenticator) Login ¶ added in v0.0.63
func (a *HeaderAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*HeaderAuthenticator) Logout ¶ added in v0.0.63
func (a *HeaderAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
type HeaderAuthenticatorExample ¶ added in v0.0.63
type HeaderAuthenticatorExample struct {
}
func NewHeaderAuthenticatorExample ¶ added in v0.0.63
func NewHeaderAuthenticatorExample() *HeaderAuthenticatorExample
func (*HeaderAuthenticatorExample) Authenticate ¶ added in v0.0.63
func (a *HeaderAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)
func (*HeaderAuthenticatorExample) Login ¶ added in v0.0.63
func (a *HeaderAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*HeaderAuthenticatorExample) Logout ¶ added in v0.0.63
func (a *HeaderAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error
type JWTAuthenticator ¶ added in v0.0.63
type JWTAuthenticator struct {
// contains filtered or unexported fields
}
JWTAuthenticator provides JWT token-based authentication All database operations go through stored procedures Procedure names are configurable via SQLNames (see DefaultSQLNames for defaults) NOTE: JWT signing/verification requires github.com/golang-jwt/jwt/v5 to be installed and imported
func NewJWTAuthenticator ¶ added in v0.0.63
func NewJWTAuthenticator(secretKey string, db *sql.DB, names ...*SQLNames) *JWTAuthenticator
func (*JWTAuthenticator) Authenticate ¶ added in v0.0.63
func (a *JWTAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
func (*JWTAuthenticator) Login ¶ added in v0.0.63
func (a *JWTAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*JWTAuthenticator) Logout ¶ added in v0.0.63
func (a *JWTAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
func (*JWTAuthenticator) WithDBFactory ¶ added in v1.0.78
func (a *JWTAuthenticator) WithDBFactory(factory func() (*sql.DB, error)) *JWTAuthenticator
WithDBFactory configures a factory used to reopen the database connection if it is closed.
type JWTAuthenticatorExample ¶ added in v0.0.63
type JWTAuthenticatorExample struct {
// contains filtered or unexported fields
}
func NewJWTAuthenticatorExample ¶ added in v0.0.63
func NewJWTAuthenticatorExample(secretKey string, db *gorm.DB) *JWTAuthenticatorExample
func (*JWTAuthenticatorExample) Authenticate ¶ added in v0.0.63
func (a *JWTAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)
func (*JWTAuthenticatorExample) Login ¶ added in v0.0.63
func (a *JWTAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*JWTAuthenticatorExample) Logout ¶ added in v0.0.63
func (a *JWTAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error
type KeyStore ¶ added in v1.0.78
type KeyStore interface {
// CreateKey generates a new key, stores its hash, and returns the raw key once.
CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
// GetUserKeys returns all active, non-expired keys for a user.
// Pass an empty KeyType to return all types.
GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)
// DeleteKey soft-deletes a key by ID after verifying ownership.
DeleteKey(ctx context.Context, userID int, keyID int64) error
// ValidateKey checks a raw key, returns the matching UserKey on success.
// The implementation hashes the raw key before any lookup.
// Pass an empty KeyType to accept any type.
ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)
}
KeyStore manages per-user auth keys with pluggable storage backends. Implementations: ConfigKeyStore (static list) and DatabaseKeyStore (stored procedures).
type KeyStoreAuthenticator ¶ added in v1.0.78
type KeyStoreAuthenticator struct {
// contains filtered or unexported fields
}
KeyStoreAuthenticator implements the Authenticator interface using a KeyStore. It is suitable for long-lived application credentials (API keys, JWT secrets, etc.) rather than interactive sessions. Login and Logout are not supported — key lifecycle is managed directly through the KeyStore.
Key extraction order:
- Authorization: Bearer <key>
- Authorization: ApiKey <key>
- X-API-Key header
func NewKeyStoreAuthenticator ¶ added in v1.0.78
func NewKeyStoreAuthenticator(ks KeyStore, keyType KeyType) *KeyStoreAuthenticator
NewKeyStoreAuthenticator creates a KeyStoreAuthenticator. Pass an empty keyType to accept keys of any type.
func (*KeyStoreAuthenticator) Authenticate ¶ added in v1.0.78
func (a *KeyStoreAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
Authenticate extracts an API key from the request and validates it against the KeyStore. Returns a UserContext built from the matching UserKey on success.
func (*KeyStoreAuthenticator) Login ¶ added in v1.0.78
func (a *KeyStoreAuthenticator) Login(_ context.Context, _ LoginRequest) (*LoginResponse, error)
Login is not supported for keystore authentication.
func (*KeyStoreAuthenticator) Logout ¶ added in v1.0.78
func (a *KeyStoreAuthenticator) Logout(_ context.Context, _ LogoutRequest) error
Logout is not supported for keystore authentication.
type KeyStoreSQLNames ¶ added in v1.0.78
type KeyStoreSQLNames struct {
GetUserKeys string // default: "resolvespec_keystore_get_user_keys"
CreateKey string // default: "resolvespec_keystore_create_key"
DeleteKey string // default: "resolvespec_keystore_delete_key"
ValidateKey string // default: "resolvespec_keystore_validate_key"
}
KeyStoreSQLNames holds the configurable stored procedure names used by DatabaseKeyStore. Use DefaultKeyStoreSQLNames() for defaults and MergeKeyStoreSQLNames() for partial overrides.
func DefaultKeyStoreSQLNames ¶ added in v1.0.78
func DefaultKeyStoreSQLNames() *KeyStoreSQLNames
DefaultKeyStoreSQLNames returns a KeyStoreSQLNames with all default resolvespec_keystore_* values.
func MergeKeyStoreSQLNames ¶ added in v1.0.78
func MergeKeyStoreSQLNames(base, override *KeyStoreSQLNames) *KeyStoreSQLNames
MergeKeyStoreSQLNames returns a copy of base with any non-empty fields from override applied. If override is nil, a copy of base is returned.
type KeyType ¶ added in v1.0.78
type KeyType string
KeyType identifies the category of an auth key.
const ( // KeyTypeJWTSecret is a per-user JWT signing secret for token generation. KeyTypeJWTSecret KeyType = "jwt_secret" // KeyTypeHeaderAPI is a static API key sent via a request header. KeyTypeHeaderAPI KeyType = "header_api" // KeyTypeOAuth2 holds OAuth2 client credentials (client_id / client_secret). KeyTypeOAuth2 KeyType = "oauth2" // KeyTypeGenericAPI is a generic application API key. KeyTypeGenericAPI KeyType = "api" )
type LoginRequest ¶ added in v0.0.63
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
TwoFactorCode string `json:"two_factor_code,omitempty"` // TOTP or backup code
Claims map[string]any `json:"claims"` // Additional login data
Meta map[string]any `json:"meta"` // Additional metadata to be set on user context
}
LoginRequest contains credentials for login
type LoginResponse ¶ added in v0.0.63
type LoginResponse struct {
Token string `json:"token"`
RefreshToken string `json:"refresh_token"`
User *UserContext `json:"user"`
ExpiresIn int64 `json:"expires_in"` // Token expiration in seconds
Requires2FA bool `json:"requires_2fa"` // True if 2FA code is required
TwoFactorSetupData *TwoFactorSecret `json:"two_factor_setup,omitempty"` // Present when setting up 2FA
Meta map[string]any `json:"meta"` // Additional metadata to be set on user context
}
LoginResponse contains the result of a login attempt
type LogoutRequest ¶ added in v0.0.63
LogoutRequest contains information for logout
type MemoryTwoFactorProvider ¶ added in v1.0.48
type MemoryTwoFactorProvider struct {
// contains filtered or unexported fields
}
MemoryTwoFactorProvider is an in-memory implementation of TwoFactorAuthProvider for testing/examples
func NewMemoryTwoFactorProvider ¶ added in v1.0.48
func NewMemoryTwoFactorProvider(config *TwoFactorConfig) *MemoryTwoFactorProvider
NewMemoryTwoFactorProvider creates a new in-memory 2FA provider
func (*MemoryTwoFactorProvider) Disable2FA ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Disable2FA(userID int) error
Disable2FA deactivates 2FA for a user
func (*MemoryTwoFactorProvider) Enable2FA ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Enable2FA(userID int, secret string, backupCodes []string) error
Enable2FA activates 2FA for a user
func (*MemoryTwoFactorProvider) Generate2FASecret ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)
Generate2FASecret creates a new secret for a user
func (*MemoryTwoFactorProvider) GenerateBackupCodes ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) GenerateBackupCodes(userID int, count int) ([]string, error)
GenerateBackupCodes creates backup codes for 2FA
func (*MemoryTwoFactorProvider) Get2FASecret ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Get2FASecret(userID int) (string, error)
Get2FASecret retrieves the user's 2FA secret
func (*MemoryTwoFactorProvider) Get2FAStatus ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Get2FAStatus(userID int) (bool, error)
Get2FAStatus checks if user has 2FA enabled
func (*MemoryTwoFactorProvider) Validate2FACode ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) Validate2FACode(secret string, code string) (bool, error)
Validate2FACode verifies a TOTP code
func (*MemoryTwoFactorProvider) ValidateBackupCode ¶ added in v1.0.48
func (m *MemoryTwoFactorProvider) ValidateBackupCode(userID int, code string) (bool, error)
ValidateBackupCode checks and consumes a backup code
type OAuth2Config ¶ added in v1.0.48
type OAuth2Config struct {
ClientID string
ClientSecret string
RedirectURL string
Scopes []string
AuthURL string
TokenURL string
UserInfoURL string
ProviderName string
// Optional: Custom user info parser
// If not provided, will use standard claims (sub, email, name)
UserInfoParser func(userInfo map[string]any) (*UserContext, error)
}
OAuth2Config contains configuration for OAuth2 authentication
type OAuth2Provider ¶ added in v1.0.48
type OAuth2Provider struct {
// contains filtered or unexported fields
}
OAuth2Provider holds configuration and state for a single OAuth2 provider
type OAuthCode ¶ added in v1.0.78
type OAuthCode struct {
Code string `json:"code"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
ClientState string `json:"client_state,omitempty"`
CodeChallenge string `json:"code_challenge"`
CodeChallengeMethod string `json:"code_challenge_method"`
SessionToken string `json:"session_token"`
RefreshToken string `json:"refresh_token,omitempty"`
Scopes []string `json:"scopes,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
}
OAuthCode is a short-lived authorization code.
type OAuthServer ¶ added in v1.0.78
type OAuthServer struct {
// contains filtered or unexported fields
}
OAuthServer implements the MCP-standard OAuth2 authorization server (OAuth 2.1 + PKCE).
It can act as both:
- A direct identity provider using DatabaseAuthenticator username/password login
- A federation layer that delegates authentication to external OAuth2 providers (Google, GitHub, Microsoft, etc.) registered via RegisterExternalProvider
The server exposes these RFC-compliant endpoints:
GET /.well-known/oauth-authorization-server RFC 8414 — server metadata discovery
POST /oauth/register RFC 7591 — dynamic client registration
GET /oauth/authorize OAuth 2.1 + PKCE — start authorization
POST /oauth/authorize Direct login form submission
POST /oauth/token Token exchange and refresh
POST /oauth/revoke RFC 7009 — token revocation
POST /oauth/introspect RFC 7662 — token introspection
GET {ProviderCallbackPath} Internal — external provider callback
func NewOAuthServer ¶ added in v1.0.78
func NewOAuthServer(cfg OAuthServerConfig, auth *DatabaseAuthenticator) *OAuthServer
NewOAuthServer creates a new MCP OAuth2 authorization server.
Pass a DatabaseAuthenticator to enable direct username/password login (the server acts as its own identity provider). Pass nil to use only external providers. External providers are added separately via RegisterExternalProvider.
Call Close() to stop background goroutines when the server is no longer needed.
func (*OAuthServer) Close ¶ added in v1.0.78
func (s *OAuthServer) Close()
Close stops the background goroutines started by NewOAuthServer. It is safe to call Close multiple times.
func (*OAuthServer) HTTPHandler ¶ added in v1.0.78
func (s *OAuthServer) HTTPHandler() http.Handler
HTTPHandler returns an http.Handler that serves all RFC-required OAuth2 endpoints. Mount it at the root of your HTTP server alongside the MCP transport.
mux := http.NewServeMux()
mux.Handle("/", oauthServer.HTTPHandler())
mux.Handle("/mcp/", mcpTransport)
func (*OAuthServer) ProviderCallbackPath ¶ added in v1.0.78
func (s *OAuthServer) ProviderCallbackPath() string
ProviderCallbackPath returns the configured path for external provider callbacks.
func (*OAuthServer) RegisterExternalProvider ¶ added in v1.0.78
func (s *OAuthServer) RegisterExternalProvider(auth *DatabaseAuthenticator, providerName string)
RegisterExternalProvider adds an external OAuth2 provider (Google, GitHub, Microsoft, etc.) that handles user authentication via redirect. The DatabaseAuthenticator must have been configured with WithOAuth2(providerName, ...) before calling this. Multiple providers can be registered; the first is used as the default. All providers must be registered before the server starts serving requests.
type OAuthServerClient ¶ added in v1.0.78
type OAuthServerClient struct {
ClientID string `json:"client_id"`
RedirectURIs []string `json:"redirect_uris"`
ClientName string `json:"client_name,omitempty"`
GrantTypes []string `json:"grant_types"`
AllowedScopes []string `json:"allowed_scopes,omitempty"`
}
OAuthServerClient is a persisted RFC 7591 registered OAuth2 client.
type OAuthServerConfig ¶ added in v1.0.78
type OAuthServerConfig struct {
// Issuer is the public base URL of this server (e.g. "https://api.example.com").
// Used in /.well-known/oauth-authorization-server and to build endpoint URLs.
Issuer string
// ProviderCallbackPath is the path on this server that external OAuth2 providers
// redirect back to. Defaults to "/oauth/provider/callback".
ProviderCallbackPath string
// LoginTitle is shown on the built-in login form when the server acts as its own
// identity provider. Defaults to "Sign in".
LoginTitle string
// PersistClients stores registered clients in the database when a DatabaseAuthenticator is provided.
// Clients registered during a session survive server restarts.
PersistClients bool
// PersistCodes stores authorization codes in the database.
// Useful for multi-instance deployments. Defaults to in-memory.
PersistCodes bool
// DefaultScopes lists scopes advertised in server metadata. Defaults to ["openid","profile","email"].
DefaultScopes []string
// AccessTokenTTL is the issued token lifetime. Defaults to 24h.
AccessTokenTTL time.Duration
// AuthCodeTTL is the auth code lifetime. Defaults to 2 minutes.
AuthCodeTTL time.Duration
}
OAuthServerConfig configures the MCP-standard OAuth2 authorization server.
type OAuthTokenInfo ¶ added in v1.0.78
type OAuthTokenInfo struct {
Active bool `json:"active"`
Sub string `json:"sub,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
UserLevel int `json:"user_level,omitempty"`
Roles []string `json:"roles,omitempty"`
Exp int64 `json:"exp,omitempty"`
Iat int64 `json:"iat,omitempty"`
}
OAuthTokenInfo is the RFC 7662 token introspection response.
type PasskeyAuthenticationOptions ¶ added in v1.0.48
type PasskeyAuthenticationOptions struct {
Challenge []byte `json:"challenge"`
Timeout int64 `json:"timeout,omitempty"`
RelyingPartyID string `json:"rpId,omitempty"`
AllowCredentials []PasskeyCredentialDescriptor `json:"allowCredentials,omitempty"`
UserVerification string `json:"userVerification,omitempty"` // required, preferred, discouraged
Extensions map[string]any `json:"extensions,omitempty"`
}
PasskeyAuthenticationOptions contains options for beginning passkey authentication
type PasskeyAuthenticationResponse ¶ added in v1.0.48
type PasskeyAuthenticationResponse struct {
ID string `json:"id"` // Base64URL encoded credential ID
RawID []byte `json:"rawId"` // Raw credential ID
Type string `json:"type"` // "public-key"
Response PasskeyAuthenticatorAssertionResponse `json:"response"`
ClientExtensionResults map[string]any `json:"clientExtensionResults,omitempty"`
}
PasskeyAuthenticationResponse contains the client's authentication response
func ParsePasskeyAuthenticationResponse ¶ added in v1.0.48
func ParsePasskeyAuthenticationResponse(data []byte) (*PasskeyAuthenticationResponse, error)
ParsePasskeyAuthenticationResponse parses a JSON passkey authentication response
type PasskeyAuthenticatorAssertionResponse ¶ added in v1.0.48
type PasskeyAuthenticatorAssertionResponse struct {
ClientDataJSON []byte `json:"clientDataJSON"`
AuthenticatorData []byte `json:"authenticatorData"`
Signature []byte `json:"signature"`
UserHandle []byte `json:"userHandle,omitempty"`
}
PasskeyAuthenticatorAssertionResponse contains assertion data
type PasskeyAuthenticatorAttestationResponse ¶ added in v1.0.48
type PasskeyAuthenticatorAttestationResponse struct {
ClientDataJSON []byte `json:"clientDataJSON"`
AttestationObject []byte `json:"attestationObject"`
Transports []string `json:"transports,omitempty"`
}
PasskeyAuthenticatorAttestationResponse contains attestation data
type PasskeyAuthenticatorSelection ¶ added in v1.0.48
type PasskeyAuthenticatorSelection struct {
AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"` // platform, cross-platform
RequireResidentKey bool `json:"requireResidentKey,omitempty"`
ResidentKey string `json:"residentKey,omitempty"` // discouraged, preferred, required
UserVerification string `json:"userVerification,omitempty"` // required, preferred, discouraged
}
PasskeyAuthenticatorSelection specifies authenticator requirements
type PasskeyBeginAuthenticationRequest ¶ added in v1.0.48
type PasskeyBeginAuthenticationRequest struct {
Username string `json:"username,omitempty"` // Optional for resident key flow
}
PasskeyBeginAuthenticationRequest contains options for starting passkey authentication
type PasskeyBeginRegistrationRequest ¶ added in v1.0.48
type PasskeyBeginRegistrationRequest struct {
UserID int `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
PasskeyBeginRegistrationRequest contains options for starting passkey registration
type PasskeyCredential ¶ added in v1.0.48
type PasskeyCredential struct {
ID string `json:"id"`
UserID int `json:"user_id"`
CredentialID []byte `json:"credential_id"` // Raw credential ID from authenticator
PublicKey []byte `json:"public_key"` // COSE public key
AttestationType string `json:"attestation_type"` // none, indirect, direct
AAGUID []byte `json:"aaguid"` // Authenticator AAGUID
SignCount uint32 `json:"sign_count"` // Signature counter
CloneWarning bool `json:"clone_warning"` // True if cloning detected
Transports []string `json:"transports,omitempty"` // usb, nfc, ble, internal
BackupEligible bool `json:"backup_eligible"` // Credential can be backed up
BackupState bool `json:"backup_state"` // Credential is currently backed up
Name string `json:"name,omitempty"` // User-friendly name
CreatedAt time.Time `json:"created_at"`
LastUsedAt time.Time `json:"last_used_at"`
}
PasskeyCredential represents a stored WebAuthn/FIDO2 credential
type PasskeyCredentialDescriptor ¶ added in v1.0.48
type PasskeyCredentialDescriptor struct {
Type string `json:"type"` // "public-key"
ID []byte `json:"id"` // Credential ID
Transports []string `json:"transports,omitempty"` // usb, nfc, ble, internal
}
PasskeyCredentialDescriptor describes a credential
type PasskeyCredentialParam ¶ added in v1.0.48
type PasskeyCredentialParam struct {
Type string `json:"type"` // "public-key"
Alg int `json:"alg"` // COSE algorithm identifier (e.g., -7 for ES256, -257 for RS256)
}
PasskeyCredentialParam specifies supported public key algorithm
type PasskeyLoginRequest ¶ added in v1.0.48
type PasskeyLoginRequest struct {
Response PasskeyAuthenticationResponse `json:"response"`
ExpectedChallenge []byte `json:"expected_challenge"`
Claims map[string]any `json:"claims"` // Additional login data
}
PasskeyLoginRequest contains passkey authentication data
type PasskeyProvider ¶ added in v1.0.48
type PasskeyProvider interface {
// BeginRegistration creates registration options for a new passkey
BeginRegistration(ctx context.Context, userID int, username, displayName string) (*PasskeyRegistrationOptions, error)
// CompleteRegistration verifies and stores a new passkey credential
CompleteRegistration(ctx context.Context, userID int, response PasskeyRegistrationResponse, expectedChallenge []byte) (*PasskeyCredential, error)
// BeginAuthentication creates authentication options for passkey login
BeginAuthentication(ctx context.Context, username string) (*PasskeyAuthenticationOptions, error)
// CompleteAuthentication verifies a passkey assertion and returns the user
CompleteAuthentication(ctx context.Context, response PasskeyAuthenticationResponse, expectedChallenge []byte) (int, error)
// GetCredentials returns all passkey credentials for a user
GetCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)
// DeleteCredential removes a passkey credential
DeleteCredential(ctx context.Context, userID int, credentialID string) error
// UpdateCredentialName updates the friendly name of a credential
UpdateCredentialName(ctx context.Context, userID int, credentialID string, name string) error
}
PasskeyProvider handles passkey registration and authentication
type PasskeyRegisterRequest ¶ added in v1.0.48
type PasskeyRegisterRequest struct {
UserID int `json:"user_id"`
Response PasskeyRegistrationResponse `json:"response"`
ExpectedChallenge []byte `json:"expected_challenge"`
CredentialName string `json:"credential_name,omitempty"`
}
PasskeyRegisterRequest contains passkey registration data
type PasskeyRegistrationOptions ¶ added in v1.0.48
type PasskeyRegistrationOptions struct {
Challenge []byte `json:"challenge"`
RelyingParty PasskeyRelyingParty `json:"rp"`
User PasskeyUser `json:"user"`
PubKeyCredParams []PasskeyCredentialParam `json:"pubKeyCredParams"`
Timeout int64 `json:"timeout,omitempty"` // Milliseconds
ExcludeCredentials []PasskeyCredentialDescriptor `json:"excludeCredentials,omitempty"`
AuthenticatorSelection *PasskeyAuthenticatorSelection `json:"authenticatorSelection,omitempty"`
Attestation string `json:"attestation,omitempty"` // none, indirect, direct, enterprise
Extensions map[string]any `json:"extensions,omitempty"`
}
PasskeyRegistrationOptions contains options for beginning passkey registration
type PasskeyRegistrationResponse ¶ added in v1.0.48
type PasskeyRegistrationResponse struct {
ID string `json:"id"` // Base64URL encoded credential ID
RawID []byte `json:"rawId"` // Raw credential ID
Type string `json:"type"` // "public-key"
Response PasskeyAuthenticatorAttestationResponse `json:"response"`
ClientExtensionResults map[string]any `json:"clientExtensionResults,omitempty"`
Transports []string `json:"transports,omitempty"`
}
PasskeyRegistrationResponse contains the client's registration response
func ParsePasskeyRegistrationResponse ¶ added in v1.0.48
func ParsePasskeyRegistrationResponse(data []byte) (*PasskeyRegistrationResponse, error)
ParsePasskeyRegistrationResponse parses a JSON passkey registration response
type PasskeyRelyingParty ¶ added in v1.0.48
type PasskeyRelyingParty struct {
ID string `json:"id"` // Domain (e.g., "example.com")
Name string `json:"name"` // Display name
}
PasskeyRelyingParty identifies the relying party
type PasskeyUser ¶ added in v1.0.48
type PasskeyUser struct {
ID []byte `json:"id"` // User handle (unique, persistent)
Name string `json:"name"` // Username
DisplayName string `json:"displayName"` // Display name
}
PasskeyUser identifies the user
type Refreshable ¶ added in v0.0.63
type Refreshable interface {
// RefreshToken exchanges a refresh token for a new access token
RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
}
Refreshable allows providers to support token refresh
type RegisterRequest ¶ added in v1.0.48
type RegisterRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
UserLevel int `json:"user_level"`
Roles []string `json:"roles"`
Claims map[string]any `json:"claims"` // Additional registration data
Meta map[string]any `json:"meta"` // Additional metadata
}
RegisterRequest contains information for new user registration
type Registrable ¶ added in v1.0.48
type Registrable interface {
// Register creates a new user account
Register(ctx context.Context, req RegisterRequest) (*LoginResponse, error)
}
Registrable allows providers to support user registration
type RowSecurity ¶
type RowSecurity struct {
Schema string `json:"schema"`
Tablename string `json:"tablename"`
Template string `json:"template"`
HasBlock bool `json:"has_block"`
UserID int `json:"user_id"`
}
func (*RowSecurity) GetTemplate ¶
func (m *RowSecurity) GetTemplate(pPrimaryKeyName string, pModelType reflect.Type) string
type RowSecurityProvider ¶ added in v0.0.63
type RowSecurityProvider interface {
// GetRowSecurity loads row security rules for a user and entity
GetRowSecurity(ctx context.Context, userID int, schema, table string) (RowSecurity, error)
}
RowSecurityProvider handles row-level security (filtering)
type SQLNames ¶ added in v1.0.73
type SQLNames struct {
// Auth procedures (DatabaseAuthenticator)
Login string // default: "resolvespec_login"
Register string // default: "resolvespec_register"
Logout string // default: "resolvespec_logout"
Session string // default: "resolvespec_session"
SessionUpdate string // default: "resolvespec_session_update"
RefreshToken string // default: "resolvespec_refresh_token"
// JWT procedures (JWTAuthenticator)
JWTLogin string // default: "resolvespec_jwt_login"
JWTLogout string // default: "resolvespec_jwt_logout"
// Security policy procedures
ColumnSecurity string // default: "resolvespec_column_security"
RowSecurity string // default: "resolvespec_row_security"
// TOTP procedures (DatabaseTwoFactorProvider)
TOTPEnable string // default: "resolvespec_totp_enable"
TOTPDisable string // default: "resolvespec_totp_disable"
TOTPGetStatus string // default: "resolvespec_totp_get_status"
TOTPGetSecret string // default: "resolvespec_totp_get_secret"
TOTPRegenerateBackup string // default: "resolvespec_totp_regenerate_backup_codes"
TOTPValidateBackupCode string // default: "resolvespec_totp_validate_backup_code"
// Passkey procedures (DatabasePasskeyProvider)
PasskeyStoreCredential string // default: "resolvespec_passkey_store_credential"
PasskeyGetCredsByUsername string // default: "resolvespec_passkey_get_credentials_by_username"
PasskeyGetCredential string // default: "resolvespec_passkey_get_credential"
PasskeyUpdateCounter string // default: "resolvespec_passkey_update_counter"
PasskeyGetUserCredentials string // default: "resolvespec_passkey_get_user_credentials"
PasskeyDeleteCredential string // default: "resolvespec_passkey_delete_credential"
PasskeyUpdateName string // default: "resolvespec_passkey_update_name"
PasskeyLogin string // default: "resolvespec_passkey_login"
// OAuth2 procedures (DatabaseAuthenticator OAuth2 methods)
OAuthGetOrCreateUser string // default: "resolvespec_oauth_getorcreateuser"
OAuthCreateSession string // default: "resolvespec_oauth_createsession"
OAuthGetRefreshToken string // default: "resolvespec_oauth_getrefreshtoken"
OAuthUpdateRefreshToken string // default: "resolvespec_oauth_updaterefreshtoken"
OAuthGetUser string // default: "resolvespec_oauth_getuser"
// OAuth2 server procedures (OAuthServer persistence)
OAuthRegisterClient string // default: "resolvespec_oauth_register_client"
OAuthGetClient string // default: "resolvespec_oauth_get_client"
OAuthSaveCode string // default: "resolvespec_oauth_save_code"
OAuthExchangeCode string // default: "resolvespec_oauth_exchange_code"
OAuthIntrospect string // default: "resolvespec_oauth_introspect"
OAuthRevoke string // default: "resolvespec_oauth_revoke"
}
SQLNames defines all configurable SQL stored procedure and table names used by the security package. Override individual fields to remap to custom database objects. Use DefaultSQLNames() for baseline defaults, and MergeSQLNames() to apply partial overrides.
func DefaultSQLNames ¶ added in v1.0.73
func DefaultSQLNames() *SQLNames
DefaultSQLNames returns an SQLNames with all default resolvespec_* values.
func MergeSQLNames ¶ added in v1.0.73
MergeSQLNames returns a copy of base with any non-empty fields from override applied. If override is nil, a copy of base is returned.
type SecurityContext ¶ added in v0.0.67
type SecurityContext interface {
GetContext() context.Context
GetUserID() (int, bool)
GetSchema() string
GetEntity() string
GetModel() interface{}
GetQuery() interface{}
SetQuery(interface{})
GetResult() interface{}
SetResult(interface{})
}
SecurityContext is a generic interface that any spec can implement to integrate with security features This interface abstracts the common security context needs across different specs
type SecurityList ¶
type SecurityList struct {
ColumnSecurityMutex sync.RWMutex
ColumnSecurity map[string][]ColumnSecurity
RowSecurityMutex sync.RWMutex
RowSecurity map[string]RowSecurity
// contains filtered or unexported fields
}
SecurityList manages security state and caching It wraps a SecurityProvider and provides caching and utility methods
func GetSecurityList ¶ added in v0.0.83
func GetSecurityList(ctx context.Context) (*SecurityList, bool)
GetSecurityList extracts the SecurityList from request context
func NewSecurityList ¶ added in v0.0.63
func NewSecurityList(provider SecurityProvider) (*SecurityList, error)
NewSecurityList creates a new security list with the given provider
func (*SecurityList) ApplyColumnSecurity ¶
func (*SecurityList) ClearSecurity ¶
func (m *SecurityList) ClearSecurity(pUserID int, pSchema, pTablename string) error
func (*SecurityList) ColumSecurityApplyOnRecord ¶
func (*SecurityList) GetRowSecurityTemplate ¶
func (m *SecurityList) GetRowSecurityTemplate(pUserID int, pSchema, pTablename string) (RowSecurity, error)
func (*SecurityList) LoadColumnSecurity ¶
func (*SecurityList) LoadRowSecurity ¶
func (m *SecurityList) LoadRowSecurity(ctx context.Context, pUserID int, pSchema, pTablename string, pOverwrite bool) (RowSecurity, error)
func (*SecurityList) Provider ¶ added in v0.0.63
func (m *SecurityList) Provider() SecurityProvider
Provider returns the underlying security provider
type SecurityProvider ¶ added in v0.0.63
type SecurityProvider interface {
Authenticator
ColumnSecurityProvider
RowSecurityProvider
}
SecurityProvider is the main interface combining all security concerns
type SessionCookieOptions ¶ added in v1.0.64
type SessionCookieOptions struct {
// Name is the cookie name. Defaults to "session_token".
Name string
// Path is the cookie path. Defaults to "/".
Path string
// Domain restricts the cookie to a specific domain. Empty means current host.
Domain string
// Secure sets the Secure flag. Defaults to true.
// Set to false only in local development over HTTP.
Secure *bool
// SameSite sets the SameSite policy. Defaults to http.SameSiteLaxMode.
SameSite http.SameSite
}
SessionCookieOptions configures the session cookie set by SetSessionCookie. All fields are optional; sensible secure defaults are applied when omitted.
type TOTPGenerator ¶ added in v1.0.48
type TOTPGenerator struct {
// contains filtered or unexported fields
}
TOTPGenerator handles TOTP code generation and validation
func NewTOTPGenerator ¶ added in v1.0.48
func NewTOTPGenerator(config *TwoFactorConfig) *TOTPGenerator
NewTOTPGenerator creates a new TOTP generator with config
func (*TOTPGenerator) GenerateCode ¶ added in v1.0.48
GenerateCode creates a TOTP code for a given time
func (*TOTPGenerator) GenerateQRCodeURL ¶ added in v1.0.48
func (t *TOTPGenerator) GenerateQRCodeURL(secret, issuer, accountName string) string
GenerateQRCodeURL creates a URL for QR code generation
func (*TOTPGenerator) GenerateSecret ¶ added in v1.0.48
func (t *TOTPGenerator) GenerateSecret() (string, error)
GenerateSecret creates a random base32-encoded secret
func (*TOTPGenerator) ValidateCode ¶ added in v1.0.48
func (t *TOTPGenerator) ValidateCode(secret, code string) (bool, error)
ValidateCode checks if a code is valid for the secret
type TwoFactorAuthProvider ¶ added in v1.0.48
type TwoFactorAuthProvider interface {
// Generate2FASecret creates a new secret for a user
Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)
// Validate2FACode verifies a TOTP code
Validate2FACode(secret string, code string) (bool, error)
// Enable2FA activates 2FA for a user (store secret in your database)
Enable2FA(userID int, secret string, backupCodes []string) error
// Disable2FA deactivates 2FA for a user
Disable2FA(userID int) error
// Get2FAStatus checks if user has 2FA enabled
Get2FAStatus(userID int) (bool, error)
// Get2FASecret retrieves the user's 2FA secret
Get2FASecret(userID int) (string, error)
// GenerateBackupCodes creates backup codes for 2FA
GenerateBackupCodes(userID int, count int) ([]string, error)
// ValidateBackupCode checks and consumes a backup code
ValidateBackupCode(userID int, code string) (bool, error)
}
TwoFactorAuthProvider defines interface for 2FA operations
type TwoFactorAuthenticator ¶ added in v1.0.48
type TwoFactorAuthenticator struct {
// contains filtered or unexported fields
}
TwoFactorAuthenticator wraps an Authenticator and adds 2FA support
func NewTwoFactorAuthenticator ¶ added in v1.0.48
func NewTwoFactorAuthenticator(baseAuth Authenticator, provider TwoFactorAuthProvider, config *TwoFactorConfig) *TwoFactorAuthenticator
NewTwoFactorAuthenticator creates a new 2FA-enabled authenticator
func (*TwoFactorAuthenticator) Authenticate ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
Authenticate delegates to base authenticator
func (*TwoFactorAuthenticator) Disable2FA ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Disable2FA(userID int) error
Disable2FA removes 2FA from a user account
func (*TwoFactorAuthenticator) Enable2FA ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Enable2FA(userID int, secret, verificationCode string) error
Enable2FA completes 2FA setup after user confirms with a valid code
func (*TwoFactorAuthenticator) Login ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
Login authenticates with 2FA support
func (*TwoFactorAuthenticator) Logout ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
Logout delegates to base authenticator
func (*TwoFactorAuthenticator) RegenerateBackupCodes ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) RegenerateBackupCodes(userID int, count int) ([]string, error)
RegenerateBackupCodes creates new backup codes for a user
func (*TwoFactorAuthenticator) Setup2FA ¶ added in v1.0.48
func (t *TwoFactorAuthenticator) Setup2FA(userID int, issuer, accountName string) (*TwoFactorSecret, error)
Setup2FA initiates 2FA setup for a user
type TwoFactorConfig ¶ added in v1.0.48
type TwoFactorConfig struct {
Algorithm string // SHA1, SHA256, SHA512
Digits int // Number of digits in code (6 or 8)
Period int // Time step in seconds (default 30)
SkewWindow int // Number of time steps to check before/after (default 1)
}
TwoFactorConfig holds TOTP configuration
func DefaultTwoFactorConfig ¶ added in v1.0.48
func DefaultTwoFactorConfig() *TwoFactorConfig
DefaultTwoFactorConfig returns standard TOTP configuration
type TwoFactorSecret ¶ added in v1.0.48
type TwoFactorSecret struct {
Secret string `json:"secret"` // Base32 encoded secret
QRCodeURL string `json:"qr_code_url"` // URL for QR code generation
BackupCodes []string `json:"backup_codes"` // One-time backup codes
Issuer string `json:"issuer"` // Application name
AccountName string `json:"account_name"` // User identifier (email/username)
}
TwoFactorSecret contains 2FA setup information
type UserContext ¶ added in v0.0.63
type UserContext struct {
UserID int `json:"user_id"`
UserName string `json:"user_name"`
UserLevel int `json:"user_level"`
SessionID string `json:"session_id"`
SessionRID int64 `json:"session_rid"`
RemoteID string `json:"remote_id"`
Roles []string `json:"roles"`
Email string `json:"email"`
Claims map[string]any `json:"claims"`
Meta map[string]any `json:"meta"` // Additional metadata that can hold any JSON-serializable values
TwoFactorEnabled bool `json:"two_factor_enabled"` // Indicates if 2FA is enabled for this user
}
UserContext holds authenticated user information
func GetUserContext ¶ added in v0.0.63
func GetUserContext(ctx context.Context) (*UserContext, bool)
GetUserContext extracts the full user context from request context
type UserKey ¶ added in v1.0.78
type UserKey struct {
ID int64 `json:"id"`
UserID int `json:"user_id"`
KeyType KeyType `json:"key_type"`
KeyHash string `json:"key_hash"` // SHA-256 hex; never the raw key
Name string `json:"name"`
Scopes []string `json:"scopes,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
IsActive bool `json:"is_active"`
}
UserKey represents a single named auth key belonging to a user. KeyHash stores the SHA-256 hex digest of the raw key; the raw key is never persisted.
Source Files
¶
- composite.go
- examples.go
- examples_funcspec.go
- hooks.go
- interfaces.go
- keystore.go
- keystore_authenticator.go
- keystore_config.go
- keystore_database.go
- keystore_sql_names.go
- middleware.go
- oauth2_examples.go
- oauth2_methods.go
- oauth_server.go
- oauth_server_db.go
- passkey.go
- passkey_examples.go
- passkey_provider.go
- provider.go
- providers.go
- sql_names.go
- totp.go
- totp_middleware.go
- totp_provider_database.go
- totp_provider_memory.go