Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error
- func ApplyRowSecurity(secCtx SecurityContext, securityList *SecurityList) error
- func ApplyTxSettings(secCtx SecurityContext, tx common.Database, settings map[string]string) error
- func ApplyWriteColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error
- func CheckModelAuthAllowed(secCtx SecurityContext, operation string) error
- func CheckModelCreateAllowed(secCtx SecurityContext) 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 ExampleOAuth2FullClient()
- func ExampleOAuth2FullServer()
- func ExampleOAuth2GitHub()
- func ExampleOAuth2Google()
- func ExampleOAuth2Logout()
- func ExampleOAuth2MultiProvider()
- func ExampleOAuth2TokenRefresh()
- 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 IsModelSecurityDisabled(secCtx SecurityContext) 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 PreloadSecurityRules(secCtx SecurityContext, securityList *SecurityList, operation string) error
- func SetSecurityMiddleware(securityList *SecurityList) func(http.Handler) http.Handler
- func SetSessionCookie(w http.ResponseWriter, loginResp *LoginResponse, opts ...SessionCookieOptions)
- func ShouldSkipRowSecurity(secCtx SecurityContext, operation string) bool
- func SkipAuth(ctx context.Context) context.Context
- func StampTxSettings(secCtx SecurityContext, list *SecurityList, tx common.Database) 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 APIKeyLoginable
- type AccessTokenClaims
- type Authenticator
- type CONTEXT_KEY
- type Cacheable
- type ChainAuthenticator
- func (c *ChainAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
- func (c *ChainAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (c *ChainAuthenticator) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
- func (c *ChainAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
- func (c *ChainAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
- func (c *ChainAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
- func (c *ChainAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))
- 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, userRef any, schema, table string) (RowSecurity, error)
- func (c *CompositeSecurityProvider) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) Logout(ctx context.Context, req LogoutRequest) error
- func (c *CompositeSecurityProvider) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
- func (c *CompositeSecurityProvider) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)
- func (c *CompositeSecurityProvider) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))
- func (c *CompositeSecurityProvider) ValidateToken(ctx context.Context, token string) (bool, error)
- 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) Close() error
- func (a *DatabaseAuthenticator) CompletePasskeyRegistration(ctx context.Context, req PasskeyRegisterRequest) (*PasskeyCredential, error)
- func (a *DatabaseAuthenticator) CompletePasswordReset(ctx context.Context, req PasswordResetCompleteRequest) 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) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*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) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
- func (a *DatabaseAuthenticator) OAuth2GenerateState() (string, error)
- func (a *DatabaseAuthenticator) OAuth2GetAuthURL(providerName, state string) (string, error)
- func (a *DatabaseAuthenticator) OAuth2GetAuthURLWithOptions(providerName, state string, opts OAuth2AuthOptions) (string, error)
- func (a *DatabaseAuthenticator) OAuth2GetProviders() []string
- func (a *DatabaseAuthenticator) OAuth2HandleCallback(ctx context.Context, providerName, code, state string) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) OAuth2HandleCallbackRequest(ctx context.Context, providerName string, r *http.Request) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) OAuth2LogoutURL(ctx context.Context, ...) (string, error)
- func (a *DatabaseAuthenticator) OAuth2RefreshToken(ctx context.Context, refreshToken, providerName string) (*LoginResponse, error)
- func (a *DatabaseAuthenticator) OAuthDeleteClient(ctx context.Context, clientID string) 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) OAuthGetUser(ctx context.Context, userID int) (*UserContext, error)
- func (a *DatabaseAuthenticator) OAuthGrants() lookup.OAuthGrantStore
- 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) OAuthUpdateClient(ctx context.Context, client *OAuthServerClient) 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) RequestPasswordReset(ctx context.Context, req PasswordResetRequest) (*PasswordResetResponse, error)
- func (a *DatabaseAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, 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) WithOIDC(ctx context.Context, cfg OIDCConfig) (*DatabaseAuthenticator, error)
- 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
- func (p *DatabaseColumnSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)
- func (p *DatabaseColumnSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseColumnSecurityProvider
- func (p *DatabaseColumnSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseColumnSecurityProvider
- func (p *DatabaseColumnSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseColumnSecurityProvider
- func (p *DatabaseColumnSecurityProvider) WithNoGroupTables() *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
- func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)
- func (p *DatabaseRowSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseRowSecurityProvider
- func (p *DatabaseRowSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseRowSecurityProvider
- func (p *DatabaseRowSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseRowSecurityProvider
- func (p *DatabaseRowSecurityProvider) WithNoGroupTables() *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)
- func (p *DatabaseTwoFactorProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseTwoFactorProvider
- func (p *DatabaseTwoFactorProvider) WithLookup(cfg lookup.Config) *DatabaseTwoFactorProvider
- func (p *DatabaseTwoFactorProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseTwoFactorProvider
- 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) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
- func (a *JWTAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
- func (a *JWTAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
- func (a *JWTAuthenticator) WithDBFactory(factory func() (*sql.DB, error)) *JWTAuthenticator
- func (a *JWTAuthenticator) WithLookup(cfg lookup.Config) *JWTAuthenticator
- func (a *JWTAuthenticator) WithLookupProvider(p *lookup.Provider) *JWTAuthenticator
- func (a *JWTAuthenticator) WithPasswordHashUpgrade(enabled bool) *JWTAuthenticator
- type JWTAuthenticatorExample
- type KeyStore
- type KeyType
- type LoginRequest
- type LoginResponse
- type LogoutRequest
- type OAuth2AuthOptions
- type OAuth2Config
- type OAuth2Provider
- type OAuthClaimsProvider
- type OAuthClaimsRequest
- type OAuthCode
- type OAuthConsentPage
- type OAuthLoginPage
- type OAuthSSOCookieConfig
- type OAuthScopeInfo
- type OAuthServer
- func (s *OAuthServer) Close()
- func (s *OAuthServer) HTTPHandler() http.Handler
- func (s *OAuthServer) ProviderCallbackPath() string
- func (s *OAuthServer) RegisterExternalProvider(auth *DatabaseAuthenticator, providerName string)
- func (s *OAuthServer) RegisterTrustedClient(ctx context.Context, c OAuthServerClient) (registered *OAuthServerClient, plainSecret string, err error)
- func (s *OAuthServer) VerifyAccessToken(ctx context.Context, token string, opts VerifyAccessTokenOptions) (*AccessTokenClaims, error)
- type OAuthServerClient
- type OAuthServerConfig
- type OAuthSigningKey
- type OAuthTokenInfo
- type OIDCConfig
- 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 PasswordResetCompleteRequest
- type PasswordResetRequest
- type PasswordResetResponse
- type PasswordResettable
- type Refreshable
- type RegisterRequest
- type Registrable
- type RowSecurity
- type RowSecurityProvider
- type SecurityContext
- type SecurityList
- func (m *SecurityList) ApplyColumnSecurity(records reflect.Value, modelType reflect.Type, pUserID int, ...) (out reflect.Value, err 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(pUserRef any, pSchema, pTablename string) (out RowSecurity, err error)
- func (m *SecurityList) LoadColumnSecurity(ctx context.Context, pUserID int, pSchema, pTablename string, pOverwrite bool) error
- func (m *SecurityList) LoadRowSecurity(ctx context.Context, pUserRef any, pSchema, pTablename string, pOverwrite bool) (RowSecurity, error)
- func (m *SecurityList) Provider() SecurityProvider
- func (m *SecurityList) SetTxSettings(fn TxSettingsFunc)
- func (m *SecurityList) TxSettings() TxSettingsFunc
- type SecurityProvider
- type SessionCookieOptions
- type TwoFactorSecret
- type TxSettingsFunc
- type UserContext
- type UserKey
- type Validatable
- type VerifyAccessTokenOptions
- type WriteDataContext
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" )
const ( KeyTypeJWTSecret = sectypes.KeyTypeJWTSecret KeyTypeHeaderAPI = sectypes.KeyTypeHeaderAPI KeyTypeOAuth2 = sectypes.KeyTypeOAuth2 KeyTypeGenericAPI = sectypes.KeyTypeGenericAPI )
Variables ¶
var ErrNoColumnSecurity = errors.New("no column security data")
ErrNoColumnSecurity is the column-security equivalent of ErrNoRowSecurity.
var ErrNoRowSecurity = errors.New("no row security data")
ErrNoRowSecurity is returned by GetRowSecurityTemplate when no row security entry is loaded for the user and table. It means "no rules", as opposed to a failure, which callers must treat as fatal.
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 ApplyTxSettings ¶ added in v1.2.7
ApplyTxSettings sets each entry as a transaction-local setting on tx, in name order. Postgres only; any other driver with a non-empty map is an error so a missing RLS stamp fails closed. The SQL lives in lookup.ApplyTxSettings.
func ApplyWriteColumnSecurity ¶ added in v1.2.7
func ApplyWriteColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error
ApplyWriteColumnSecurity removes columns the user may not see (column security "hide" or "mask") from the create/update payload in place, so a hidden or masked column can never be written. It only reads the rules cache (see PreloadSecurityRules) and never queries the provider, so it is safe inside the transaction. Models with security disabled are skipped. Without a loaded rule set for a known user it fails closed.
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 CheckModelCreateAllowed ¶ added in v1.2.12
func CheckModelCreateAllowed(secCtx SecurityContext) error
CheckModelCreateAllowed returns an error if CanCreate is false for the model. Rules are read from context with a fallback to the model registry; an unregistered model is allowed.
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 ExampleOAuth2FullClient ¶ added in v1.2.12
func ExampleOAuth2FullClient()
ExampleOAuth2FullClient is the relying-party side: log users in with any OpenID Connect provider (including the server above). Discovery, PKCE, nonce and id_token validation are automatic.
func ExampleOAuth2FullServer ¶ added in v1.2.12
func ExampleOAuth2FullServer()
ExampleOAuth2FullServer runs a complete OAuth 2.1 / OpenID Connect provider: login, consent, rotating refresh tokens, JWT access tokens, DPoP, PAR, the device grant and token exchange. OAUTH2_SERVER.md walks through every endpoint.
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 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 IsModelSecurityDisabled ¶ added in v1.1.49
func IsModelSecurityDisabled(secCtx SecurityContext) bool
IsModelSecurityDisabled reports whether all model-level security processing is disabled for the model. This is distinct from ShouldSkipRowSecurity: CanPublicRead skips row filtering for reads but must still allow other read security, such as column masking, to be loaded.
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 PreloadSecurityRules ¶ added in v1.2.7
func PreloadSecurityRules(secCtx SecurityContext, securityList *SecurityList, operation string) error
PreloadSecurityRules loads column/row security rules into the SecurityList cache for read operations. Call it from a BeforeHandle hook, i.e. before the handler opens its transaction, so the provider queries do not need a second pooled connection while the transaction holds one. Later LoadSecurityRules calls in the same request are then cache hits. Reads load column and row rules; create/update load the column rules that ApplyWriteColumnSecurity reads. Other operations and models with security disabled are skipped.
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 ShouldSkipRowSecurity ¶ added in v1.1.49
func ShouldSkipRowSecurity(secCtx SecurityContext, operation string) bool
ShouldSkipRowSecurity reports whether row-security enforcement should be skipped for the operation. It uses the same model-rule resolution as CheckModelAuthAllowed so the model registry remains the single source of truth for security behavior.
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 StampTxSettings ¶ added in v1.2.7
func StampTxSettings(secCtx SecurityContext, list *SecurityList, tx common.Database) error
StampTxSettings runs the list's TxSettingsFunc and applies the result to tx as transaction-local settings (set_config(name, value, true)). No-op when no function is configured or it returns no settings. tx must be the transaction itself, never the pool: the settings are lost on any other connection.
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 APIKeyLoginable ¶ added in v1.2.12
type APIKeyLoginable interface {
// LoginWithAPIKey validates the raw API key and creates a session for its user.
// Unknown, expired and inactive keys all yield the same generic error.
LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
}
APIKeyLoginable allows providers to exchange a raw API key for a session.
type AccessTokenClaims ¶ added in v1.2.12
type AccessTokenClaims struct {
Subject string
UserID int
ClientID string
Scopes []string
Audience []string
JTI string
SessionID string
ExpiresAt time.Time
// DPoPKey is the thumbprint of the key the token is bound to, or "".
DPoPKey string
// JWT is true for RFC 9068 JWT access tokens.
JWT bool
}
AccessTokenClaims describes a verified access token.
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)
// LoginWithCookie authenticates credentials and, when cookie sessions are enabled,
// writes the session cookie to w. Implementations that do not support cookies
// should delegate to Login and ignore w.
LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
// Logout invalidates a user's session/token
Logout(ctx context.Context, req LogoutRequest) error
// LogoutWithCookie invalidates a user's session/token and, when cookie sessions are
// enabled, clears the session cookie on w. Implementations that do not support cookies
// should delegate to Logout and ignore w.
LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
// Authenticate extracts and validates user from HTTP request
// Returns UserContext or error if authentication fails
Authenticate(r *http.Request) (*UserContext, error)
// SetAuthenticateCallback registers a fallback called when primary authentication fails.
// If the callback returns a non-nil UserContext, that result is used instead of the error.
SetAuthenticateCallback(fn func(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 ChainAuthenticator ¶ added in v1.0.108
type ChainAuthenticator struct {
// contains filtered or unexported fields
}
ChainAuthenticator tries each authenticator in order, returning the first success. Login and Logout are delegated to the primary authenticator.
func NewChainAuthenticator ¶ added in v1.0.108
func NewChainAuthenticator(primary Authenticator, rest ...Authenticator) *ChainAuthenticator
NewChainAuthenticator creates a ChainAuthenticator from the given authenticators. At least one authenticator is required; the first is treated as primary for Login/Logout.
func (*ChainAuthenticator) Authenticate ¶ added in v1.0.108
func (c *ChainAuthenticator) Authenticate(r *http.Request) (*UserContext, error)
func (*ChainAuthenticator) Login ¶ added in v1.0.108
func (c *ChainAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
func (*ChainAuthenticator) LoginWithAPIKey ¶ added in v1.2.12
func (c *ChainAuthenticator) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
LoginWithAPIKey tries each authenticator that supports API key login and returns the first success. Failures collapse to one generic error.
func (*ChainAuthenticator) LoginWithCookie ¶ added in v1.0.112
func (c *ChainAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
func (*ChainAuthenticator) Logout ¶ added in v1.0.108
func (c *ChainAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
func (*ChainAuthenticator) LogoutWithCookie ¶ added in v1.0.112
func (c *ChainAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
func (*ChainAuthenticator) SetAuthenticateCallback ¶ added in v1.0.112
func (c *ChainAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))
type ColumnSecurity ¶
type ColumnSecurity = sectypes.ColumnSecurity
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, userRef any, 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) LoginWithAPIKey ¶ added in v1.2.12
func (c *CompositeSecurityProvider) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
LoginWithAPIKey implements APIKeyLoginable if the authenticator supports it
func (*CompositeSecurityProvider) LoginWithCookie ¶ added in v1.0.110
func (c *CompositeSecurityProvider) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
LoginWithCookie 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) LogoutWithCookie ¶ added in v1.0.110
func (c *CompositeSecurityProvider) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
LogoutWithCookie 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) SetAuthenticateCallback ¶ added in v1.0.112
func (c *CompositeSecurityProvider) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))
SetAuthenticateCallback delegates to the authenticator
func (*CompositeSecurityProvider) ValidateToken ¶ added in v0.0.63
ValidateToken implements Validatable if the authenticator supports it
type CreateKeyRequest ¶ added in v1.0.78
type CreateKeyRequest = sectypes.CreateKeyRequest
type CreateKeyResponse ¶ added in v1.0.78
type CreateKeyResponse = sectypes.CreateKeyResponse
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 and modes are configured through lookup.Config (see lookup.DefaultProcNames) See lookup/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) Close ¶ added in v1.2.0
func (a *DatabaseAuthenticator) Close() error
Close stops the background OAuth2 state cleanup goroutines and waits for in-flight session activity updates. It is safe to call more than once.
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) CompletePasswordReset ¶ added in v1.0.85
func (a *DatabaseAuthenticator) CompletePasswordReset(ctx context.Context, req PasswordResetCompleteRequest) error
CompletePasswordReset implements PasswordResettable. It validates the token and updates the user's password via resolvespec_password_reset.
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) LoginWithAPIKey ¶ added in v1.2.12
func (a *DatabaseAuthenticator) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)
LoginWithAPIKey implements APIKeyLoginable. It validates a raw header/generic API key and creates a session for the key's user. Unknown, expired and inactive keys all return errInvalidAPIKey; the raw key is never logged. Procedure-only: the key and user lookup live in resolvespec_login_api_key so the underlying schema can differ per database; there is no direct-SQL path.
func (*DatabaseAuthenticator) LoginWithCookie ¶ added in v1.0.109
func (a *DatabaseAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
LoginWithCookie performs a login and, when EnableCookieSession is true, writes the session cookie to w using the configured CookieOptions. The LoginResponse is returned regardless of whether cookie sessions are enabled.
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) LogoutWithCookie ¶ added in v1.0.109
func (a *DatabaseAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error
LogoutWithCookie performs a logout and, when EnableCookieSession is true, clears the session cookie on w. The logout itself is performed regardless of the cookie flag.
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) OAuth2GetAuthURLWithOptions ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuth2GetAuthURLWithOptions(providerName, state string, opts OAuth2AuthOptions) (string, error)
OAuth2GetAuthURLWithOptions is OAuth2GetAuthURL with OpenID Connect request parameters. For an OIDC provider (and with UsePKCE) it also creates the PKCE verifier and the nonce, which are kept with the state until the callback.
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) OAuth2HandleCallbackRequest ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuth2HandleCallbackRequest(ctx context.Context, providerName string, r *http.Request) (*LoginResponse, error)
OAuth2HandleCallbackRequest is OAuth2HandleCallback for the redirect request itself. Besides code and state it honours the error parameters and the RFC 9207 "iss" parameter, which protects against mix-up attacks when several providers are in use.
func (*DatabaseAuthenticator) OAuth2LogoutURL ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuth2LogoutURL(ctx context.Context, providerName, idTokenHint, postLogoutRedirect, state string) (string, error)
OAuth2LogoutURL returns the provider's RP-initiated logout URL (OIDC RP-Initiated Logout 1.0). idTokenHint is LoginResponse.Meta["id_token"]. It fails when the provider has no end_session_endpoint.
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) OAuthDeleteClient ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuthDeleteClient(ctx context.Context, clientID string) error
OAuthDeleteClient deactivates a registered client (RFC 7592).
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) OAuthGetUser ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuthGetUser(ctx context.Context, userID int) (*UserContext, error)
OAuthGetUser returns the active user with the given id.
func (*DatabaseAuthenticator) OAuthGrants ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuthGrants() lookup.OAuthGrantStore
OAuthGrants returns the store holding consents, managed refresh tokens, device codes, pushed authorization requests and the replay cache.
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) OAuthUpdateClient ¶ added in v1.2.12
func (a *DatabaseAuthenticator) OAuthUpdateClient(ctx context.Context, client *OAuthServerClient) error
OAuthUpdateClient replaces the registered metadata of a client (RFC 7592).
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) RequestPasswordReset ¶ added in v1.0.85
func (a *DatabaseAuthenticator) RequestPasswordReset(ctx context.Context, req PasswordResetRequest) (*PasswordResetResponse, error)
RequestPasswordReset implements PasswordResettable. It calls the stored procedure resolvespec_password_reset_request and returns the reset token and expiry.
func (*DatabaseAuthenticator) SetAuthenticateCallback ¶ added in v1.0.112
func (a *DatabaseAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))
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) WithOIDC ¶ added in v1.2.12
func (a *DatabaseAuthenticator) WithOIDC(ctx context.Context, cfg OIDCConfig) (*DatabaseAuthenticator, error)
WithOIDC registers an OpenID Connect provider. The endpoints come from the issuer's discovery document. Login uses PKCE and a nonce, and the id_token is validated on callback and refresh.
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
// Lookup selects dialect, query mode and procedure/table/column names.
// The zero value uses stored procedures on Postgres and direct SQL elsewhere.
Lookup lookup.Config
// LookupProvider, when set, is used instead of building one from Lookup and the db.
LookupProvider *lookup.Provider
// 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)
// EnableCookieSession enables cookie-based session management.
// When true, Authenticate reads the session token from the cookie named by
// CookieOptions.Name (default "session_token") in addition to the Authorization header,
// and LoginWithCookie / LogoutWithCookie automatically set / clear the cookie.
EnableCookieSession bool
// UpgradePasswordHash, when true, rewrites a legacy cleartext password as a
// bcrypt hash after a successful login. It is off by default and is never
// enabled automatically: legacy cleartext values are still accepted at login,
// but stored rows are left untouched unless this is set.
UpgradePasswordHash bool
// CookieOptions configures the session cookie written by LoginWithCookie.
// Only used when EnableCookieSession is true.
CookieOptions SessionCookieOptions
// AuthenticateCallback is a fallback called when the primary authentication (database
// session lookup) fails. If non-nil and the callback returns a non-nil UserContext,
// that result is used in place of the failure.
AuthenticateCallback func(r *http.Request) (*UserContext, 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 through the lookup package (stored procedure on Postgres by default, direct SQL elsewhere).
func NewDatabaseColumnSecurityProvider ¶ added in v0.0.63
func NewDatabaseColumnSecurityProvider(db *sql.DB) *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
func (*DatabaseColumnSecurityProvider) WithLookup ¶ added in v1.2.12
func (p *DatabaseColumnSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseColumnSecurityProvider
WithLookup configures dialect, query mode and names. Call before first use.
func (*DatabaseColumnSecurityProvider) WithLookupProvider ¶ added in v1.2.12
func (p *DatabaseColumnSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseColumnSecurityProvider
WithLookupProvider uses an existing provider instead of building one.
func (*DatabaseColumnSecurityProvider) WithNoGroupTables ¶ added in v1.2.12
func (p *DatabaseColumnSecurityProvider) WithNoGroupTables() *DatabaseColumnSecurityProvider
WithNoGroupTables skips group membership when loading rules in direct mode.
type DatabaseKeyStore ¶ added in v1.0.78
type DatabaseKeyStore struct {
// contains filtered or unexported fields
}
DatabaseKeyStore is a KeyStore backed by the lookup package (stored procedures on Postgres by default, direct SQL elsewhere). The raw key is never passed to the database.
See lookup/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
// Lookup selects dialect, query mode and procedure/table/column names.
// The zero value uses stored procedures on Postgres and direct SQL elsewhere.
Lookup lookup.Config
// LookupProvider, when set, is used instead of building one from Lookup and the db.
LookupProvider *lookup.Provider
// 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 on top of the lookup package (stored procedures on Postgres by default, direct SQL elsewhere).
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
// Lookup selects dialect, query mode and procedure/table/column names.
Lookup lookup.Config
// LookupProvider, when set, is used instead of building one from Lookup and the db.
LookupProvider *lookup.Provider
// 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 through the lookup package (stored procedure on Postgres by default, direct SQL elsewhere).
func NewDatabaseRowSecurityProvider ¶ added in v0.0.63
func NewDatabaseRowSecurityProvider(db *sql.DB) *DatabaseRowSecurityProvider
func (*DatabaseRowSecurityProvider) GetRowSecurity ¶ added in v0.0.63
func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)
func (*DatabaseRowSecurityProvider) WithDBFactory ¶ added in v1.0.78
func (p *DatabaseRowSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseRowSecurityProvider
func (*DatabaseRowSecurityProvider) WithLookup ¶ added in v1.2.12
func (p *DatabaseRowSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseRowSecurityProvider
WithLookup configures dialect, query mode and names. Call before first use.
func (*DatabaseRowSecurityProvider) WithLookupProvider ¶ added in v1.2.12
func (p *DatabaseRowSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseRowSecurityProvider
WithLookupProvider uses an existing provider instead of building one.
func (*DatabaseRowSecurityProvider) WithNoGroupTables ¶ added in v1.2.12
func (p *DatabaseRowSecurityProvider) WithNoGroupTables() *DatabaseRowSecurityProvider
WithNoGroupTables skips group membership when loading rules in direct mode.
type DatabaseTwoFactorProvider ¶ added in v1.0.48
type DatabaseTwoFactorProvider struct {
// contains filtered or unexported fields
}
DatabaseTwoFactorProvider implements TwoFactorAuthProvider on top of the lookup package (stored procedures on Postgres by default, direct SQL elsewhere). See lookup/database_schema.sql for procedure definitions
func NewDatabaseTwoFactorProvider ¶ added in v1.0.48
func NewDatabaseTwoFactorProvider(db *sql.DB, config *totp.Config) *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
func (*DatabaseTwoFactorProvider) WithDBFactory ¶ added in v1.1.25
func (p *DatabaseTwoFactorProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseTwoFactorProvider
WithDBFactory configures a factory used to reopen the database connection if it is closed.
func (*DatabaseTwoFactorProvider) WithLookup ¶ added in v1.2.12
func (p *DatabaseTwoFactorProvider) WithLookup(cfg lookup.Config) *DatabaseTwoFactorProvider
WithLookup configures dialect, query mode and names. Call before first use.
func (*DatabaseTwoFactorProvider) WithLookupProvider ¶ added in v1.2.12
func (p *DatabaseTwoFactorProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseTwoFactorProvider
WithLookupProvider uses an existing provider instead of building one.
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 and modes are configured through lookup.Config (see lookup.DefaultProcNames) 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) *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) LoginWithCookie ¶ added in v1.0.110
func (a *JWTAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)
func (*JWTAuthenticator) Logout ¶ added in v0.0.63
func (a *JWTAuthenticator) Logout(ctx context.Context, req LogoutRequest) error
func (*JWTAuthenticator) LogoutWithCookie ¶ added in v1.0.110
func (a *JWTAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) 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.
func (*JWTAuthenticator) WithLookup ¶ added in v1.2.12
func (a *JWTAuthenticator) WithLookup(cfg lookup.Config) *JWTAuthenticator
WithLookup configures dialect, query mode and names. Call before first use.
func (*JWTAuthenticator) WithLookupProvider ¶ added in v1.2.12
func (a *JWTAuthenticator) WithLookupProvider(p *lookup.Provider) *JWTAuthenticator
WithLookupProvider uses an existing provider instead of building one.
func (*JWTAuthenticator) WithPasswordHashUpgrade ¶ added in v1.2.0
func (a *JWTAuthenticator) WithPasswordHashUpgrade(enabled bool) *JWTAuthenticator
WithPasswordHashUpgrade explicitly enables (or disables) upgrading legacy cleartext passwords to bcrypt after a successful login. Off by default.
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 LoginRequest ¶ added in v0.0.63
type LoginRequest = sectypes.LoginRequest
type LoginResponse ¶ added in v0.0.63
type LoginResponse = sectypes.LoginResponse
type LogoutRequest ¶ added in v0.0.63
type LogoutRequest = sectypes.LogoutRequest
type OAuth2AuthOptions ¶ added in v1.2.12
type OAuth2AuthOptions struct {
LoginHint string
Prompt string // none, login, consent, select_account
MaxAge *int
ACRValues string
Extra map[string]string
}
OAuth2AuthOptions are optional OpenID Connect authentication request parameters.
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)
// Issuer turns the provider into an OpenID Connect provider: PKCE and a nonce are used and
// the id_token returned by the token endpoint is validated (signature, iss, aud, exp, nonce,
// at_hash). WithOIDC fills the endpoints in by discovery; with WithOAuth2 set JWKSURL
// as well. UserInfoURL stays optional: the id_token claims are used when it is empty.
Issuer string
// JWKSURL is the provider's key set. Only needed with WithOAuth2; WithOIDC discovers it.
JWKSURL string
// EndSessionURL is the provider's RP-initiated logout endpoint (discovered by WithOIDC).
EndSessionURL string
// UsePKCE sends a PKCE S256 challenge for a provider that is not OIDC. It is always on in OIDC mode.
UsePKCE bool
// AllowedAlgs lists the id_token signature algorithms to accept. Default: RS256, PS256, ES256, ES384.
AllowedAlgs []string
// AuthStyle selects how the client authenticates at the token endpoint: "basic", "post" or ""
// (try basic, fall back to post).
AuthStyle string
// HTTPClient is used for discovery, JWKS, token and userinfo requests.
HTTPClient *http.Client
// ClockSkew tolerates clock differences when validating the id_token. Default 1 minute.
ClockSkew time.Duration
}
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 OAuthClaimsProvider ¶ added in v1.2.12
OAuthClaimsProvider returns the claims for a user. The server only includes the standard claims the granted scopes entitle the client to (profile, email, address, phone) plus every claim the client requested explicitly; claims outside those sets are dropped.
type OAuthClaimsRequest ¶ added in v1.2.12
type OAuthClaimsRequest struct {
UserID int
Sub string
Scopes []string
// Requested holds the names the client asked for individually through the OIDC "claims"
// request parameter for this destination.
Requested []string
// Destination is "id_token" or "userinfo".
Destination string
// Base are the claims the server already knows (sub, preferred_username, email).
Base map[string]any
}
OAuthClaimsRequest is the input of an OAuthClaimsProvider.
type OAuthConsentPage ¶ added in v1.2.12
type OAuthConsentPage struct {
Title string
Action string
State string // opaque, must be posted back as the "req" field
ClientName string
ClientURI string
LogoURI string
Scopes []OAuthScopeInfo
User string
Hidden map[string]string
}
OAuthConsentPage is the data of the consent page template.
type OAuthLoginPage ¶ added in v1.2.12
type OAuthLoginPage struct {
Title string
Error string
Action string // form action
State string // opaque, must be posted back as the "req" field
ClientName string
LoginHint string
// Extra hidden fields to post back (device flow).
Hidden map[string]string
}
OAuthLoginPage is the data of the login page template.
type OAuthSSOCookieConfig ¶ added in v1.2.12
type OAuthSSOCookieConfig struct {
Name string // default "resolvespec_sso"
Path string // default "/"
TTL time.Duration // default 8h
SameSite http.SameSite // default Lax
// Insecure sends the cookie over plain HTTP. By default Secure is on whenever Issuer is https.
Insecure bool
Disable bool // never set a cookie: every authorization request authenticates again
}
OAuthSSOCookieConfig configures the SSO cookie.
type OAuthScopeInfo ¶ added in v1.2.12
OAuthScopeInfo is one line of the consent screen.
type OAuthServer ¶ added in v1.0.78
type OAuthServer struct {
// contains filtered or unexported fields
}
OAuthServer is an OAuth 2.1 authorization server and OpenID Connect provider.
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
Endpoints (see OAUTH2_SERVER.md for parameters and examples):
GET /.well-known/oauth-authorization-server RFC 8414 server metadata
GET /.well-known/openid-configuration OIDC Discovery
GET /.well-known/oauth-protected-resource RFC 9728 protected resource metadata
POST /oauth/register RFC 7591 dynamic client registration
GET|PUT|DELETE /oauth/register/{client_id} RFC 7592 client management
GET|POST /oauth/authorize authorization endpoint (PKCE S256 required)
POST /oauth/token authorization_code, refresh_token, client_credentials,
device_code and token-exchange grants
POST /oauth/par RFC 9126 pushed authorization requests
POST /oauth/device_authorization RFC 8628 device authorization
GET|POST /oauth/device device verification page
POST /oauth/revoke RFC 7009 token revocation
POST /oauth/introspect RFC 7662 token introspection
GET|POST /oauth/userinfo OIDC UserInfo
GET /oauth/jwks.json JWKS
GET|POST /oauth/logout OIDC RP-initiated logout
GET {ProviderCallbackPath} external provider callback
func NewOAuthServer ¶ added in v1.0.78
func NewOAuthServer(cfg OAuthServerConfig, auth *DatabaseAuthenticator) *OAuthServer
NewOAuthServer creates a new OAuth2 / OIDC 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.
func (*OAuthServer) RegisterTrustedClient ¶ added in v1.2.12
func (s *OAuthServer) RegisterTrustedClient(ctx context.Context, c OAuthServerClient) (registered *OAuthServerClient, plainSecret string, err error)
RegisterTrustedClient registers a client programmatically and returns its plaintext secret (empty for a public client). Unlike dynamic registration it may set FirstParty (skips the consent screen), RequireConsent and RequirePAR, which a remote caller must not control. ClientID is generated when empty. Leave ClientSecretHash empty and set TokenEndpointAuthMethod to a client_secret_* method to have a secret generated.
func (*OAuthServer) VerifyAccessToken ¶ added in v1.2.12
func (s *OAuthServer) VerifyAccessToken(ctx context.Context, token string, opts VerifyAccessTokenOptions) (*AccessTokenClaims, error)
VerifyAccessToken validates an access token issued by this server (JWT or opaque) against the store, so revoked tokens are rejected.
type OAuthServerClient ¶ added in v1.0.78
type OAuthServerClient = sectypes.OAuthServerClient
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"). It is
// the "iss" of every token and the base of every endpoint URL. A path is allowed
// ("https://example.com/auth"); the server then also answers the RFC 8414 path-insertion
// well-known 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 and granted to clients that
// register without allowed_scopes. 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
// ResourceIdentifier is this server's protected-resource identifier, advertised in
// RFC 9728 metadata. Defaults to Issuer.
ResourceIdentifier string
// SigningKey signs id_tokens (RS256) and is exposed via the JWKS endpoint. If nil and
// SigningKeys is empty, an RSA-2048 key is generated in memory when the server starts.
// Supply a persistent key for multi-instance deployments so tokens remain verifiable
// across restarts and instances.
SigningKey *rsa.PrivateKey
// SigningKeys supersedes SigningKey. The first key is the default; all are published in
// the JWKS, which is how a key is rotated (add the new key first, publish, then remove the
// old one once its tokens have expired). RSA and ECDSA (P-256/P-384) keys are supported.
SigningKeys []OAuthSigningKey
// CookieSecret keys the HMAC that protects the SSO cookie and the state carried through
// the login and consent forms. Defaults to a value derived from the first signing key, so
// instances sharing a signing key share sessions.
CookieSecret []byte
// SSOCookie configures the browser session cookie that makes prompt=none, max_age,
// single sign-on and logout work.
SSOCookie OAuthSSOCookieConfig
// RequireConsent shows a consent screen for every client that is not first-party and has
// no stored consent covering the requested scopes. A client can also opt in with its
// require_consent metadata.
RequireConsent bool
// ConsentTTL is how long a stored consent is honoured. Defaults to 90 days.
ConsentTTL time.Duration
// ManagedRefreshTokens makes the server issue and rotate its own refresh tokens (stored
// hashed, one family per grant, reuse of a rotated token revokes the family). When false,
// the refresh token of the underlying DatabaseAuthenticator is passed through as before.
ManagedRefreshTokens bool
// RefreshTokenTTL is the absolute lifetime of a refresh token family. Defaults to 30 days.
RefreshTokenTTL time.Duration
// JWTAccessTokens issues RFC 9068 JWT access tokens instead of opaque session tokens.
// Resource servers can verify them locally (VerifyAccessToken).
JWTAccessTokens bool
// AccessTokenAudience is the "aud" of JWT access tokens that were not requested for a
// specific resource. Defaults to ResourceIdentifier.
AccessTokenAudience string
// EnableDPoP accepts RFC 9449 DPoP proofs at the token and userinfo endpoints and binds
// the issued tokens to the proof key.
EnableDPoP bool
// EnablePAR serves the RFC 9126 pushed authorization request endpoint; RequirePAR makes it
// mandatory for every client.
EnablePAR bool
RequirePAR bool
PARTTL time.Duration // default 90 seconds
// EnableDeviceFlow serves the RFC 8628 device authorization grant.
EnableDeviceFlow bool
DeviceCodeTTL time.Duration // default 10 minutes
DevicePollSeconds int // minimum poll interval, default 5
// EnableTokenExchange serves the RFC 8693 token exchange grant.
EnableTokenExchange bool
// ClaimsProvider supplies the user claims for id_tokens and UserInfo (profile, email,
// address, phone, custom claims). The default returns sub, preferred_username and email.
ClaimsProvider OAuthClaimsProvider
// SupportedACR lists the authentication context class references advertised and accepted.
SupportedACR []string
// DisableLogout does not serve the RP-initiated logout endpoint.
DisableLogout bool
// InitialAccessToken, when set, must be presented as a Bearer token to register a client.
InitialAccessToken string
// AllowAnonymousIntrospection lets callers without client credentials use the revocation
// and introspection endpoints. By default they must authenticate as a client.
AllowAnonymousIntrospection bool
// RateLimiter, when set, is called for every request to a token-issuing endpoint
// ("authorize", "token", "par", "device", "register", "introspect", "revoke", "userinfo",
// "logout"). Returning false answers 429.
RateLimiter func(r *http.Request, endpoint string) bool
// AllowPrivateNetworkFetch lets the server fetch client jwks_uri documents from loopback and
// private addresses. Leave false in production (SSRF protection).
AllowPrivateNetworkFetch bool
// ScopeDescriptions are shown next to each scope on the consent screen. Built-in
// descriptions exist for openid, profile, email and offline_access.
ScopeDescriptions map[string]string
// LoginTemplate and ConsentTemplate replace the built-in pages. They receive
// OAuthLoginPage and OAuthConsentPage.
LoginTemplate *template.Template
ConsentTemplate *template.Template
}
OAuthServerConfig configures the OAuth2 / OpenID Connect authorization server.
Every field except Issuer is optional. The zero value of each new option keeps the behaviour of earlier versions; see OAUTH2_SERVER.md for the full guide.
type OAuthSigningKey ¶ added in v1.2.12
type OAuthSigningKey struct {
// ID is the JWKS "kid". Derived from the public key (RFC 7638 thumbprint) when empty.
ID string
// Key is an *rsa.PrivateKey (RS256) or an *ecdsa.PrivateKey (ES256 for P-256, ES384 for P-384).
Key crypto.Signer
// Alg overrides the algorithm inferred from Key (RS256, PS256, ES256, ES384).
Alg string
}
OAuthSigningKey is a key the authorization server signs tokens with. The first configured key is the default; the others are published in the JWKS so tokens signed before a rotation stay verifiable, and a client can ask for one by id_token_signed_response_alg.
type OAuthTokenInfo ¶ added in v1.0.78
type OAuthTokenInfo = sectypes.OAuthTokenInfo
type OIDCConfig ¶ added in v1.2.12
type OIDCConfig struct {
// Issuer is the provider's issuer URL; /.well-known/openid-configuration is fetched from it.
Issuer string
ClientID string
ClientSecret string
RedirectURL string
// Scopes defaults to openid, profile, email.
Scopes []string
ProviderName string // default "oidc"
// Optional, see OAuth2Config.
UserInfoParser func(userInfo map[string]any) (*UserContext, error)
AllowedAlgs []string
AuthStyle string
HTTPClient *http.Client
ClockSkew time.Duration
}
OIDCConfig configures an OpenID Connect provider found by discovery.
type PasskeyAuthenticationOptions ¶ added in v1.0.48
type PasskeyAuthenticationOptions = sectypes.PasskeyAuthenticationOptions
type PasskeyAuthenticationResponse ¶ added in v1.0.48
type PasskeyAuthenticationResponse = sectypes.PasskeyAuthenticationResponse
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 = sectypes.PasskeyAuthenticatorAssertionResponse
type PasskeyAuthenticatorAttestationResponse ¶ added in v1.0.48
type PasskeyAuthenticatorAttestationResponse = sectypes.PasskeyAuthenticatorAttestationResponse
type PasskeyAuthenticatorSelection ¶ added in v1.0.48
type PasskeyAuthenticatorSelection = sectypes.PasskeyAuthenticatorSelection
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 = sectypes.PasskeyCredential
type PasskeyCredentialDescriptor ¶ added in v1.0.48
type PasskeyCredentialDescriptor = sectypes.PasskeyCredentialDescriptor
type PasskeyCredentialParam ¶ added in v1.0.48
type PasskeyCredentialParam = sectypes.PasskeyCredentialParam
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 = sectypes.PasskeyRegistrationOptions
type PasskeyRegistrationResponse ¶ added in v1.0.48
type PasskeyRegistrationResponse = sectypes.PasskeyRegistrationResponse
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 = sectypes.PasskeyRelyingParty
type PasskeyUser ¶ added in v1.0.48
type PasskeyUser = sectypes.PasskeyUser
type PasswordResetCompleteRequest ¶ added in v1.0.85
type PasswordResetCompleteRequest = sectypes.PasswordResetCompleteRequest
type PasswordResetRequest ¶ added in v1.0.85
type PasswordResetRequest = sectypes.PasswordResetRequest
type PasswordResetResponse ¶ added in v1.0.85
type PasswordResetResponse = sectypes.PasswordResetResponse
type PasswordResettable ¶ added in v1.0.85
type PasswordResettable interface {
// RequestPasswordReset creates a reset token for the given email/username
RequestPasswordReset(ctx context.Context, req PasswordResetRequest) (*PasswordResetResponse, error)
// CompletePasswordReset validates the token and sets the new password
CompletePasswordReset(ctx context.Context, req PasswordResetCompleteRequest) error
}
PasswordResettable allows providers to support self-service password reset
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 = sectypes.RegisterRequest
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 = sectypes.RowSecurity
type RowSecurityProvider ¶ added in v0.0.63
type RowSecurityProvider interface {
// GetRowSecurity loads row security rules for a user and entity.
// userRef identifies the user and is opaque to the caller: it may be an int ID,
// a string/UUID, or the full *security.UserContext (see SecurityContext.GetUserRef),
// so providers backed by non-integer user identifiers (e.g. UUIDs) or that need
// access to JWT claims can implement row security without relying on a numeric ID.
GetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)
}
RowSecurityProvider handles row-level security (filtering)
type SecurityContext ¶ added in v0.0.67
type SecurityContext interface {
GetContext() context.Context
GetUserID() (int, bool)
// GetUserRef returns an opaque user identifier for row security lookups.
// Unlike GetUserID, it is not required to be an integer: implementations backed by
// non-integer identifiers (e.g. UUIDs) can return a string, or the full
// *security.UserContext so a RowSecurityProvider can read JWT claims directly.
GetUserRef() (any, 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(pUserRef any, pSchema, pTablename string) (out RowSecurity, err error)
func (*SecurityList) LoadColumnSecurity ¶
func (*SecurityList) LoadRowSecurity ¶
func (m *SecurityList) LoadRowSecurity(ctx context.Context, pUserRef any, 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
func (*SecurityList) SetTxSettings ¶ added in v1.2.7
func (m *SecurityList) SetTxSettings(fn TxSettingsFunc)
SetTxSettings sets the function that provides transaction-local settings for every transaction opened by a spec that registered its security hooks with this list. Pass nil to disable. May be called before or after RegisterSecurityHooks.
func (*SecurityList) TxSettings ¶ added in v1.2.7
func (m *SecurityList) TxSettings() TxSettingsFunc
TxSettings returns the configured TxSettingsFunc, or nil.
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 TwoFactorSecret ¶ added in v1.0.48
type TwoFactorSecret = sectypes.TwoFactorSecret
type TxSettingsFunc ¶ added in v1.2.7
type TxSettingsFunc func(secCtx SecurityContext) (map[string]string, error)
TxSettingsFunc returns the transaction-local settings (e.g. RLS GUCs such as "app.user_id") to stamp on a transaction. It runs once per transaction, at OnTxBegin, before any other SQL. Returning an error rolls the transaction back.
type UserContext ¶ added in v0.0.63
type UserContext = sectypes.UserContext
func GetUserContext ¶ added in v0.0.63
func GetUserContext(ctx context.Context) (*UserContext, bool)
GetUserContext extracts the full user context from request context
type Validatable ¶ added in v0.0.63
type Validatable interface {
// ValidateToken checks if a token is valid without extracting full user context
ValidateToken(ctx context.Context, token string) (bool, error)
}
Validatable allows providers to validate tokens without full authentication
type VerifyAccessTokenOptions ¶ added in v1.2.12
type VerifyAccessTokenOptions struct {
// Audience, when set, must be one of the token's audiences.
Audience string
// Scopes that must all be granted.
Scopes []string
}
VerifyAccessTokenOptions tunes VerifyAccessToken.
type WriteDataContext ¶ added in v1.2.7
type WriteDataContext interface {
GetData() interface{}
SetData(interface{})
}
WriteDataContext is implemented by security contexts that expose the create/update payload of the operation in flight.
Source Files
¶
- chain.go
- composite.go
- examples.go
- examples_funcspec.go
- hooks.go
- interfaces.go
- keystore.go
- keystore_database.go
- lookup_bridge.go
- middleware.go
- oauth2_examples.go
- oauth2_full_example.go
- oauth2_methods.go
- oauth_authorize.go
- oauth_clientauth.go
- oauth_consent.go
- oauth_device.go
- oauth_dpop.go
- oauth_exchange.go
- oauth_introspect.go
- oauth_jwk.go
- oauth_logout.go
- oauth_oidc.go
- oauth_par.go
- oauth_refresh.go
- oauth_register.go
- oauth_server.go
- oauth_server_db.go
- oauth_session.go
- oauth_templates.go
- oauth_token.go
- oidc_client.go
- passkey.go
- passkey_examples.go
- passkey_provider.go
- provider.go
- providers.go
- totp_provider_database.go
- txsettings.go
- types.go
- writesecurity.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package lookup owns every database read and write the security package needs.
|
Package lookup owns every database read and write the security package needs. |
|
backends
Package backends assembles a lookup.Provider: it builds the procedure and direct stores for one database and routes every operation to one of them according to lookup.Config.
|
Package backends assembles a lookup.Provider: it builds the procedure and direct stores for one database and routes every operation to one of them according to lookup.Config. |
|
conformance
Package conformance is the shared behavioural suite every lookup backend must pass.
|
Package conformance is the shared behavioural suite every lookup backend must pass. |
|
ddl
Package ddl holds the reference table schemas for the lookup direct backend, one per dialect.
|
Package ddl holds the reference table schemas for the lookup direct backend, one per dialect. |
|
dialect
Package dialect holds the per-database adaptors used by the lookup direct backend.
|
Package dialect holds the per-database adaptors used by the lookup direct backend. |
|
direct
Package direct is the table-backed implementation of the lookup stores.
|
Package direct is the table-backed implementation of the lookup stores. |
|
procedure
Package procedure is the stored-procedure backend of lookup: it calls the resolvespec_* functions (names from lookup.ProcNames) and keeps their p_success / p_error / p_data contract.
|
Package procedure is the stored-procedure backend of lookup: it calls the resolvespec_* functions (names from lookup.ProcNames) and keeps their p_success / p_error / p_data contract. |