base

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var KeyTypeScopes = map[KeyType][]string{
	KeyTypePublishable: {
		"app:identify",
		"sessions:create",
		"users:verify",
		"public:read",
	},
	KeyTypeSecret: {
		"admin:full",
	},
	KeyTypeRestricted: {},
}

KeyTypeScopes defines default scopes for each key type These are automatically granted based on key type

View Source
var SafePublicScopes = map[string]bool{
	"app:identify":    true,
	"sessions:create": true,
	"sessions:verify": true,
	"users:verify":    true,
	"users:read":      true,
	"public:read":     true,
	"webhooks:verify": true,
}

SafePublicScopes defines scopes that are safe for publishable keys Only these scopes can be granted to pk_ keys

Functions

func IsSafeForPublicKey

func IsSafeForPublicKey(scope string) bool

IsSafeForPublicKey checks if a scope is safe for publishable keys

Types

type APIKey

type APIKey struct {
	ID             xid.ID            `json:"id"`
	AppID          xid.ID            `json:"appID"`                    // Platform tenant
	EnvironmentID  xid.ID            `json:"environmentID"`            // Required: environment-scoped
	OrganizationID *xid.ID           `json:"organizationID,omitempty"` // Optional: org-scoped
	UserID         xid.ID            `json:"userID"`                   // User who created the key
	Name           string            `json:"name"`
	Description    string            `json:"description,omitempty"`
	Prefix         string            `json:"prefix"`
	KeyType        KeyType           `json:"keyType"` // pk/sk/rk
	Scopes         []string          `json:"scopes"`
	Permissions    map[string]string `json:"permissions"`
	RateLimit      int               `json:"rate_limit"`
	AllowedIPs     []string          `json:"allowed_ips,omitempty"`
	Active         bool              `json:"active"`
	ExpiresAt      *time.Time        `json:"expires_at,omitempty"`
	UsageCount     int64             `json:"usage_count"`
	LastUsedAt     *time.Time        `json:"last_used_at,omitempty"`
	LastUsedIP     string            `json:"last_used_ip,omitempty"`
	LastUsedUA     string            `json:"last_used_ua,omitempty"`
	CreatedAt      time.Time         `json:"created_at"`
	UpdatedAt      time.Time         `json:"updated_at"`
	Metadata       map[string]string `json:"metadata,omitempty"`

	// RBAC Integration (Hybrid Approach)
	DelegateUserPermissions bool     `json:"delegateUserPermissions"`     // Inherit creator's permissions
	ImpersonateUserID       *xid.ID  `json:"impersonateUserID,omitempty"` // Act as specific user
	Roles                   []string `json:"roles,omitempty"`             // Role IDs or names
	RBACPermissions         []string `json:"rbacPermissions,omitempty"`   // Computed RBAC permissions

	// Transient field - only populated during creation
	Key string `json:"key,omitempty"`
}

APIKey represents an API key with its metadata (DTO) Updated for V2 architecture: App → Environment → Organization

func FromSchemaAPIKey

func FromSchemaAPIKey(s *schema.APIKey) *APIKey

FromSchemaAPIKey converts a schema.APIKey to APIKey DTO

func FromSchemaAPIKeys

func FromSchemaAPIKeys(keys []*schema.APIKey) []*APIKey

FromSchemaAPIKeys converts multiple schema.APIKey to APIKey DTOs

func (*APIKey) CanPerformAdminOperation

func (a *APIKey) CanPerformAdminOperation() bool

CanPerformAdminOperation returns true if the key has admin privileges

func (*APIKey) GetAllScopes

func (a *APIKey) GetAllScopes() []string

GetAllScopes returns all scopes including default key type scopes

func (*APIKey) HasPermission

func (a *APIKey) HasPermission(permission string) bool

HasPermission checks if the API key has a specific permission

func (*APIKey) HasScope

func (a *APIKey) HasScope(scope string) bool

HasScope checks if the API key has a specific scope

func (*APIKey) HasScopeWildcard

func (a *APIKey) HasScopeWildcard(scope string) bool

HasScopeWildcard checks if the API key has a scope, supporting wildcards Examples: "admin:*" matches "admin:users", "admin:settings", etc.

func (*APIKey) IsExpired

func (a *APIKey) IsExpired() bool

IsExpired checks if the API key has expired

func (*APIKey) IsPublishable

func (a *APIKey) IsPublishable() bool

IsPublishable returns true if this is a publishable (frontend-safe) key

func (*APIKey) IsRestricted

func (a *APIKey) IsRestricted() bool

IsRestricted returns true if this is a restricted (backend-only, scoped) key

func (*APIKey) IsSecret

func (a *APIKey) IsSecret() bool

IsSecret returns true if this is a secret (backend-only, admin) key

func (*APIKey) ToSchema

func (a *APIKey) ToSchema() *schema.APIKey

ToSchema converts the APIKey DTO to schema.APIKey

type CreateAPIKeyRequest

type CreateAPIKeyRequest struct {
	AppID         xid.ID            `json:"appID" validate:"required"`         // Platform tenant
	EnvironmentID xid.ID            `json:"environmentID" validate:"required"` // Required: environment-scoped
	OrgID         *xid.ID           `json:"orgID,omitempty"`                   // Optional: org-scoped
	UserID        xid.ID            `json:"userID" validate:"required"`        // User creating the key
	Name          string            `json:"name" validate:"required,min=1,max=100"`
	Description   string            `json:"description,omitempty" validate:"max=500"`
	KeyType       KeyType           `json:"keyType" validate:"required"` // pk/sk/rk
	Scopes        []string          `json:"scopes" validate:"required,min=1"`
	Permissions   map[string]string `json:"permissions,omitempty"`
	RateLimit     int               `json:"rate_limit,omitempty" validate:"min=0,max=10000"`
	AllowedIPs    []string          `json:"allowed_ips,omitempty"` // IP whitelist (CIDR notation supported)
	ExpiresAt     *time.Time        `json:"expires_at,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`

	// RBAC Integration
	DelegateUserPermissions bool     `json:"delegateUserPermissions,omitempty"` // Inherit creator's permissions
	ImpersonateUserID       *xid.ID  `json:"impersonateUserID,omitempty"`       // Act as specific user
	RoleIDs                 []xid.ID `json:"roleIDs,omitempty"`                 // Assign roles on creation
}

CreateAPIKeyRequest represents a request to create an API key Updated for V2 architecture

type KeyType

type KeyType string

KeyType represents the type of API key

const (
	// KeyTypePublishable - Frontend-safe, identifies app, limited operations
	// Can be safely exposed in client-side code (browser, mobile apps)
	// Limited to read-only and session creation operations
	KeyTypePublishable KeyType = "pk"

	// KeyTypeSecret - Backend-only, full administrative privileges
	// Must be kept secret on server-side only
	// Has unrestricted access to all operations
	KeyTypeSecret KeyType = "sk"

	// KeyTypeRestricted - Backend-only, scoped to specific operations
	// Must be kept secret on server-side
	// Access limited to explicitly granted scopes
	KeyTypeRestricted KeyType = "rk"
)

func (KeyType) GetDefaultScopes

func (kt KeyType) GetDefaultScopes() []string

GetDefaultScopes returns the default scopes for this key type

func (KeyType) IsBackendOnly

func (kt KeyType) IsBackendOnly() bool

IsBackendOnly returns true if key must be used server-side only

func (KeyType) IsPublic

func (kt KeyType) IsPublic() bool

IsPublic returns true if key can be safely exposed in frontend

func (KeyType) IsValid

func (kt KeyType) IsValid() bool

IsValid checks if the key type is valid

func (KeyType) String

func (kt KeyType) String() string

String returns the string representation of the key type

type ListAPIKeysResponse

type ListAPIKeysResponse = pagination.PageResponse[*APIKey]

ListAPIKeysResponse is a type alias for the paginated response

type RotateAPIKeyRequest

type RotateAPIKeyRequest struct {
	ID             xid.ID     `json:"id" validate:"required"`
	AppID          xid.ID     `json:"appID" validate:"required"`
	EnvironmentID  xid.ID     `json:"environmentID" validate:"required"`
	OrganizationID *xid.ID    `json:"organizationID,omitempty"`
	UserID         xid.ID     `json:"userID" validate:"required"`
	ExpiresAt      *time.Time `json:"expires_at,omitempty"`
}

RotateAPIKeyRequest represents a request to rotate an API key Updated for V2 architecture

type Session

type Session struct {
	ID             xid.ID    `json:"id"`
	Token          string    `json:"token"`
	AppID          xid.ID    `json:"appID"`
	EnvironmentID  *xid.ID   `json:"environmentID,omitempty"`
	OrganizationID *xid.ID   `json:"organizationID,omitempty"`
	UserID         xid.ID    `json:"userId"`
	ExpiresAt      time.Time `json:"expiresAt"`
	IPAddress      string    `json:"ipAddress"`
	UserAgent      string    `json:"userAgent"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
}

Session represents a user session (DTO)

func (*Session) ToSchema

func (s *Session) ToSchema() *schema.Session

ToSchema converts Session DTO to schema.Session

type UpdateAPIKeyRequest

type UpdateAPIKeyRequest struct {
	Name        *string           `json:"name,omitempty" validate:"omitempty,min=1,max=100"`
	Description *string           `json:"description,omitempty" validate:"omitempty,max=500"`
	Scopes      []string          `json:"scopes,omitempty" validate:"omitempty,min=1"`
	Permissions map[string]string `json:"permissions,omitempty"`
	RateLimit   *int              `json:"rate_limit,omitempty" validate:"omitempty,min=0,max=10000"`
	ExpiresAt   *time.Time        `json:"expires_at,omitempty"`
	Active      *bool             `json:"active,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
}

UpdateAPIKeyRequest represents a request to update an API key

type User

type User struct {
	ID              xid.ID     `json:"id"`
	AppID           xid.ID     `json:"appId"`
	Email           string     `json:"email"`
	EmailVerified   bool       `json:"emailVerified"`
	EmailVerifiedAt *time.Time `json:"emailVerifiedAt,omitempty"`
	Name            string     `json:"name"`
	Image           string     `json:"image,omitempty"`
	PasswordHash    string     `json:"-"` // Never expose in JSON
	Username        string     `json:"username"`
	DisplayUsername string     `json:"displayUsername,omitempty"`
	// Audit fields
	CreatedAt time.Time  `json:"createdAt"`
	UpdatedAt time.Time  `json:"updatedAt"`
	DeletedAt *time.Time `json:"deletedAt,omitempty"`
}

User represents a user entity DTO This is separate from schema.User to maintain proper separation of concerns

func (*User) ToSchema

func (u *User) ToSchema() *schema.User

ToSchema converts the User DTO to a schema.User model

type VerifyAPIKeyRequest

type VerifyAPIKeyRequest struct {
	Key                string `json:"key" validate:"required"`
	RequiredScope      string `json:"required_scope,omitempty"`
	RequiredPermission string `json:"required_permission,omitempty"`
	IP                 string `json:"ip,omitempty"`
	UserAgent          string `json:"user_agent,omitempty"`
}

VerifyAPIKeyRequest represents a request to verify an API key

type VerifyAPIKeyResponse

type VerifyAPIKeyResponse struct {
	Valid  bool    `json:"valid"`
	APIKey *APIKey `json:"api_key,omitempty"`
	Error  string  `json:"error,omitempty"`
}

VerifyAPIKeyResponse represents a response from API key verification

Jump to

Keyboard shortcuts

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