Documentation
¶
Index ¶
- Constants
- func GetAPIKey(c forge.Context) *apikey.APIKey
- func GetOrgID(c forge.Context) string
- func GetScopes(c forge.Context) []string
- func GetUser(c forge.Context) *user.User
- func IsAuthenticated(c forge.Context) bool
- type AssignRoleRequest
- type AutoCleanupConfig
- type Config
- type CreateAPIKeyRequest
- type CreateAPIKeyResponse
- type DashboardExtension
- func (e *DashboardExtension) CreateAPIKey(c forge.Context) error
- func (e *DashboardExtension) DashboardWidgets() []ui.DashboardWidget
- func (e *DashboardExtension) ExtensionID() string
- func (e *DashboardExtension) NavigationItems() []ui.NavigationItem
- func (e *DashboardExtension) RenderDashboardWidget(basePath string, currentApp *app.App) g.Node
- func (e *DashboardExtension) RevokeAPIKey(c forge.Context) error
- func (e *DashboardExtension) RotateAPIKey(c forge.Context) error
- func (e *DashboardExtension) Routes() []ui.Route
- func (e *DashboardExtension) ServeAPIKeysConfigPage(c forge.Context) error
- func (e *DashboardExtension) ServeAPIKeysListPage(c forge.Context) error
- func (e *DashboardExtension) ServeAPIKeysSecurityPage(c forge.Context) error
- func (e *DashboardExtension) SetRegistry(registry *dashboard.ExtensionRegistry)
- func (e *DashboardExtension) SettingsPages() []ui.SettingsPage
- func (e *DashboardExtension) SettingsSections() []ui.SettingsSection
- func (e *DashboardExtension) UpdateConfig(c forge.Context) error
- func (e *DashboardExtension) UpdateSecurity(c forge.Context) error
- type DeleteAPIKeyRequest
- type GetAPIKeyRequest
- type GetEffectivePermissionsRequest
- type GetRolesRequest
- type Handler
- func (h *Handler) AssignRole(c forge.Context) error
- func (h *Handler) CreateAPIKey(c forge.Context) error
- func (h *Handler) DeleteAPIKey(c forge.Context) error
- func (h *Handler) GetAPIKey(c forge.Context) error
- func (h *Handler) GetEffectivePermissions(c forge.Context) error
- func (h *Handler) GetRoles(c forge.Context) error
- func (h *Handler) ListAPIKeys(c forge.Context) error
- func (h *Handler) RotateAPIKey(c forge.Context) error
- func (h *Handler) UnassignRole(c forge.Context) error
- func (h *Handler) UpdateAPIKey(c forge.Context) error
- func (h *Handler) VerifyAPIKey(c forge.Context) error
- type IPWhitelistConfig
- type KeyStats
- type ListAPIKeysRequest
- type MessageResponse
- type Middleware
- func (m *Middleware) Authenticate(next func(forge.Context) error) func(forge.Context) error
- func (m *Middleware) RequireAPIKey(scopes ...string) func(next func(forge.Context) error) func(forge.Context) error
- func (m *Middleware) RequirePermission(permissions ...string) func(next func(forge.Context) error) func(forge.Context) error
- type Plugin
- func (p *Plugin) DashboardExtension() ui.DashboardExtension
- func (p *Plugin) ID() string
- func (p *Plugin) Init(authInstance core.Authsome) error
- func (p *Plugin) Middleware() func(next func(forge.Context) error) func(forge.Context) error
- func (p *Plugin) Migrate() error
- func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error
- func (p *Plugin) RegisterRoutes(router forge.Router) error
- func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error
- func (p *Plugin) RequireAPIKey(scopes ...string) func(next func(forge.Context) error) func(forge.Context) error
- func (p *Plugin) RequirePermission(permissions ...string) func(next func(forge.Context) error) func(forge.Context) error
- func (p *Plugin) Service() *apikey.Service
- func (p *Plugin) StopCleanupScheduler()
- type PluginOption
- func WithAllowQueryParam(allow bool) PluginOption
- func WithAutoCleanup(enabled bool, interval time.Duration) PluginOption
- func WithDefaultConfig(cfg Config) PluginOption
- func WithDefaultExpiry(expiry time.Duration) PluginOption
- func WithDefaultRateLimit(limit int) PluginOption
- func WithKeyLength(length int) PluginOption
- func WithMaxKeysPerOrg(max int) PluginOption
- func WithMaxKeysPerUser(max int) PluginOption
- func WithMaxRateLimit(limit int) PluginOption
- type RateLimitConfig
- type RolesResponse
- type RotateAPIKeyRequest
- type RotateAPIKeyResponse
- type ScopeDefinition
- type UnassignRoleRequest
- type UpdateAPIKeyRequest
- type VerifyAPIKeyRequest
- type WebhookConfig
Examples ¶
Constants ¶
const ( APIKeyContextKey contextKey = "api_key" APIKeyUserContextKey contextKey = "api_key_user" APIKeyAuthenticatedKey contextKey = "api_key_authenticated" APIKeyPermissionsKey contextKey = "api_key_permissions" )
Variables ¶
This section is empty.
Functions ¶
func GetOrgID ¶
GetOrgID extracts the organization ID from context (V2 architecture) Returns the xid.ID, check with IsNil() before use
func IsAuthenticated ¶
IsAuthenticated checks if the request is authenticated via API key
Types ¶
type AssignRoleRequest ¶ added in v0.0.7
type AutoCleanupConfig ¶
type AutoCleanupConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Interval time.Duration `json:"interval" yaml:"interval"` // How often to run cleanup
}
AutoCleanupConfig configures automatic cleanup of expired keys
type Config ¶
type Config struct {
// Service configuration
DefaultRateLimit int `json:"default_rate_limit" yaml:"default_rate_limit"`
MaxRateLimit int `json:"max_rate_limit" yaml:"max_rate_limit"`
DefaultExpiry time.Duration `json:"default_expiry" yaml:"default_expiry"`
MaxKeysPerUser int `json:"max_keys_per_user" yaml:"max_keys_per_user"`
MaxKeysPerOrg int `json:"max_keys_per_org" yaml:"max_keys_per_org"`
KeyLength int `json:"key_length" yaml:"key_length"`
// Authentication configuration
AllowQueryParam bool `json:"allow_query_param" yaml:"allow_query_param"` // Allow API key in query params (not recommended for production)
// Rate limiting configuration
RateLimiting RateLimitConfig `json:"rate_limiting" yaml:"rate_limiting"`
// IP whitelisting
IPWhitelisting IPWhitelistConfig `json:"ip_whitelisting" yaml:"ip_whitelisting"`
// Webhook notifications
Webhooks WebhookConfig `json:"webhooks" yaml:"webhooks"`
// Cleanup scheduler
AutoCleanup AutoCleanupConfig `json:"auto_cleanup" yaml:"auto_cleanup"`
}
Config holds the API key plugin configuration
type CreateAPIKeyRequest ¶ added in v0.0.7
type CreateAPIKeyRequest struct {
Name string `json:"name" validate:"required"`
Description string `json:"description"`
Scopes []string `json:"scopes" validate:"required,min=1"`
Permissions map[string]string `json:"permissions"`
RateLimit int `json:"rate_limit"`
AllowedIPs []string `json:"allowed_ips"`
Metadata map[string]string `json:"metadata"`
}
Request types
type CreateAPIKeyResponse ¶
type CreateAPIKeyResponse struct {
APIKey *apikey.APIKey `json:"api_key"`
Message string `json:"message"`
}
Response types
type DashboardExtension ¶ added in v0.0.2
type DashboardExtension struct {
// contains filtered or unexported fields
}
DashboardExtension implements the ui.DashboardExtension interface This allows the API key plugin to add its own screens to the dashboard
func NewDashboardExtension ¶ added in v0.0.2
func NewDashboardExtension(plugin *Plugin) *DashboardExtension
NewDashboardExtension creates a new dashboard extension for API keys
func (*DashboardExtension) CreateAPIKey ¶ added in v0.0.2
func (e *DashboardExtension) CreateAPIKey(c forge.Context) error
CreateAPIKey handles API key creation
func (*DashboardExtension) DashboardWidgets ¶ added in v0.0.2
func (e *DashboardExtension) DashboardWidgets() []ui.DashboardWidget
DashboardWidgets returns widgets to show on the main dashboard
func (*DashboardExtension) ExtensionID ¶ added in v0.0.2
func (e *DashboardExtension) ExtensionID() string
ExtensionID returns the unique identifier for this extension
func (*DashboardExtension) NavigationItems ¶ added in v0.0.2
func (e *DashboardExtension) NavigationItems() []ui.NavigationItem
NavigationItems returns navigation items to register (none for settings-only plugin)
func (*DashboardExtension) RenderDashboardWidget ¶ added in v0.0.2
RenderDashboardWidget renders the API key stats widget
func (*DashboardExtension) RevokeAPIKey ¶ added in v0.0.2
func (e *DashboardExtension) RevokeAPIKey(c forge.Context) error
RevokeAPIKey handles API key revocation
func (*DashboardExtension) RotateAPIKey ¶ added in v0.0.2
func (e *DashboardExtension) RotateAPIKey(c forge.Context) error
RotateAPIKey handles API key rotation
func (*DashboardExtension) Routes ¶ added in v0.0.2
func (e *DashboardExtension) Routes() []ui.Route
Routes returns routes to register under /dashboard/app/:appId/
func (*DashboardExtension) ServeAPIKeysConfigPage ¶ added in v0.0.2
func (e *DashboardExtension) ServeAPIKeysConfigPage(c forge.Context) error
ServeAPIKeysConfigPage renders the configuration page
func (*DashboardExtension) ServeAPIKeysListPage ¶ added in v0.0.2
func (e *DashboardExtension) ServeAPIKeysListPage(c forge.Context) error
ServeAPIKeysListPage renders the API keys management page
func (*DashboardExtension) ServeAPIKeysSecurityPage ¶ added in v0.0.2
func (e *DashboardExtension) ServeAPIKeysSecurityPage(c forge.Context) error
ServeAPIKeysSecurityPage renders the security settings page
func (*DashboardExtension) SetRegistry ¶ added in v0.0.2
func (e *DashboardExtension) SetRegistry(registry *dashboard.ExtensionRegistry)
SetRegistry sets the extension registry reference (called by dashboard after registration)
func (*DashboardExtension) SettingsPages ¶ added in v0.0.2
func (e *DashboardExtension) SettingsPages() []ui.SettingsPage
SettingsPages returns full settings pages for the sidebar layout
func (*DashboardExtension) SettingsSections ¶ added in v0.0.2
func (e *DashboardExtension) SettingsSections() []ui.SettingsSection
SettingsSections returns settings sections (deprecated, using SettingsPages instead)
func (*DashboardExtension) UpdateConfig ¶ added in v0.0.2
func (e *DashboardExtension) UpdateConfig(c forge.Context) error
UpdateConfig handles configuration updates
func (*DashboardExtension) UpdateSecurity ¶ added in v0.0.2
func (e *DashboardExtension) UpdateSecurity(c forge.Context) error
UpdateSecurity handles security settings updates
type DeleteAPIKeyRequest ¶ added in v0.0.7
type DeleteAPIKeyRequest struct {
ID string `path:"id" validate:"required"`
}
type GetAPIKeyRequest ¶ added in v0.0.7
type GetAPIKeyRequest struct {
ID string `path:"id" validate:"required"`
}
type GetEffectivePermissionsRequest ¶ added in v0.0.7
type GetEffectivePermissionsRequest struct {
ID string `path:"id" validate:"required"`
}
type GetRolesRequest ¶ added in v0.0.7
type GetRolesRequest struct {
ID string `path:"id" validate:"required"`
}
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles API key related HTTP requests Updated for V2 architecture: App → Environment → Organization
func NewHandler ¶
NewHandler creates a new API key handler
func (*Handler) AssignRole ¶
AssignRole handles POST /api-keys/:id/roles
func (*Handler) CreateAPIKey ¶
CreateAPIKey handles POST /api-keys
func (*Handler) DeleteAPIKey ¶
DeleteAPIKey handles DELETE /api-keys/:id
func (*Handler) GetEffectivePermissions ¶
GetEffectivePermissions handles GET /api-keys/:id/permissions
func (*Handler) ListAPIKeys ¶
ListAPIKeys handles GET /api-keys
func (*Handler) RotateAPIKey ¶
RotateAPIKey handles POST /api-keys/:id/rotate
func (*Handler) UnassignRole ¶
UnassignRole handles DELETE /api-keys/:id/roles/:roleId
func (*Handler) UpdateAPIKey ¶
UpdateAPIKey handles PATCH /api-keys/:id
type IPWhitelistConfig ¶
type IPWhitelistConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
StrictMode bool `json:"strict_mode" yaml:"strict_mode"` // Reject if IP not in allowlist
}
IPWhitelistConfig configures IP whitelisting
type KeyStats ¶ added in v0.0.2
type KeyStats struct {
TotalActive int
UsedLast24h int
AvgRequestRate float64
ExpiringSoon int
TotalRevoked int
MostUsedKeyName string
}
KeyStats holds API key statistics
type ListAPIKeysRequest ¶ added in v0.0.7
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware handles API key authentication
func NewMiddleware ¶
func NewMiddleware( service *apikey.Service, userSvc *user.Service, rateLimiter *ratelimit.Service, config Config, ) *Middleware
NewMiddleware creates a new API key middleware
func (*Middleware) Authenticate ¶
Authenticate attempts to authenticate using an API key from the request This middleware is non-blocking - it will set context values if a valid API key is found, but will not reject requests without API keys (use RequireAPIKey for that)
func (*Middleware) RequireAPIKey ¶
func (m *Middleware) RequireAPIKey(scopes ...string) func(next func(forge.Context) error) func(forge.Context) error
RequireAPIKey enforces API key authentication
func (*Middleware) RequirePermission ¶
func (m *Middleware) RequirePermission(permissions ...string) func(next func(forge.Context) error) func(forge.Context) error
RequirePermission enforces specific permissions
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements API key authentication for external clients
Example (Basic) ¶
Example: Basic plugin registration
package main
import (
"context"
"github.com/uptrace/bun"
"github.com/xraph/authsome"
apikeyPlugin "github.com/xraph/authsome/plugins/apikey"
"github.com/xraph/forge"
)
func main() {
// Initialize database (example)
var db *bun.DB // Your database connection
// Create Forge app
app := forge.New()
// Create AuthSome instance
auth := authsome.New(
authsome.WithDatabase(db),
authsome.WithForgeApp(app),
)
// Register API key plugin
plugin := apikeyPlugin.NewPlugin()
_ = auth.RegisterPlugin(plugin)
// Initialize (this will call plugin Init)
_ = auth.Initialize(context.Background())
// Mount to router
_ = auth.Mount(app.Router(), "/api/auth")
// Now API key authentication is available
}
Example (CreateKey) ¶
Example: Create and use API keys programmatically
package main
import (
"context"
"github.com/rs/xid"
"github.com/xraph/authsome/core/apikey"
)
func main() {
var ctx context.Context
var service *apikey.Service // From plugin.Service()
// V2 Architecture: App → Environment → Organization (optional)
appID := xid.New() // Platform app (required)
envID := xid.New() // Environment: dev/staging/prod (required)
orgID := xid.New() // User org (optional - can be nil)
userID := xid.New() // User creating the key
// Create an API key
req := &apikey.CreateAPIKeyRequest{
AppID: appID, // Platform app (required)
EnvironmentID: envID, // Environment (required)
OrgID: &orgID, // User-created org (optional)
UserID: userID, // User who owns the key
Name: "Production API Key",
Description: "Key for prod server",
KeyType: apikey.KeyTypeSecret, // sk (secret), pk (publishable), rk (restricted)
Scopes: []string{"users:read", "users:write"},
RateLimit: 5000,
}
key, err := service.CreateAPIKey(ctx, req)
if err != nil {
panic(err)
}
// IMPORTANT: Store key.Key securely - it won't be shown again!
// key.Key = "sk_prod_abc123.secret_token"
_ = key
}
Example (ProtectRoutes) ¶
Example: Protect routes with API key middleware
package main
import (
apikeyPlugin "github.com/xraph/authsome/plugins/apikey"
"github.com/xraph/forge"
)
func main() {
// This example demonstrates how to extract API key context from requests
// For actual middleware setup, see the plugin documentation
// When a request is authenticated with an API key, you can extract context:
// In your handler:
handler := func(c forge.Context) error {
// Extract API key context (V2 Architecture)
key := apikeyPlugin.GetAPIKey(c) // The full API key data
orgID := apikeyPlugin.GetOrgID(c) // User org ID (may be empty string)
user := apikeyPlugin.GetUser(c) // Associated user
scopes := apikeyPlugin.GetScopes(c) // API key scopes
authenticated := apikeyPlugin.IsAuthenticated(c) // Check if authenticated
// V2 Architecture context is available in the key:
if key != nil {
_ = key.AppID // Platform app ID
_ = key.EnvironmentID // Environment ID (dev/staging/prod)
_ = key.OrganizationID // User-created org ID (may be nil)
_ = key.Scopes // Key scopes
_ = key.Permissions // Key permissions
}
_ = orgID
_ = user
_ = scopes
_ = authenticated
return c.JSON(200, map[string]string{"status": "ok"})
}
_ = handler
// Middleware is configured through the plugin's Middleware() method
// See plugin documentation for setup details
}
func NewPlugin ¶
func NewPlugin(opts ...PluginOption) *Plugin
NewPlugin creates a new API key plugin instance with optional configuration
func (*Plugin) DashboardExtension ¶ added in v0.0.2
func (p *Plugin) DashboardExtension() ui.DashboardExtension
DashboardExtension returns the dashboard extension for this plugin This implements the PluginWithDashboardExtension interface
func (*Plugin) Middleware ¶
Middleware returns the authentication middleware
func (*Plugin) RegisterHooks ¶
func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error
RegisterHooks registers plugin hooks with the hook registry
func (*Plugin) RegisterRoutes ¶
RegisterRoutes registers the plugin's HTTP routes
func (*Plugin) RegisterServiceDecorators ¶
func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error
RegisterServiceDecorators allows plugins to replace core services with decorated versions
func (*Plugin) RequireAPIKey ¶
func (p *Plugin) RequireAPIKey(scopes ...string) func(next func(forge.Context) error) func(forge.Context) error
RequireAPIKey returns middleware that requires a valid API key
func (*Plugin) RequirePermission ¶
func (p *Plugin) RequirePermission(permissions ...string) func(next func(forge.Context) error) func(forge.Context) error
RequirePermission returns middleware that requires specific permissions
func (*Plugin) StopCleanupScheduler ¶
func (p *Plugin) StopCleanupScheduler()
StopCleanupScheduler stops the cleanup scheduler (for graceful shutdown)
type PluginOption ¶
type PluginOption func(*Plugin)
PluginOption is a functional option for configuring the API key plugin
func WithAllowQueryParam ¶
func WithAllowQueryParam(allow bool) PluginOption
WithAllowQueryParam sets whether to allow API keys in query params
func WithAutoCleanup ¶
func WithAutoCleanup(enabled bool, interval time.Duration) PluginOption
WithAutoCleanup sets the auto cleanup configuration
func WithDefaultConfig ¶
func WithDefaultConfig(cfg Config) PluginOption
WithDefaultConfig sets the default configuration for the plugin
func WithDefaultExpiry ¶
func WithDefaultExpiry(expiry time.Duration) PluginOption
WithDefaultExpiry sets the default key expiry
func WithDefaultRateLimit ¶
func WithDefaultRateLimit(limit int) PluginOption
WithDefaultRateLimit sets the default rate limit
func WithKeyLength ¶
func WithKeyLength(length int) PluginOption
WithKeyLength sets the API key length
func WithMaxKeysPerOrg ¶
func WithMaxKeysPerOrg(max int) PluginOption
WithMaxKeysPerOrg sets the maximum keys per organization
func WithMaxKeysPerUser ¶
func WithMaxKeysPerUser(max int) PluginOption
WithMaxKeysPerUser sets the maximum keys per user
func WithMaxRateLimit ¶
func WithMaxRateLimit(limit int) PluginOption
WithMaxRateLimit sets the maximum rate limit
type RateLimitConfig ¶
type RateLimitConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Window time.Duration `json:"window" yaml:"window"` // Time window for rate limiting
}
RateLimitConfig configures rate limiting behavior
type RolesResponse ¶
type RotateAPIKeyRequest ¶ added in v0.0.7
type RotateAPIKeyRequest struct {
ID string `path:"id" validate:"required"`
}
type RotateAPIKeyResponse ¶
type ScopeDefinition ¶ added in v0.0.2
type ScopeDefinition struct {
Value string
Label string
Description string
DangerLevel string // "safe", "moderate", "dangerous", "critical"
Category string // "read", "write", "admin", "special"
}
ScopeDefinition defines a scope with metadata
type UnassignRoleRequest ¶ added in v0.0.7
type UpdateAPIKeyRequest ¶ added in v0.0.7
type UpdateAPIKeyRequest struct {
ID string `path:"id" validate:"required"`
Name *string `json:"name"`
Description *string `json:"description"`
Scopes []string `json:"scopes"`
Permissions map[string]string `json:"permissions"`
RateLimit *int `json:"rate_limit"`
AllowedIPs []string `json:"allowed_ips"`
Metadata map[string]string `json:"metadata"`
}
type VerifyAPIKeyRequest ¶ added in v0.0.7
type VerifyAPIKeyRequest struct {
Key string `json:"key" validate:"required"`
}
type WebhookConfig ¶
type WebhookConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
NotifyOnCreated bool `json:"notify_on_created" yaml:"notify_on_created"`
NotifyOnRotated bool `json:"notify_on_rotated" yaml:"notify_on_rotated"`
NotifyOnDeleted bool `json:"notify_on_deleted" yaml:"notify_on_deleted"`
NotifyOnRateLimit bool `json:"notify_on_rate_limit" yaml:"notify_on_rate_limit"`
NotifyOnExpiring bool `json:"notify_on_expiring" yaml:"notify_on_expiring"` // Notify N days before expiry
ExpiryWarningDays int `json:"expiry_warning_days" yaml:"expiry_warning_days"`
WebhookURLs []string `json:"webhook_urls" yaml:"webhook_urls"`
}
WebhookConfig configures webhook notifications for API key events