Documentation
¶
Index ¶
- Constants
- type AuditEvent
- type AuditLogger
- func (a *AuditLogger) LogEvent(event *AuditEvent) error
- func (a *AuditLogger) LogLogin(user *types.User, clientIP net.IP, userAgent string) error
- func (a *AuditLogger) LogLoginFailed(email string, organizationID string, clientIP net.IP, userAgent string, ...) error
- func (a *AuditLogger) LogLogout(userID, organizationID string, clientIP net.IP, voluntary bool) error
- func (a *AuditLogger) LogSuspiciousActivity(organizationID, actorID string, clientIP net.IP, activity string, ...) error
- func (a *AuditLogger) LogTokenRefresh(userID, organizationID string, clientIP net.IP, success bool, errorMsg string) error
- func (a *AuditLogger) LogUserCreated(user *types.User, creatorID string, clientIP net.IP) error
- type CacheConfig
- type Claims
- type CleanupConfig
- type CleanupStats
- type Config
- type ConfigService
- func (s *ConfigService) GetConfiguration(orgID uuid.UUID) (*types.AuthConfigurationResponse, error)
- func (s *ConfigService) GetDefaults() *types.AuthConfigDefaults
- func (s *ConfigService) UpdateConfiguration(orgID uuid.UUID, req *types.CompleteAuthConfigurationRequest, ...) (*types.AuthConfigurationResponse, error)
- func (s *ConfigService) ValidateConfiguration(req *types.CompleteAuthConfigurationRequest) error
- type JWK
- type JWKS
- type JWTManager
- func (j *JWTManager) CleanupExpiredTokens(ctx context.Context) error
- func (j *JWTManager) Close() error
- func (j *JWTManager) GenerateAccessToken(user *types.User) (string, error)
- func (j *JWTManager) GenerateRefreshToken(user *types.User) (string, error)
- func (j *JWTManager) InvalidateToken(ctx context.Context, tokenString string) error
- func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error)
- type LoginAttempt
- type LoginAttemptTracker
- func (t *LoginAttemptTracker) GetRecentFailedAttempts(email string, clientIP net.IP, since time.Duration) (int, error)
- func (t *LoginAttemptTracker) IsRateLimited(email string, clientIP net.IP) (bool, time.Duration, error)
- func (t *LoginAttemptTracker) RecordLoginAttempt(email string, clientIP net.IP, success bool) error
- type LoginContext
- type MemoryTokenCache
- type Middleware
- func (m *Middleware) OptionalAuth() gin.HandlerFunc
- func (m *Middleware) RequireAPIKey() gin.HandlerFunc
- func (m *Middleware) RequireAdmin() gin.HandlerFunc
- func (m *Middleware) RequireAllPermissions(permissions []string) gin.HandlerFunc
- func (m *Middleware) RequireAnyPermission(permissions []string) gin.HandlerFunc
- func (m *Middleware) RequireAuth() gin.HandlerFunc
- func (m *Middleware) RequireOrganizationAccess() gin.HandlerFunc
- func (m *Middleware) RequirePermission(permission string) gin.HandlerFunc
- func (m *Middleware) RequireResourceAccess(resource, action string) gin.HandlerFunc
- func (m *Middleware) RequireRole(requiredRole string) gin.HandlerFunc
- func (m *Middleware) RequireSystemAdmin() gin.HandlerFunc
- func (m *Middleware) RequireUser() gin.HandlerFunc
- type OAuthConfig
- type OAuthService
- func (s *OAuthService) CheckUserConsent(ctx context.Context, userID, clientID, scope string) (bool, error)
- func (s *OAuthService) CreateAuthorizationCode(ctx context.Context, clientID, userID, redirectURI, scope string, ...) (string, error)
- func (s *OAuthService) CreateUserConsent(ctx context.Context, userID, clientID, scope string) error
- func (s *OAuthService) GetClient(ctx context.Context, clientID string) (*types.OAuthClient, error)
- func (s *OAuthService) GetDB() *sqlx.DB
- func (s *OAuthService) GetJWKS() (*JWKS, error)
- func (s *OAuthService) GetProtectedResourceMetadata() *types.ProtectedResourceMetadata
- func (s *OAuthService) GetServerMetadata() *types.AuthorizationServerMetadata
- func (s *OAuthService) IntrospectToken(ctx context.Context, token string) (*types.IntrospectionResponse, error)
- func (s *OAuthService) IssueToken(ctx context.Context, req *types.TokenRequest) (*types.TokenResponse, error)
- func (s *OAuthService) RegisterClient(ctx context.Context, req *types.ClientRegistrationRequest, orgID string) (*types.ClientRegistrationResponse, error)
- func (s *OAuthService) RevokeToken(ctx context.Context, token string, clientID string, clientSecret string) error
- func (s *OAuthService) ValidateToken(ctx context.Context, bearerToken string) (*types.OAuthToken, error)
- type PolicyCondition
- type PolicyEngine
- type RBAC
- func (r *RBAC) CanAccessAllEndpoints(role string) bool
- func (r *RBAC) CanAccessNamespaceEndpoints(role string) bool
- func (r *RBAC) CanAccessResource(role, resource, action string) bool
- func (r *RBAC) CanElevateToRole(currentRole, targetRole string) bool
- func (r *RBAC) CanManageResource(role, resource string) bool
- func (r *RBAC) GetAllRoles() []string
- func (r *RBAC) GetRoleLevel(role string) int
- func (r *RBAC) GetRolePermissions(role string) []string
- func (r *RBAC) HasAllPermissions(role string, permissions []string) bool
- func (r *RBAC) HasAnyPermission(role string, permissions []string) bool
- func (r *RBAC) HasPermission(role, permission string) bool
- func (r *RBAC) HasRequiredRole(userRole, requiredRole string) bool
- func (r *RBAC) IsAdmin(role string) bool
- func (r *RBAC) IsUser(role string) bool
- func (r *RBAC) IsViewer(role string) bool
- func (r *RBAC) ValidateRole(role string) bool
- type RedisTokenCache
- type RefreshTokenResponse
- type RequestContext
- type Service
- func (s *Service) CreateAPIKey(userID string, req *types.CreateAPIKeyRequest) (*types.CreateAPIKeyResponse, error)
- func (s *Service) CreateUser(req *types.CreateUserRequest) (*types.User, error)
- func (s *Service) DeleteAPIKey(userID, keyID string) error
- func (s *Service) DeleteAPIKeyByAdmin(organizationID, keyID string) error
- func (s *Service) DeleteUser(userID string) error
- func (s *Service) GetAttemptTracker() *LoginAttemptTracker
- func (s *Service) GetAuditLogger() *AuditLogger
- func (s *Service) GetJWTManager() *JWTManager
- func (s *Service) GetUserByEmail(email string) (*types.User, error)
- func (s *Service) GetUserByID(userID string) (*types.User, error)
- func (s *Service) ListAPIKeys(userID string) ([]*types.APIKey, error)
- func (s *Service) ListAllAPIKeys(organizationID string) ([]*types.APIKey, error)
- func (s *Service) Login(email, password string) (*types.LoginResponse, error)
- func (s *Service) LoginWithContext(email, password string, ctx *LoginContext) (*types.LoginResponse, error)
- func (s *Service) Logout(accessToken string) error
- func (s *Service) LogoutWithContext(accessToken string, ctx *LoginContext, voluntary bool) error
- func (s *Service) RefreshToken(refreshToken string) (*types.LoginResponse, error)
- func (s *Service) RefreshTokenWithContext(refreshToken string, ctx *LoginContext) (*types.LoginResponse, error)
- func (s *Service) RefreshTokenWithRotation(refreshToken string, ctx *LoginContext) (*RefreshTokenResponse, error)
- func (s *Service) RevokeAPIKey(keyID string) error
- func (s *Service) UpdateUser(userID string, req *types.UpdateUserRequest) (*types.User, error)
- func (s *Service) ValidateAPIKey(keyString string) (*types.APIKey, error)
- type ServiceInterface
- type TokenCache
- type TokenCleanupService
Constants ¶
const ( ActionUserLogin = "user.login" ActionUserLoginFailed = "user.login.failed" ActionUserLogout = "user.logout" ActionTokenRefresh = "user.token.refresh" ActionTokenInvalidate = "user.token.invalidate" ActionUserCreated = "user.created" ActionUserUpdated = "user.updated" ActionUserDeleted = "user.deleted" ActionAPIKeyCreated = "api_key.created" ActionAPIKeyRevoked = "api_key.revoked" ActionPasswordChanged = "user.password.changed" ActionAccountLocked = "user.account.locked" ActionAccountUnlocked = "user.account.unlocked" ActionSuspiciousActivity = "security.suspicious_activity" )
Authentication audit actions
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AuditEvent ¶
type AuditEvent struct { OldValues map[string]interface{} NewValues map[string]interface{} Metadata map[string]interface{} OrganizationID string Action string ResourceType string ResourceID string ActorID string ErrorMessage string ActorIP net.IP Success bool }
AuditEvent represents an authentication audit event
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger handles authentication audit logging
func NewAuditLogger ¶
func NewAuditLogger(db *sql.DB) *AuditLogger
NewAuditLogger creates a new audit logger
func (*AuditLogger) LogEvent ¶
func (a *AuditLogger) LogEvent(event *AuditEvent) error
LogEvent logs an audit event to the database
func (*AuditLogger) LogLoginFailed ¶
func (a *AuditLogger) LogLoginFailed(email string, organizationID string, clientIP net.IP, userAgent string, reason string) error
LogLoginFailed logs a failed login attempt
func (*AuditLogger) LogLogout ¶
func (a *AuditLogger) LogLogout(userID, organizationID string, clientIP net.IP, voluntary bool) error
LogLogout logs a user logout event
func (*AuditLogger) LogSuspiciousActivity ¶
func (a *AuditLogger) LogSuspiciousActivity(organizationID, actorID string, clientIP net.IP, activity string, details map[string]interface{}) error
LogSuspiciousActivity logs suspicious authentication activity
func (*AuditLogger) LogTokenRefresh ¶
func (a *AuditLogger) LogTokenRefresh(userID, organizationID string, clientIP net.IP, success bool, errorMsg string) error
LogTokenRefresh logs a token refresh event
func (*AuditLogger) LogUserCreated ¶
LogUserCreated logs user creation event
type CacheConfig ¶
type CacheConfig struct { RedisAddr string `yaml:"redis_addr"` RedisPassword string `yaml:"redis_password"` RedisDB int `yaml:"redis_db"` UseRedis bool `yaml:"use_redis"` }
CacheConfig holds cache configuration
type Claims ¶
type Claims struct { UserID string `json:"user_id"` OrganizationID string `json:"organization_id"` Role string `json:"role"` TokenType string `json:"token_type"` // "access" or "refresh" jwt.RegisteredClaims }
Claims represents JWT claims
type CleanupConfig ¶
type CleanupConfig struct { // How often to run cleanup (default: 1 hour) CleanupInterval time.Duration // How old audit logs should be before cleanup (default: 30 days) AuditLogRetentionPeriod time.Duration // How old login attempt logs should be before cleanup (default: 7 days) LoginAttemptRetentionPeriod time.Duration // Maximum number of records to delete in each cleanup batch (default: 1000) BatchSize int }
CleanupConfig holds configuration for the cleanup service
func DefaultCleanupConfig ¶
func DefaultCleanupConfig() *CleanupConfig
DefaultCleanupConfig returns default cleanup configuration
type CleanupStats ¶
type CleanupStats struct { TotalAuditLogs int `json:"total_audit_logs"` OldAuditLogs int `json:"old_audit_logs"` TotalLoginAttempts int `json:"total_login_attempts"` OldLoginAttempts int `json:"old_login_attempts"` }
CleanupStats holds statistics about cleanup operations
type Config ¶
type Config struct { JWTSecret string Cache CacheConfig AccessTokenExpiry time.Duration RefreshTokenExpiry time.Duration BCryptCost int }
Config holds authentication service configuration
type ConfigService ¶
type ConfigService struct {
// contains filtered or unexported fields
}
ConfigService handles authentication configuration management
func NewConfigService ¶
func NewConfigService(db models.Database) *ConfigService
NewConfigService creates a new auth configuration service
func (*ConfigService) GetConfiguration ¶
func (s *ConfigService) GetConfiguration(orgID uuid.UUID) (*types.AuthConfigurationResponse, error)
GetConfiguration retrieves the complete auth configuration for an organization
func (*ConfigService) GetDefaults ¶
func (s *ConfigService) GetDefaults() *types.AuthConfigDefaults
GetDefaults returns the default auth configuration
func (*ConfigService) UpdateConfiguration ¶
func (s *ConfigService) UpdateConfiguration(orgID uuid.UUID, req *types.CompleteAuthConfigurationRequest, updatedBy uuid.UUID) (*types.AuthConfigurationResponse, error)
UpdateConfiguration updates the authentication configuration for an organization
func (*ConfigService) ValidateConfiguration ¶
func (s *ConfigService) ValidateConfiguration(req *types.CompleteAuthConfigurationRequest) error
ValidateConfiguration validates auth configuration before applying
type JWK ¶
type JWK struct { KeyType string `json:"kty"` KeyID string `json:"kid,omitempty"` Use string `json:"use,omitempty"` Algorithm string `json:"alg,omitempty"` N string `json:"n,omitempty"` // RSA modulus E string `json:"e,omitempty"` // RSA exponent K string `json:"k,omitempty"` // Symmetric key value X string `json:"x,omitempty"` // EC x coordinate Y string `json:"y,omitempty"` // EC y coordinate Curve string `json:"crv,omitempty"` // EC curve D string `json:"d,omitempty"` // EC private value }
JWK represents a JSON Web Key
type JWTManager ¶
type JWTManager struct {
// contains filtered or unexported fields
}
JWTManager handles JWT token operations
func NewJWTManager ¶
func NewJWTManager(secret string, accessExpiry, refreshExpiry time.Duration) *JWTManager
NewJWTManager creates a new JWT manager
func NewJWTManagerWithCache ¶
func NewJWTManagerWithCache(secret string, accessExpiry, refreshExpiry time.Duration, cache TokenCache) *JWTManager
NewJWTManagerWithCache creates a new JWT manager with custom cache
func (*JWTManager) CleanupExpiredTokens ¶
func (j *JWTManager) CleanupExpiredTokens(ctx context.Context) error
CleanupExpiredTokens removes expired tokens from blacklist Should be called periodically by a background job
func (*JWTManager) GenerateAccessToken ¶
func (j *JWTManager) GenerateAccessToken(user *types.User) (string, error)
GenerateAccessToken generates a new access token
func (*JWTManager) GenerateRefreshToken ¶
func (j *JWTManager) GenerateRefreshToken(user *types.User) (string, error)
GenerateRefreshToken generates a new refresh token
func (*JWTManager) InvalidateToken ¶
func (j *JWTManager) InvalidateToken(ctx context.Context, tokenString string) error
InvalidateToken adds token to blacklist
func (*JWTManager) ValidateToken ¶
func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error)
ValidateToken validates and parses a JWT token
type LoginAttempt ¶
type LoginAttempt struct { CreatedAt time.Time ID string Email string ClientIP net.IP Success bool }
LoginAttempt represents a login attempt record
type LoginAttemptTracker ¶
type LoginAttemptTracker struct {
// contains filtered or unexported fields
}
LoginAttemptTracker tracks failed login attempts for rate limiting and security
func NewLoginAttemptTracker ¶
func NewLoginAttemptTracker(db *sql.DB) *LoginAttemptTracker
NewLoginAttemptTracker creates a new login attempt tracker
func (*LoginAttemptTracker) GetRecentFailedAttempts ¶
func (t *LoginAttemptTracker) GetRecentFailedAttempts(email string, clientIP net.IP, since time.Duration) (int, error)
GetRecentFailedAttempts gets recent failed login attempts for an email or IP
func (*LoginAttemptTracker) IsRateLimited ¶
func (t *LoginAttemptTracker) IsRateLimited(email string, clientIP net.IP) (bool, time.Duration, error)
IsRateLimited checks if login attempts should be rate limited
func (*LoginAttemptTracker) RecordLoginAttempt ¶
RecordLoginAttempt records a login attempt (success or failure)
type LoginContext ¶
LoginContext contains additional context for login attempts
type MemoryTokenCache ¶
type MemoryTokenCache struct {
// contains filtered or unexported fields
}
MemoryTokenCache implements TokenCache using in-memory storage
func NewMemoryTokenCache ¶
func NewMemoryTokenCache() *MemoryTokenCache
NewMemoryTokenCache creates a new memory-backed token cache
func (*MemoryTokenCache) Cleanup ¶
func (m *MemoryTokenCache) Cleanup(ctx context.Context) error
Cleanup removes expired tokens from memory
func (*MemoryTokenCache) Close ¶
func (m *MemoryTokenCache) Close() error
Close is a no-op for memory cache
func (*MemoryTokenCache) IsBlacklisted ¶
IsBlacklisted checks if a token is blacklisted
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware handles authentication and authorization
func NewMiddleware ¶
func NewMiddleware(jwtManager *JWTManager, service *Service) *Middleware
NewMiddleware creates a new auth middleware
func NewMiddlewareWithInterface ¶
func NewMiddlewareWithInterface(jwtManager *JWTManager, service ServiceInterface) *Middleware
NewMiddlewareWithInterface creates a new auth middleware with interface
func (*Middleware) OptionalAuth ¶
func (m *Middleware) OptionalAuth() gin.HandlerFunc
OptionalAuth middleware that allows optional authentication
func (*Middleware) RequireAPIKey ¶
func (m *Middleware) RequireAPIKey() gin.HandlerFunc
RequireAPIKey middleware for API key authentication
func (*Middleware) RequireAdmin ¶
func (m *Middleware) RequireAdmin() gin.HandlerFunc
RequireAdmin middleware that requires admin role or higher
func (*Middleware) RequireAllPermissions ¶
func (m *Middleware) RequireAllPermissions(permissions []string) gin.HandlerFunc
RequireAllPermissions middleware that requires all of the specified permissions
func (*Middleware) RequireAnyPermission ¶
func (m *Middleware) RequireAnyPermission(permissions []string) gin.HandlerFunc
RequireAnyPermission middleware that requires any of the specified permissions
func (*Middleware) RequireAuth ¶
func (m *Middleware) RequireAuth() gin.HandlerFunc
RequireAuth middleware that requires valid authentication
func (*Middleware) RequireOrganizationAccess ¶
func (m *Middleware) RequireOrganizationAccess() gin.HandlerFunc
RequireOrganizationAccess middleware for organization-level access control
func (*Middleware) RequirePermission ¶
func (m *Middleware) RequirePermission(permission string) gin.HandlerFunc
RequirePermission middleware that requires specific permission
func (*Middleware) RequireResourceAccess ¶
func (m *Middleware) RequireResourceAccess(resource, action string) gin.HandlerFunc
RequireResourceAccess middleware for resource-based access control
func (*Middleware) RequireRole ¶
func (m *Middleware) RequireRole(requiredRole string) gin.HandlerFunc
RequireRole middleware that requires specific role
func (*Middleware) RequireSystemAdmin ¶
func (m *Middleware) RequireSystemAdmin() gin.HandlerFunc
RequireSystemAdmin middleware that requires system admin role
func (*Middleware) RequireUser ¶
func (m *Middleware) RequireUser() gin.HandlerFunc
RequireUser middleware that requires user role or higher
type OAuthConfig ¶
type OAuthConfig struct { Issuer string `yaml:"issuer"` AuthorizationEndpoint string `yaml:"authorization_endpoint"` TokenEndpoint string `yaml:"token_endpoint"` RegistrationEndpoint string `yaml:"registration_endpoint"` IntrospectionEndpoint string `yaml:"introspection_endpoint"` RevocationEndpoint string `yaml:"revocation_endpoint"` JWKSUri string `yaml:"jwks_uri"` SupportedGrantTypes []string `yaml:"supported_grant_types"` SupportedResponseTypes []string `yaml:"supported_response_types"` SupportedScopes []string `yaml:"supported_scopes"` TokenExpiry time.Duration `yaml:"token_expiry"` RefreshTokenExpiry time.Duration `yaml:"refresh_token_expiry"` AuthCodeExpiry time.Duration `yaml:"auth_code_expiry"` EnableDynamicRegistration bool `yaml:"enable_dynamic_registration"` RequireClientAuth bool `yaml:"require_client_authentication"` AllowPublicClients bool `yaml:"allow_public_clients"` }
OAuthConfig holds OAuth 2.0 configuration
func DefaultOAuthConfig ¶
func DefaultOAuthConfig() *OAuthConfig
DefaultOAuthConfig returns default OAuth configuration
type OAuthService ¶
type OAuthService struct {
// contains filtered or unexported fields
}
OAuthService handles OAuth 2.0 operations
func NewOAuthService ¶
func NewOAuthService(db *sqlx.DB, jwtSecret string, issuer string, config *OAuthConfig) *OAuthService
NewOAuthService creates a new OAuth service
func (*OAuthService) CheckUserConsent ¶
func (s *OAuthService) CheckUserConsent(ctx context.Context, userID, clientID, scope string) (bool, error)
CheckUserConsent checks if user has already consented to the requested scope
func (*OAuthService) CreateAuthorizationCode ¶
func (s *OAuthService) CreateAuthorizationCode(ctx context.Context, clientID, userID, redirectURI, scope string, codeChallenge, codeChallengeMethod *string) (string, error)
CreateAuthorizationCode creates a new authorization code
func (*OAuthService) CreateUserConsent ¶
func (s *OAuthService) CreateUserConsent(ctx context.Context, userID, clientID, scope string) error
CreateUserConsent creates a user consent record
func (*OAuthService) GetClient ¶
func (s *OAuthService) GetClient(ctx context.Context, clientID string) (*types.OAuthClient, error)
GetClient retrieves an OAuth client by client ID
func (*OAuthService) GetDB ¶
func (s *OAuthService) GetDB() *sqlx.DB
GetDB returns the database connection for use by handlers
func (*OAuthService) GetJWKS ¶
func (s *OAuthService) GetJWKS() (*JWKS, error)
GetJWKS returns the JSON Web Key Set for token verification
func (*OAuthService) GetProtectedResourceMetadata ¶
func (s *OAuthService) GetProtectedResourceMetadata() *types.ProtectedResourceMetadata
GetProtectedResourceMetadata returns OAuth 2.0 Protected Resource Metadata
func (*OAuthService) GetServerMetadata ¶
func (s *OAuthService) GetServerMetadata() *types.AuthorizationServerMetadata
GetServerMetadata returns OAuth 2.0 Authorization Server Metadata
func (*OAuthService) IntrospectToken ¶
func (s *OAuthService) IntrospectToken(ctx context.Context, token string) (*types.IntrospectionResponse, error)
IntrospectToken introspects an OAuth token
func (*OAuthService) IssueToken ¶
func (s *OAuthService) IssueToken(ctx context.Context, req *types.TokenRequest) (*types.TokenResponse, error)
IssueToken issues an access token based on the grant type
func (*OAuthService) RegisterClient ¶
func (s *OAuthService) RegisterClient(ctx context.Context, req *types.ClientRegistrationRequest, orgID string) (*types.ClientRegistrationResponse, error)
RegisterClient handles dynamic client registration
func (*OAuthService) RevokeToken ¶
func (s *OAuthService) RevokeToken(ctx context.Context, token string, clientID string, clientSecret string) error
RevokeToken revokes an OAuth token
func (*OAuthService) ValidateToken ¶
func (s *OAuthService) ValidateToken(ctx context.Context, bearerToken string) (*types.OAuthToken, error)
ValidateToken validates a Bearer token and returns token info
type PolicyCondition ¶
type PolicyCondition struct { Value interface{} `json:"value"` Field string `json:"field"` Operator string `json:"operator"` }
PolicyCondition represents a single policy condition
type PolicyEngine ¶
type PolicyEngine struct {
// contains filtered or unexported fields
}
PolicyEngine handles policy evaluation
func NewPolicyEngine ¶
func NewPolicyEngine(service *Service) *PolicyEngine
NewPolicyEngine creates a new policy engine
func (*PolicyEngine) EvaluateOrganizationPolicies ¶
func (p *PolicyEngine) EvaluateOrganizationPolicies(orgID string, ctx *RequestContext) (bool, error)
EvaluateOrganizationPolicies evaluates organization-level policies
func (*PolicyEngine) EvaluatePolicy ¶
func (p *PolicyEngine) EvaluatePolicy(policy *types.Policy, ctx *RequestContext) (bool, error)
EvaluatePolicy evaluates a policy against a request context
func (*PolicyEngine) EvaluateUserPolicies ¶
func (p *PolicyEngine) EvaluateUserPolicies(userID string, ctx *RequestContext) (bool, error)
EvaluateUserPolicies evaluates all policies for a user
type RBAC ¶
type RBAC struct {
// contains filtered or unexported fields
}
RBAC implements Role-Based Access Control
func NewRBAC ¶
func NewRBAC() *RBAC
NewRBAC creates a new RBAC instance with predefined role permissions
func (*RBAC) CanAccessAllEndpoints ¶
CanAccessAllEndpoints checks if a role has access to all endpoints
func (*RBAC) CanAccessNamespaceEndpoints ¶
CanAccessNamespaceEndpoints checks if a role has access to namespace endpoints
func (*RBAC) CanAccessResource ¶
CanAccessResource checks if a role can access a specific resource type with an action
func (*RBAC) CanElevateToRole ¶
CanElevateToRole checks if a user with currentRole can elevate someone to targetRole
func (*RBAC) CanManageResource ¶
CanManageResource checks if a role has management permissions for a resource
func (*RBAC) GetAllRoles ¶
GetAllRoles returns all available roles
func (*RBAC) GetRoleLevel ¶
GetRoleLevel returns the hierarchy level for a role
func (*RBAC) GetRolePermissions ¶
GetRolePermissions returns all permissions for a role
func (*RBAC) HasAllPermissions ¶
HasAllPermissions checks if a role has all of the specified permissions
func (*RBAC) HasAnyPermission ¶
HasAnyPermission checks if a role has any of the specified permissions
func (*RBAC) HasPermission ¶
HasPermission checks if a role has a specific permission
func (*RBAC) HasRequiredRole ¶
HasRequiredRole checks if user role meets the required role level
func (*RBAC) ValidateRole ¶
ValidateRole checks if a role is valid
type RedisTokenCache ¶
type RedisTokenCache struct {
// contains filtered or unexported fields
}
RedisTokenCache implements TokenCache using Redis
func NewRedisTokenCache ¶
func NewRedisTokenCache(addr, password string, db int) (*RedisTokenCache, error)
NewRedisTokenCache creates a new Redis-backed token cache
func (*RedisTokenCache) Cleanup ¶
func (r *RedisTokenCache) Cleanup(ctx context.Context) error
Cleanup is a no-op for Redis (TTL handles expiration automatically)
func (*RedisTokenCache) Close ¶
func (r *RedisTokenCache) Close() error
Close closes the Redis connection
func (*RedisTokenCache) IsBlacklisted ¶
IsBlacklisted checks if a token is blacklisted
type RefreshTokenResponse ¶
type RefreshTokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` TokenType string `json:"token_type"` ExpiresIn int64 `json:"expires_in"` }
RefreshTokenResponse extends TokenResponse with new refresh token
type RequestContext ¶
type RequestContext struct { UserID string OrganizationID string Role string Method string Path string Headers map[string]string RemoteIP string UserAgent string Timestamp int64 }
RequestContext contains information about the current request
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service handles authentication and user management
func NewService ¶
NewService creates a new authentication service
func (*Service) CreateAPIKey ¶
func (s *Service) CreateAPIKey(userID string, req *types.CreateAPIKeyRequest) (*types.CreateAPIKeyResponse, error)
CreateAPIKey creates a new API key for a user
func (*Service) CreateUser ¶
CreateUser creates a new user
func (*Service) DeleteAPIKey ¶
DeleteAPIKey deletes an API key
func (*Service) DeleteAPIKeyByAdmin ¶
DeleteAPIKeyByAdmin deletes any API key in the organization (admin only)
func (*Service) DeleteUser ¶
DeleteUser soft deletes a user
func (*Service) GetAttemptTracker ¶
func (s *Service) GetAttemptTracker() *LoginAttemptTracker
GetAttemptTracker returns the login attempt tracker instance
func (*Service) GetAuditLogger ¶
func (s *Service) GetAuditLogger() *AuditLogger
GetAuditLogger returns the audit logger instance
func (*Service) GetJWTManager ¶
func (s *Service) GetJWTManager() *JWTManager
GetJWTManager returns the JWT manager instance
func (*Service) GetUserByEmail ¶
GetUserByEmail retrieves user by email
func (*Service) GetUserByID ¶
GetUserByID retrieves user by ID
func (*Service) ListAPIKeys ¶
ListAPIKeys lists all API keys for a user
func (*Service) ListAllAPIKeys ¶
ListAllAPIKeys lists all API keys for an organization (admin only)
func (*Service) Login ¶
func (s *Service) Login(email, password string) (*types.LoginResponse, error)
Login authenticates a user with email and password
func (*Service) LoginWithContext ¶
func (s *Service) LoginWithContext(email, password string, ctx *LoginContext) (*types.LoginResponse, error)
LoginWithContext authenticates a user with email and password including security context
func (*Service) LogoutWithContext ¶
func (s *Service) LogoutWithContext(accessToken string, ctx *LoginContext, voluntary bool) error
LogoutWithContext invalidates user tokens with security context
func (*Service) RefreshToken ¶
func (s *Service) RefreshToken(refreshToken string) (*types.LoginResponse, error)
RefreshToken generates new access token from refresh token
func (*Service) RefreshTokenWithContext ¶
func (s *Service) RefreshTokenWithContext(refreshToken string, ctx *LoginContext) (*types.LoginResponse, error)
RefreshTokenWithContext generates new access token with security context and optional rotation
func (*Service) RefreshTokenWithRotation ¶
func (s *Service) RefreshTokenWithRotation(refreshToken string, ctx *LoginContext) (*RefreshTokenResponse, error)
RefreshTokenWithRotation generates new access and refresh tokens, invalidating the old refresh token
func (*Service) RevokeAPIKey ¶
RevokeAPIKey revokes an API key
func (*Service) UpdateUser ¶
UpdateUser updates user information
type ServiceInterface ¶
type ServiceInterface interface { GetUserByID(userID string) (*types.User, error) ValidateAPIKey(apiKey string) (*types.APIKey, error) }
ServiceInterface defines the methods needed by the middleware
type TokenCache ¶
type TokenCache interface { // Set adds a token to the blacklist with expiration Set(ctx context.Context, token string, expiration time.Duration) error // IsBlacklisted checks if a token is blacklisted IsBlacklisted(ctx context.Context, token string) (bool, error) // Cleanup removes expired tokens (for memory cache) Cleanup(ctx context.Context) error // Close closes the cache connection Close() error }
TokenCache defines the interface for JWT token caching/blacklisting
func NewTokenCache ¶
func NewTokenCache(config CacheConfig) (TokenCache, error)
NewTokenCache creates a new token cache based on configuration
type TokenCleanupService ¶
type TokenCleanupService struct {
// contains filtered or unexported fields
}
TokenCleanupService handles background cleanup of expired tokens and audit logs
func NewTokenCleanupService ¶
func NewTokenCleanupService(db *sql.DB, jwtManager *JWTManager, auditLogger *AuditLogger, config *CleanupConfig) *TokenCleanupService
NewTokenCleanupService creates a new token cleanup service
func (*TokenCleanupService) ForceCleanup ¶
func (c *TokenCleanupService) ForceCleanup(ctx context.Context) error
ForceCleanup performs an immediate cleanup operation
func (*TokenCleanupService) GetCleanupStats ¶
func (c *TokenCleanupService) GetCleanupStats(ctx context.Context) (*CleanupStats, error)
GetCleanupStats returns statistics about cleanup operations
func (*TokenCleanupService) Start ¶
func (c *TokenCleanupService) Start(ctx context.Context) error
Start begins the background cleanup process
func (*TokenCleanupService) Stop ¶
func (c *TokenCleanupService) Stop()
Stop stops the background cleanup process