auth

package
v0.1.53 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 19 Imported by: 0

README

auth

JWT authentication middleware and Role-Based Access Control (RBAC).

What It Does

Two related but independent pieces:

  1. Middleware: Extract and validate JWT tokens, store user info in context
  2. RBAC: Define roles and permissions, check if users can perform actions

JWT Middleware

Basic Usage
// Create middleware with secret
authMiddleware := auth.NewJWTmiddleware(secretKey)

// Use with Fiber, Gin, etc.
app.Use(authMiddleware.Handler)

// In handlers, get user info from context
userID := auth.GetUserID(ctx)
role := auth.GetRole(ctx)
Configuration
config := &auth.JWTConfig{
    Secret:        "your-secret-key",
    TokenLookup:   "header:Authorization",  // Where to find token
    TokenPrefix:   "Bearer",                 // Prefix to strip
    Expiration:    time.Hour,                // Token expiry
    SigningMethod: "HS256",
}
middleware := auth.NewJWTmiddlewareFromConfig(config)

RBAC (Role-Based Access Control)

Creating RBAC
// With database-backed role store
roleStore := auth.NewDatabaseRoleStore(func(ctx context.Context, userID string) (auth.Role, error) {
    // Query your database
    return db.GetUserRole(ctx, userID)
})
rbac := auth.NewRBAC(roleStore)

// Or with caching
cachedStore := auth.NewCachedRoleStore(roleStore, 5*time.Minute)
rbac := auth.NewRBAC(cachedStore)

// Or default (always returns RoleUser)
rbac := auth.NewRBAC(nil)
Built-in Roles
const (
    RoleAdmin     Role = "admin"
    RoleUser      Role = "user"
    RoleReadOnly  Role = "readonly"
    RolePremium   Role = "premium"
    RoleDeveloper Role = "developer"
)
Built-in Permissions
// Wallet
PermWalletRead, PermWalletWrite, PermWalletDelete

// Portfolio
PermPortfolioRead, PermPortfolioWrite, PermPortfolioDelete

// Analytics
PermAnalyticsRead, PermAnalyticsAdvanced

// Billing
PermBillingRead, PermBillingWrite, PermBillingDelete

// User
PermUserRead, PermUserWrite, PermUserDelete

// Admin
PermAdminRead, PermAdminWrite, PermAdminDelete

// API
PermAPICreate, PermAPIRead, PermAPIDelete

// Workflow
PermWorkflowCreate, PermWorkflowRead, PermWorkflowWrite, PermWorkflowDelete

// ZK Proof
PermZKCreate, PermZKRead, PermZKVerify
Checking Permissions
// Check if role has permission
hasPerm := rbac.HasPermission(role, PermWalletRead)

// Check if role has ANY of multiple permissions
hasAny := rbac.HasAnyPermission(role, PermWalletRead, PermAdminRead)

// Check if role has ALL permissions
hasAll := rbac.HasAllPermissions(role, PermWalletRead, PermPortfolioRead)

// Get all permissions for a user
perms, err := rbac.GetUserPermissions(ctx, userID)
HTTP Middleware
// Require specific permission
rbac.RequirePermission(PermWalletWrite)(handler)

// Require any of multiple permissions
rbac.RequireAnyPermission(PermWalletRead, PermAdminRead)(handler)

// Require all permissions
rbac.RequireAllPermissions(PermWalletRead, PermAnalyticsRead)(handler)

// Require specific role
rbac.RequireRole(RoleAdmin)(handler)
gRPC Interceptors
// gRPC server with permission checking
server := grpc.NewServer(
    grpc.UnaryInterceptor(rbac.GRPCRequirePermission(PermUserRead)),
)

// Or require role
server := grpc.NewServer(
    grpc.UnaryInterceptor(rbac.GRPCRequireRole(RoleAdmin)),
)
Customizing Permissions
// Add permission to role
rbac.AddPermissionToRole(RoleUser, PermCustom)

// Remove permission from role
rbac.RemovePermissionFromRole(RoleUser, PermCustom)

// Set all permissions for a role
rbac.SetRolePermissions(RoleUser, []Permission{PermRead, PermWrite})

// Clear role cache (when user's role changes)
rbac.ClearAllRoleCaches()
rbac.InvalidateRoleCache(userID)

Context Helpers

// Put user in context
ctx := auth.WithUserID(ctx, userID)
ctx = auth.WithRole(ctx, RoleAdmin)

// Get from context
userID := auth.GetUserID(ctx)
role, ok := auth.GetRole(ctx)

Documentation

Overview

Package auth provides JWT (JSON Web Token) authentication and authorization.

This package implements JWT token generation, validation, and refresh functionality with support for both HMAC and RSA signing algorithms. It integrates with the RBAC system for permission-based access control.

Overview

The auth package provides two main components:

  • JWTManager: Handles token issuance, validation, refresh, and blacklisting
  • TokenBlacklist: Manages revoked tokens for logout functionality

JWT tokens contain standard claims (subject, issuer, audience, expiration) plus custom claims for roles and permissions from the RBAC system.

Token Generation

Generate access/refresh token pairs for authenticated users:

jwtManager := auth.NewJWTManager(auth.JWTConfig{
    SigningKey:        []byte("your-secret-key"),
    Issuer:           "your-app",
    Audience:         "your-api",
    AccessTokenTTL:  15 * time.Minute,
    RefreshTokenTTL: 7 * 24 * time.Hour,
}, rbac)

tokens, err := jwtManager.GenerateToken(ctx, "user123", "user@example.com", nil)

Token Validation

Validate tokens in HTTP handlers or middleware:

claims, err := jwtManager.ValidateToken(tokenString)
if err != nil {
    return err // invalid/expired token
}

Token Refresh

Refresh expired access tokens using refresh tokens:

newTokens, err := jwtManager.RefreshTokens(refreshToken)

Token Invalidation (Logout)

Invalidate tokens for logout using the blacklist:

blacklist := auth.NewTokenBlacklist()
jwtManager.SetBlacklist(blacklist)
jwtManager.InvalidateToken(accessToken)

RSA Support

For production environments, use RSA keys for enhanced security:

rsaMaker, _ := auth.NewRSAJWTMaker(2048)
accessToken, _ := rsaMaker.CreateToken("user123")
claims, _ := rsaMaker.VerifyToken(accessToken)

Security Considerations

  • Always use RS256 (RSA) in production with key rotation
  • Keep signing keys secure; never log or expose them
  • Set appropriate token TTLs (shorter access, longer refresh)
  • Implement token rotation on privilege escalation
  • Use the blacklist for sensitive operations (password change, logout)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidAPIKey  = errors.New("invalid API key")
	ErrAPIKeyExpired  = errors.New("API key expired")
	ErrAPIKeyRevoked  = errors.New("API key revoked")
	ErrAPIKeyNotFound = errors.New("API key not found")
)
View Source
var (
	ErrInvalidToken    = errors.New("invalid token")
	ErrTokenExpired    = errors.New("token expired")
	ErrInvalidIssuer   = errors.New("invalid issuer")
	ErrInvalidAudience = errors.New("invalid audience")
)

Functions

func GenerateKeyPair added in v0.1.3

func GenerateKeyPair(bits int) (*rsa.PrivateKey, error)

GenerateKeyPair generates an RSA key pair.

func GenerateRandomState added in v0.1.3

func GenerateRandomState() string

GenerateRandomState generates a random state string for OAuth flows.

func GenerateSecureToken added in v0.1.3

func GenerateSecureToken(length int) string

GenerateSecureToken generates a cryptographically secure random token. Used for CSRF protection, OAuth state, etc.

func GetJWTField added in v0.1.3

func GetJWTField(tokenString, field string) (interface{}, error)

GetJWTField extracts a field from the token payload without validation.

func GetUserID added in v0.1.2

func GetUserID(ctx context.Context) string

GetUserID retrieves the user ID from the context

func NewInMemoryAPIKeyStore added in v0.1.43

func NewInMemoryAPIKeyStore() *inMemoryAPIKeyStore

func NewInMemoryAuditLogger added in v0.1.43

func NewInMemoryAuditLogger(maxSize int) *inMemoryAuditLogger

func ParseJWTExpiry added in v0.1.3

func ParseJWTExpiry(tokenString string) (time.Time, error)

ParseJWTExpiry extracts the expiration time from a token without validation.

func ParseJWTIssuedAt added in v0.1.3

func ParseJWTIssuedAt(tokenString string) (time.Time, error)

ParseJWTIssuedAt extracts the issued-at time from a token without validation.

func VerifyState added in v0.1.3

func VerifyState(expected, actual string) bool

VerifyState verifies OAuth state strings using constant-time comparison.

func WithRole added in v0.1.2

func WithRole(ctx context.Context, role Role) context.Context

WithRole adds a role to the context

func WithUserID added in v0.1.2

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds a user ID to the context

Types

type APIKey added in v0.1.43

type APIKey struct {
	ID          string
	Name        string
	KeyHash     string
	Permissions []string
	Roles       []string
	TenantID    string
	ExpiresAt   time.Time
	RevokedAt   *time.Time
	CreatedAt   time.Time
	LastUsedAt  *time.Time
}

type APIKeyKeyConfig added in v0.1.43

type APIKeyKeyConfig struct {
	Store     APIKeyStore
	KeyPrefix string
	KeyLength int
}

type APIKeyManager added in v0.1.43

type APIKeyManager struct {
	// contains filtered or unexported fields
}

func NewAPIKeyManager added in v0.1.43

func NewAPIKeyManager(store APIKeyKeyConfig) *APIKeyManager

func (*APIKeyManager) CreateKey added in v0.1.43

func (m *APIKeyManager) CreateKey(ctx context.Context, name string, permissions, roles []string, tenantID string, ttl time.Duration) (*CreatedAPIKey, error)

func (*APIKeyManager) GetKey added in v0.1.43

func (m *APIKeyManager) GetKey(ctx context.Context, id string) (*APIKey, error)

func (*APIKeyManager) ListKeys added in v0.1.43

func (m *APIKeyManager) ListKeys(ctx context.Context, tenantID string) ([]*APIKey, error)

func (*APIKeyManager) RevokeKey added in v0.1.43

func (m *APIKeyManager) RevokeKey(ctx context.Context, id string) error

func (*APIKeyManager) ValidateKey added in v0.1.43

func (m *APIKeyManager) ValidateKey(ctx context.Context, rawKey string) (*APIKey, error)

type APIKeyStore added in v0.1.43

type APIKeyStore interface {
	Create(ctx context.Context, key *APIKey) error
	Get(ctx context.Context, id string) (*APIKey, error)
	GetByHash(ctx context.Context, keyHash string) (*APIKey, error)
	List(ctx context.Context, tenantID string) ([]*APIKey, error)
	Revoke(ctx context.Context, id string) error
	Delete(ctx context.Context, id string) error
	UpdateLastUsed(ctx context.Context, id string) error
}

type AuditEvent added in v0.1.43

type AuditEvent struct {
	Type      AuditEventType         `json:"type"`
	Timestamp time.Time              `json:"timestamp"`
	UserID    string                 `json:"user_id,omitempty"`
	TenantID  string                 `json:"tenant_id,omitempty"`
	IPAddress string                 `json:"ip_address,omitempty"`
	UserAgent string                 `json:"user_agent,omitempty"`
	Success   bool                   `json:"success"`
	Error     string                 `json:"error,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

func (AuditEvent) String added in v0.1.43

func (e AuditEvent) String() string

func (AuditEvent) ToJSON added in v0.1.43

func (e AuditEvent) ToJSON() (string, error)

type AuditEventType added in v0.1.43

type AuditEventType string
const (
	EventLogin            AuditEventType = "login"
	EventLogout           AuditEventType = "logout"
	EventTokenRefresh     AuditEventType = "token_refresh"
	EventTokenInvalidate  AuditEventType = "token_invalidate"
	EventPermissionDenied AuditEventType = "permission_denied"
	EventRoleChange       AuditEventType = "role_change"
	EventAPIKeyCreated    AuditEventType = "api_key_created"
	EventAPIKeyRevoked    AuditEventType = "api_key_revoked"
	EventAPIKeyUsed       AuditEventType = "api_key_used"
	EventAuthFailure      AuditEventType = "auth_failure"
)

type AuditFilter added in v0.1.43

type AuditFilter struct {
	UserID    string
	TenantID  string
	EventType AuditEventType
	StartTime time.Time
	EndTime   time.Time
	Limit     int
}

type AuditLogger added in v0.1.43

type AuditLogger interface {
	Log(ctx context.Context, event AuditEvent)
	Query(ctx context.Context, filter AuditFilter) ([]AuditEvent, error)
}

type AuditRecorder added in v0.1.43

type AuditRecorder struct {
	// contains filtered or unexported fields
}

func NewAuditRecorder added in v0.1.43

func NewAuditRecorder(logger AuditLogger) *AuditRecorder

func (*AuditRecorder) Query added in v0.1.43

func (r *AuditRecorder) Query(ctx context.Context, filter AuditFilter) ([]AuditEvent, error)

func (*AuditRecorder) RecordAPIKeyUsed added in v0.1.43

func (r *AuditRecorder) RecordAPIKeyUsed(ctx context.Context, keyID, tenantID, ipAddress string, success bool)

func (*AuditRecorder) RecordAuthFailure added in v0.1.43

func (r *AuditRecorder) RecordAuthFailure(ctx context.Context, userID, reason, ipAddress string)

func (*AuditRecorder) RecordLogin added in v0.1.43

func (r *AuditRecorder) RecordLogin(ctx context.Context, userID, tenantID, ipAddress, userAgent string, success bool, err error)

func (*AuditRecorder) RecordLogout added in v0.1.43

func (r *AuditRecorder) RecordLogout(ctx context.Context, userID, tenantID string)

func (*AuditRecorder) RecordPermissionDenied added in v0.1.43

func (r *AuditRecorder) RecordPermissionDenied(ctx context.Context, userID, permission, resource string)

func (*AuditRecorder) RecordTokenRefresh added in v0.1.43

func (r *AuditRecorder) RecordTokenRefresh(ctx context.Context, userID, tenantID string)

type CachedRoleStore

type CachedRoleStore struct {
	// contains filtered or unexported fields
}

CachedRoleStore wraps a RoleStore with in-memory caching

func NewCachedRoleStore

func NewCachedRoleStore(store RoleStore, ttl time.Duration) *CachedRoleStore

NewCachedRoleStore creates a new cached role store with the specified TTL

func (*CachedRoleStore) ClearCache

func (s *CachedRoleStore) ClearCache()

ClearCache clears all cached roles

func (*CachedRoleStore) GetUserRole

func (s *CachedRoleStore) GetUserRole(ctx context.Context, userID string) (Role, error)

GetUserRole retrieves the user role from cache or backing store

func (*CachedRoleStore) InvalidateCache

func (s *CachedRoleStore) InvalidateCache(userID string)

InvalidateCache invalidates the cached role for a specific user

func (*CachedRoleStore) Stop added in v0.1.2

func (s *CachedRoleStore) Stop()

Stop stops the background cleanup goroutine

type CreatedAPIKey added in v0.1.43

type CreatedAPIKey struct {
	ID        string
	RawKey    string
	ExpiresAt time.Time
}

type DatabaseRoleStore

type DatabaseRoleStore struct {
	// contains filtered or unexported fields
}

DatabaseRoleStore implements RoleStore for database-backed role retrieval

func NewDatabaseRoleStore

func NewDatabaseRoleStore(getRole func(ctx context.Context, userID string) (Role, error)) *DatabaseRoleStore

NewDatabaseRoleStore creates a new database-backed role store

func (*DatabaseRoleStore) GetUserRole

func (s *DatabaseRoleStore) GetUserRole(ctx context.Context, userID string) (Role, error)

GetUserRole retrieves the user role from the database

type JWTConfig added in v0.1.3

type JWTConfig struct {
	SigningKey      []byte          // Secret key for HMAC signing (HS256/HS384/HS512)
	PublicKey       *rsa.PublicKey  // RSA public key for RS256 verification
	PrivateKey      *rsa.PrivateKey // RSA private key for RS256 signing
	Algorithm       string          // Signing algorithm: "HS256", "HS384", "HS512", "RS256"
	Issuer          string          // Token issuer (iss claim)
	Audience        string          // Expected audience (aud claim)
	AccessTokenTTL  time.Duration   // Access token lifetime (default: 15 minutes)
	RefreshTokenTTL time.Duration   // Refresh token lifetime (default: 7 days)
}

JWTConfig holds configuration for JWT token operations.

type JWTMaker added in v0.1.3

type JWTMaker struct {
	// contains filtered or unexported fields
}

JWTMaker provides simple HMAC-based JWT operations. Suitable for development or simple use cases.

func NewJWTMaker added in v0.1.3

func NewJWTMaker(secretKey string) *JWTMaker

NewJWTMaker creates a JWTMaker with the given secret key.

func (*JWTMaker) CreateToken added in v0.1.3

func (m *JWTMaker) CreateToken(username string) (string, error)

CreateToken creates a JWT with the username as subject.

func (*JWTMaker) SetTokenDuration added in v0.1.3

func (m *JWTMaker) SetTokenDuration(d time.Duration)

SetTokenDuration sets the token duration.

func (*JWTMaker) VerifyToken added in v0.1.3

func (m *JWTMaker) VerifyToken(tokenString string) (*jwt.RegisteredClaims, error)

VerifyToken verifies and returns claims from a token.

type JWTManager added in v0.1.3

type JWTManager struct {
	// contains filtered or unexported fields
}

JWTManager handles JWT token generation, validation, and refresh.

func NewJWTManager added in v0.1.3

func NewJWTManager(config JWTConfig, rbac *RBAC) *JWTManager

NewJWTManager creates a new JWT manager with the given configuration. If rbac is provided, permissions will be automatically loaded from RBAC on token generation. Default TTLs: AccessToken=15min, RefreshToken=7 days. Default algorithm: HS256.

func (*JWTManager) GenerateToken added in v0.1.3

func (j *JWTManager) GenerateToken(ctx context.Context, userID, email string, roles []string) (*TokenPair, error)

GenerateToken creates a new access/refresh token pair for a user. If roles is nil and rbac is configured, permissions are loaded from RBAC.

func (*JWTManager) GenerateTokenWithTenant added in v0.1.3

func (j *JWTManager) GenerateTokenWithTenant(ctx context.Context, userID, email, tenantID string, roles []string, metadata map[string]string) (*TokenPair, error)

GenerateTokenWithTenant creates tokens with tenant context for multi-tenant applications.

func (*JWTManager) InvalidateToken added in v0.1.3

func (j *JWTManager) InvalidateToken(tokenString string) error

InvalidateToken adds a token to the blacklist for logout.

func (*JWTManager) RefreshTokens added in v0.1.3

func (j *JWTManager) RefreshTokens(refreshToken string) (*TokenPair, error)

RefreshTokens creates new access/refresh tokens using a valid refresh token.

func (*JWTManager) SetBlacklist added in v0.1.3

func (j *JWTManager) SetBlacklist(blacklist *TokenBlacklist)

SetBlacklist sets the token blacklist for logout support.

func (*JWTManager) ValidateToken added in v0.1.3

func (j *JWTManager) ValidateToken(tokenString string) (*TokenClaims, error)

ValidateToken validates a token string and returns the claims. Validates: signature, expiration, issuer, audience, and blacklist.

type Permission

type Permission string

Permission represents a specific permission in the system

const (
	// Wallet permissions
	PermWalletRead   Permission = "wallet:read"
	PermWalletWrite  Permission = "wallet:write"
	PermWalletDelete Permission = "wallet:delete"

	// Portfolio permissions
	PermPortfolioRead   Permission = "portfolio:read"
	PermPortfolioWrite  Permission = "portfolio:write"
	PermPortfolioDelete Permission = "portfolio:delete"

	// Analytics permissions
	PermAnalyticsRead     Permission = "analytics:read"
	PermAnalyticsAdvanced Permission = "analytics:advanced"

	// Billing permissions
	PermBillingRead   Permission = "billing:read"
	PermBillingWrite  Permission = "billing:write"
	PermBillingDelete Permission = "billing:delete"

	// User permissions
	PermUserRead   Permission = "user:read"
	PermUserWrite  Permission = "user:write"
	PermUserDelete Permission = "user:delete"

	// Admin permissions
	PermAdminRead   Permission = "admin:read"
	PermAdminWrite  Permission = "admin:write"
	PermAdminDelete Permission = "admin:delete"

	// API permissions
	PermAPICreate Permission = "api:create"
	PermAPIRead   Permission = "api:read"
	PermAPIWrite  Permission = "api:write"
	PermAPIDelete Permission = "api:delete"

	// Workflow permissions
	PermWorkflowCreate Permission = "workflow:create"
	PermWorkflowRead   Permission = "workflow:read"
	PermWorkflowWrite  Permission = "workflow:write"
	PermWorkflowDelete Permission = "workflow:delete"

	// ZK proof permissions
	PermZKCreate Permission = "zk:create"
	PermZKRead   Permission = "zk:read"
	PermZKVerify Permission = "zk:verify"
)

type RBAC

type RBAC struct {
	// contains filtered or unexported fields
}

RBAC handles role-based access control

func NewRBAC

func NewRBAC(roleStore RoleStore) *RBAC

NewRBAC creates a new RBAC instance with default role permissions If a roleStore is provided, it will be used for database-backed role retrieval. If nil, a default in-memory role store will be used (returns RoleUser for all users).

func (*RBAC) AddPermissionToRole

func (r *RBAC) AddPermissionToRole(role Role, perm Permission)

AddPermissionToRole adds a permission to a role

func (*RBAC) CheckPermission

func (r *RBAC) CheckPermission(ctx context.Context, userID string, perm Permission) error

CheckPermission checks if a user has a specific permission

func (*RBAC) ClearAllRoleCaches

func (r *RBAC) ClearAllRoleCaches()

ClearAllRoleCaches clears all cached role data

func (*RBAC) GRPCRequireAnyPermission

func (r *RBAC) GRPCRequireAnyPermission(perms ...Permission) grpc.UnaryServerInterceptor

GRPCRequireAnyPermission creates a gRPC interceptor that requires any of the specified permissions

func (*RBAC) GRPCRequirePermission

func (r *RBAC) GRPCRequirePermission(perm Permission) grpc.UnaryServerInterceptor

GRPCRequirePermission creates a gRPC interceptor that requires a specific permission

func (*RBAC) GRPCRequireRole

func (r *RBAC) GRPCRequireRole(roles ...Role) grpc.UnaryServerInterceptor

GRPCRequireRole creates a gRPC interceptor that requires a specific role

func (*RBAC) GetEffectivePermissions added in v0.1.43

func (r *RBAC) GetEffectivePermissions(role Role) []Permission

GetEffectivePermissions returns all permissions for a role including inherited ones

func (*RBAC) GetRole

func (r *RBAC) GetRole(ctx context.Context, userID string) (Role, error)

GetRole retrieves the role for a user from the role store It uses the configured RoleStore (database, cache, etc.) for role lookup

func (*RBAC) GetRoleHierarchy added in v0.1.43

func (r *RBAC) GetRoleHierarchy(role Role) []Role

GetRoleHierarchy returns parent roles for a role

func (*RBAC) GetUserPermissions

func (r *RBAC) GetUserPermissions(ctx context.Context, userID string) ([]Permission, error)

GetUserPermissions retrieves all permissions for a user

func (*RBAC) HasAllPermissions

func (r *RBAC) HasAllPermissions(role Role, perms ...Permission) bool

HasAllPermissions checks if a role has all of the specified permissions

func (*RBAC) HasAnyPermission

func (r *RBAC) HasAnyPermission(role Role, perms ...Permission) bool

HasAnyPermission checks if a role has any of the specified permissions

func (*RBAC) HasPermission

func (r *RBAC) HasPermission(role Role, perm Permission) bool

HasPermission checks if a role has a specific permission It also checks inherited permissions from parent roles in the hierarchy

func (*RBAC) InvalidateRoleCache

func (r *RBAC) InvalidateRoleCache(userID string)

InvalidateRoleCache invalidates any cached role data for a specific user This is useful when a user's role changes

func (*RBAC) RemovePermissionFromRole

func (r *RBAC) RemovePermissionFromRole(role Role, perm Permission)

RemovePermissionFromRole removes a permission from a role

func (*RBAC) RequireAllPermissions

func (r *RBAC) RequireAllPermissions(perms ...Permission) func(http.Handler) http.Handler

RequireAllPermissions creates an HTTP middleware that requires all of the specified permissions

func (*RBAC) RequireAnyPermission

func (r *RBAC) RequireAnyPermission(perms ...Permission) func(http.Handler) http.Handler

RequireAnyPermission creates an HTTP middleware that requires any of the specified permissions

func (*RBAC) RequirePermission

func (r *RBAC) RequirePermission(perm Permission) func(http.Handler) http.Handler

RequirePermission creates an HTTP middleware that requires a specific permission

func (*RBAC) RequireRole

func (r *RBAC) RequireRole(roles ...Role) func(http.Handler) http.Handler

RequireRole creates an HTTP middleware that requires a specific role

func (*RBAC) SetRoleHierarchy added in v0.1.43

func (r *RBAC) SetRoleHierarchy(role Role, parentRoles []Role)

SetRoleHierarchy sets parent roles for a role

func (*RBAC) SetRolePermissions

func (r *RBAC) SetRolePermissions(role Role, permissions []Permission)

SetRolePermissions allows customizing permissions for a role

func (*RBAC) SetRoleStore

func (r *RBAC) SetRoleStore(store RoleStore)

SetRoleStore sets the role store for role retrieval

type RSAJWTMaker added in v0.1.3

type RSAJWTMaker struct {
	// contains filtered or unexported fields
}

RSAJWTMaker provides RSA-based JWT operations. Recommended for production use with proper key management.

func NewRSAJWTMaker added in v0.1.3

func NewRSAJWTMaker(bits int) (*RSAJWTMaker, error)

NewRSAJWTMaker creates a new RSA JWT maker with the specified key size. Common key sizes: 2048 (recommended), 4096 (high security).

func (*RSAJWTMaker) CreateToken added in v0.1.3

func (m *RSAJWTMaker) CreateToken(username string) (string, error)

CreateToken creates a JWT with the username as subject using RSA.

func (*RSAJWTMaker) PrivateKey added in v0.1.3

func (m *RSAJWTMaker) PrivateKey() *rsa.PrivateKey

PrivateKey returns the RSA private key.

func (*RSAJWTMaker) PrivateKeyPEM added in v0.1.3

func (m *RSAJWTMaker) PrivateKeyPEM() ([]byte, error)

PrivateKeyPEM returns the private key in PEM format.

func (*RSAJWTMaker) PublicKey added in v0.1.3

func (m *RSAJWTMaker) PublicKey() *rsa.PublicKey

PublicKey returns the RSA public key.

func (*RSAJWTMaker) PublicKeyPEM added in v0.1.3

func (m *RSAJWTMaker) PublicKeyPEM() ([]byte, error)

PublicKeyPEM returns the public key in PEM format.

func (*RSAJWTMaker) SetTokenDuration added in v0.1.3

func (m *RSAJWTMaker) SetTokenDuration(d time.Duration)

SetTokenDuration sets the token duration.

func (*RSAJWTMaker) VerifyToken added in v0.1.3

func (m *RSAJWTMaker) VerifyToken(tokenString string) (*jwt.RegisteredClaims, error)

VerifyToken verifies and returns claims from an RSA-signed token.

type RedisClient added in v0.1.3

type RedisClient interface {
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
	Get(ctx context.Context, key string) (string, error)
	Del(ctx context.Context, keys ...string) error
	Exists(ctx context.Context, keys ...string) (int, error)
}

RedisClient interface for Redis-backed blacklist.

type Role

type Role string

Role represents a user role in the system

const (
	RoleAdmin     Role = "admin"
	RoleUser      Role = "user"
	RoleReadOnly  Role = "readonly"
	RolePremium   Role = "premium"
	RoleDeveloper Role = "developer"
)

func GetRole added in v0.1.2

func GetRole(ctx context.Context) (Role, bool)

GetRole retrieves the role from the context

type RoleStore

type RoleStore interface {
	// GetUserRole retrieves the role for a user from the data source
	GetUserRole(ctx context.Context, userID string) (Role, error)
}

RoleStore defines the interface for retrieving user roles from a data source

type RotationConfig added in v0.1.43

type RotationConfig struct {
	EnableRotation     bool
	RotationThreshold  time.Duration
	MaxRefreshCount    int
	RotationKeyBuilder func(*JWTManager) interface{}
}

type TokenBlacklist added in v0.1.3

type TokenBlacklist struct {
	// contains filtered or unexported fields
}

TokenBlacklist stores invalidated token IDs for logout functionality. Supports both in-memory and Redis-backed storage.

func NewTokenBlacklist added in v0.1.3

func NewTokenBlacklist() *TokenBlacklist

NewTokenBlacklist creates a new in-memory token blacklist.

func (*TokenBlacklist) Blacklist added in v0.1.3

func (b *TokenBlacklist) Blacklist(tokenID string, ttl time.Duration) error

Blacklist adds a token ID to the blacklist.

func (*TokenBlacklist) CleanExpired added in v0.1.3

func (b *TokenBlacklist) CleanExpired()

CleanExpired removes expired entries from in-memory blacklist.

func (*TokenBlacklist) IsBlacklisted added in v0.1.3

func (b *TokenBlacklist) IsBlacklisted(tokenID string) (bool, error)

IsBlacklisted checks if a token ID is in the blacklist.

func (*TokenBlacklist) SetRedisClient added in v0.1.3

func (b *TokenBlacklist) SetRedisClient(client RedisClient)

SetRedisClient configures a Redis client for distributed blacklist.

type TokenClaims added in v0.1.3

type TokenClaims struct {
	jwt.RegisteredClaims                   // Standard claims (iat, exp, sub, iss, aud, etc.)
	UserID               string            `json:"user_id"`             // User identifier
	Email                string            `json:"email"`               // User email address
	Roles                []string          `json:"roles"`               // User roles
	Permissions          []string          `json:"permissions"`         // User permissions
	TenantID             string            `json:"tenant_id,omitempty"` // Multi-tenant identifier
	Metadata             map[string]string `json:"metadata,omitempty"`  // Additional metadata
}

TokenClaims represents custom JWT claims including user identity and permissions.

type TokenPair added in v0.1.3

type TokenPair struct {
	AccessToken  string `json:"access_token"`  // JWT for API access
	RefreshToken string `json:"refresh_token"` // Long-lived token for refresh
	ExpiresAt    int64  `json:"expires_at"`    // Unix timestamp when access token expires
	TokenType    string `json:"token_type"`    // Always "Bearer"
}

TokenPair represents an issued access/refresh token pair.

type TokenRotation added in v0.1.43

type TokenRotation struct {
	// contains filtered or unexported fields
}

func NewTokenRotation added in v0.1.43

func NewTokenRotation(config RotationConfig) *TokenRotation

func (*TokenRotation) GetRefreshCount added in v0.1.43

func (r *TokenRotation) GetRefreshCount(tokenID string) int

func (*TokenRotation) RecordRefresh added in v0.1.43

func (r *TokenRotation) RecordRefresh(tokenID string)

func (*TokenRotation) ResetRotation added in v0.1.43

func (r *TokenRotation) ResetRotation(tokenID string)

func (*TokenRotation) ShouldRotate added in v0.1.43

func (r *TokenRotation) ShouldRotate(tokenID string) bool

Jump to

Keyboard shortcuts

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