service

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const MetadataTenantKey = "x-tenant-id"

MetadataTenantKey is the gRPC metadata key for tenant ID

Variables

This section is empty.

Functions

func ActorIDFromContext

func ActorIDFromContext(ctx context.Context) uuid.UUID

ActorIDFromContext extracts actor ID from context (for admin operations)

func ContextWithIPAddress

func ContextWithIPAddress(ctx context.Context, ip string) context.Context

ContextWithIPAddress adds the IP address to the context

func ContextWithTenant

func ContextWithTenant(ctx context.Context, tenantID uuid.UUID) context.Context

ContextWithTenant adds the tenant ID to the context

func ContextWithUserAgent

func ContextWithUserAgent(ctx context.Context, ua string) context.Context

ContextWithUserAgent adds the user agent to the context

func GenerateEmailVerificationToken

func GenerateEmailVerificationToken(tenantID uuid.UUID, email string, userID uuid.UUID, otpRepo repository.OTPRepository) (*domain.OTP, error)

GenerateEmailVerificationToken generates an email verification token

func GeneratePasswordResetToken

func GeneratePasswordResetToken(tenantID uuid.UUID, email string, userID uuid.UUID, otpRepo repository.OTPRepository) (*domain.OTP, error)

GeneratePasswordResetToken generates a password reset token

func IPAddressFromContext

func IPAddressFromContext(ctx context.Context) string

IPAddressFromContext extracts the IP address from context

func MustTenantFromContext deprecated

func MustTenantFromContext(ctx context.Context) uuid.UUID

MustTenantFromContext extracts the tenant ID from context. Returns uuid.Nil if tenant ID is not found instead of panicking.

Deprecated: Use TenantFromContext instead which returns an error for proper error handling. This function is kept for backward compatibility but should be avoided in new code.

func StreamAuthInterceptor

func StreamAuthInterceptor() grpc.StreamServerInterceptor

StreamAuthInterceptor returns a gRPC stream interceptor for authentication

func TenantFromContext

func TenantFromContext(ctx context.Context) (uuid.UUID, error)

TenantFromContext extracts the tenant ID from context

func UnaryAuthInterceptor

func UnaryAuthInterceptor() grpc.UnaryServerInterceptor

UnaryAuthInterceptor returns a gRPC unary interceptor for authentication

func UserAgentFromContext

func UserAgentFromContext(ctx context.Context) string

UserAgentFromContext extracts the user agent from context

Types

type ActorContextKey

type ActorContextKey struct{}

ActorContextKey is the context key for actor ID

type AppleIDTokenClaims

type AppleIDTokenClaims struct {
	Issuer         string `json:"iss"`
	Subject        string `json:"sub"`              // User's unique identifier
	Audience       string `json:"aud"`              // Your client_id
	ExpiresAt      int64  `json:"exp"`              // Expiration time
	IssuedAt       int64  `json:"iat"`              // Issued at time
	Email          string `json:"email"`            // User's email (may be private relay)
	EmailVerified  string `json:"email_verified"`   // "true" or "false" as string
	IsPrivateEmail string `json:"is_private_email"` // Whether email is a private relay
	Nonce          string `json:"nonce"`            // Nonce for replay prevention
	AuthTime       int64  `json:"auth_time"`        // Time of authentication
}

AppleIDTokenClaims represents the claims in an Apple ID token

type AuditService

type AuditService interface {
	// Log creates a new audit log entry
	Log(ctx context.Context, log *domain.AuditLog) error

	// LogBatch creates multiple audit log entries
	LogBatch(ctx context.Context, logs []*domain.AuditLog) error

	// LogAction is a convenience method to log an action
	LogAction(ctx context.Context, tenantID uuid.UUID, action domain.AuditAction, resourceType domain.AuditResourceType, resourceID string, status domain.AuditStatus, details map[string]interface{}) error

	// LogUserAction logs an action performed by/on a user
	LogUserAction(ctx context.Context, tenantID, userID uuid.UUID, actorID *uuid.UUID, action domain.AuditAction, status domain.AuditStatus, details map[string]interface{}) error

	// LogSessionAction logs a session-related action
	LogSessionAction(ctx context.Context, tenantID, sessionID uuid.UUID, userID uuid.UUID, action domain.AuditAction, status domain.AuditStatus, details map[string]interface{}) error

	// Query retrieves audit logs with filtering
	Query(ctx context.Context, filter repository.AuditLogFilter) ([]domain.AuditLog, int64, error)
}

AuditService handles audit logging for compliance

func NewAuditService

func NewAuditService(auditRepo repository.AuditLogRepository) AuditService

NewAuditService creates a new audit service

type AuthService

type AuthService struct {
	authv1.UnimplementedAuthServiceServer
	// contains filtered or unexported fields
}

AuthService implements the gRPC AuthService interface

func NewAuthService

func NewAuthService(
	userRepo repository.UserRepository,
	sessionRepo repository.SessionRepository,
	otpRepo repository.OTPRepository,
	passwordService PasswordService,
	totpService TOTPService,
	passwordlessService PasswordlessService,
	oauthService OAuthService,
	jwtService JWTService,
	emailService EmailService,
	auditService AuditService,
	loginProtectionService LoginProtectionService,
	passwordHistoryService PasswordHistoryService,
	sessionConfig SessionConfig,
	logger Logger,
) *AuthService

NewAuthService creates a new AuthService

func (*AuthService) ChangePassword

ChangePassword changes a user's password

func (*AuthService) Disable2FA

Disable2FA disables 2FA for a user

func (*AuthService) Enable2FA

Enable2FA enables 2FA for a user

func (*AuthService) ForgotPassword

ForgotPassword initiates password reset

func (*AuthService) Generate2FABackupCodes

Generate2FABackupCodes generates new backup codes

func (*AuthService) GetAccountLockoutStatus

GetAccountLockoutStatus gets the lockout status for a user account

func (*AuthService) GetActiveSessions

GetActiveSessions retrieves all active sessions for a user

func (*AuthService) GetAuditLogs

GetAuditLogs retrieves audit logs with filtering (HIPAA/SOC 2/GDPR compliance)

func (*AuthService) GetLoginHistory

GetLoginHistory gets the login history for a user

func (*AuthService) GetOAuthURL

GetOAuthURL generates an OAuth authorization URL

func (*AuthService) GetUserProfile

GetUserProfile retrieves a user's profile

func (*AuthService) LinkOAuthAccount

LinkOAuthAccount links an OAuth account to an existing user

func (*AuthService) Login

Login authenticates a user

func (*AuthService) Logout

Logout logs out a user

func (*AuthService) OAuthCallback

OAuthCallback handles OAuth callback

func (*AuthService) RefreshToken

RefreshToken refreshes an access token

func (*AuthService) Register

Register registers a new user

func (*AuthService) ResendVerificationEmail

ResendVerificationEmail resends the verification email

func (*AuthService) ResetPassword

ResetPassword resets a user's password

func (*AuthService) RevokeAllSessions

RevokeAllSessions revokes all sessions for a user

func (*AuthService) RevokeSession

RevokeSession revokes a specific session

func (*AuthService) RevokeToken

RevokeToken revokes a token

func (*AuthService) SendPasswordlessEmail

SendPasswordlessEmail sends a passwordless login email

func (*AuthService) UnlinkOAuthAccount

UnlinkOAuthAccount unlinks an OAuth account from a user

func (*AuthService) UnlockAccount

UnlockAccount manually unlocks a user account (admin action)

func (*AuthService) UpdateUserProfile

UpdateUserProfile updates a user's profile

func (*AuthService) ValidateToken

ValidateToken validates an access token

func (*AuthService) Verify2FA

Verify2FA verifies a 2FA code

func (*AuthService) VerifyEmail

VerifyEmail verifies a user's email

func (*AuthService) VerifyPasswordlessToken

VerifyPasswordlessToken verifies a passwordless login token

type CacheService

type CacheService interface {
	Get(key string) (interface{}, bool)
	Set(key string, value interface{})
	SetWithTTL(key string, value interface{}, ttl time.Duration)
	Delete(key string)
	Clear()
	Close() error
}

CacheService defines the interface for caching operations

func NewCacheService

func NewCacheService(cfg *config.CacheConfig) (CacheService, error)

NewCacheService creates a cache service based on configuration

func NewMemoryCache

func NewMemoryCache(ttlSeconds, maxSize, cleanupMinutes int) CacheService

NewMemoryCache creates a new in-memory cache

func NewNoOpCache

func NewNoOpCache() CacheService

NewNoOpCache creates a cache that does nothing (for stateless deployments)

func NewRedisCache

func NewRedisCache(cfg *config.RedisCacheConfig) (CacheService, error)

NewRedisCache creates a new Redis/Valkey-backed cache service This ensures cache consistency across multiple service instances

type Claims

type Claims struct {
	UserID string            `json:"user_id"`
	Email  string            `json:"email"`
	Type   TokenType         `json:"type"`
	Extra  map[string]string `json:"extra,omitempty"`
	jwt.RegisteredClaims
}

Claims represents JWT claims

type DefaultLogger

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

DefaultLogger provides a simple default implementation using the standard library

func NewDefaultLogger

func NewDefaultLogger(level LogLevel) *DefaultLogger

NewDefaultLogger creates a new default logger

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(msg string, keysAndValues ...interface{})

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string, keysAndValues ...interface{})

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string, keysAndValues ...interface{})

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(msg string, keysAndValues ...interface{})

type EmailService

type EmailService interface {
	SendVerificationEmail(to, token string) error
	SendPasswordResetEmail(to, token string) error
	SendPasswordlessEmail(to, token string) error
	Send2FACode(to, code string) error
	SendWelcomeEmail(to, name string) error
}

EmailService handles sending emails

func NewEmailService

func NewEmailService(cfg *config.EmailConfig, appURL string) EmailService

NewEmailService creates a new email service

type EmailTemplate

type EmailTemplate string

EmailTemplate represents an email template type

const (
	TemplateVerification  EmailTemplate = "verification.txt"
	TemplatePasswordReset EmailTemplate = "password_reset.txt"
	TemplatePasswordless  EmailTemplate = "passwordless.txt"
	Template2FACode       EmailTemplate = "2fa_code.txt"
	TemplateWelcome       EmailTemplate = "welcome.txt"
)

type EmailTemplateData

type EmailTemplateData struct {
	AppName         string
	VerificationURL string
	ResetURL        string
	LoginURL        string
	Code            string
	Name            string
}

EmailTemplateData holds the data for email templates

type IPAddressKey

type IPAddressKey struct{}

IPAddressKey is the key used to store IP address in context

type JWTService

type JWTService interface {
	GenerateAccessToken(userID uuid.UUID, email string, extra map[string]string) (string, error)
	GenerateRefreshToken(userID uuid.UUID, email string) (string, error)
	ValidateToken(token string, tokenType TokenType) (*Claims, error)
	ParseToken(token string) (*Claims, error)
}

JWTService handles JWT token operations

func NewJWTService

func NewJWTService(cfg *config.JWTConfig) JWTService

NewJWTService creates a new JWT service

type LogLevel

type LogLevel int

LogLevel represents the logging level

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type Logger

type Logger interface {
	// Error logs an error message with optional context
	Error(msg string, keysAndValues ...interface{})
	// Warn logs a warning message with optional context
	Warn(msg string, keysAndValues ...interface{})
	// Info logs an info message with optional context
	Info(msg string, keysAndValues ...interface{})
	// Debug logs a debug message with optional context
	Debug(msg string, keysAndValues ...interface{})
}

Logger defines a simple logging interface for the auth service

type LoginProtectionConfig

type LoginProtectionConfig struct {
	// Maximum failed login attempts before lockout
	MaxFailedAttempts int
	// Time window to count failed attempts
	FailedAttemptsWindow time.Duration
	// Lockout duration after max failed attempts
	LockoutDuration time.Duration
	// Progressive lockout multiplier for repeat offenders
	LockoutMultiplier float64
	// Maximum lockout duration
	MaxLockoutDuration time.Duration
	// IP-based rate limiting threshold
	IPRateLimitThreshold int
	// IP rate limit window
	IPRateLimitWindow time.Duration
}

LoginProtectionConfig holds configuration for login protection

func DefaultLoginProtectionConfig

func DefaultLoginProtectionConfig() LoginProtectionConfig

DefaultLoginProtectionConfig returns sensible default configuration

type LoginProtectionService

type LoginProtectionService interface {
	// CheckLoginAllowed checks if login is allowed for the given email/IP
	CheckLoginAllowed(ctx context.Context, tenantID uuid.UUID, email, ipAddress string) error

	// RecordLoginAttempt records a login attempt (success or failure)
	RecordLoginAttempt(ctx context.Context, tenantID uuid.UUID, email, ipAddress string, userID *uuid.UUID, success bool, failureReason string) error

	// GetActiveLockout gets the active lockout for a user if any
	GetActiveLockout(ctx context.Context, tenantID, userID uuid.UUID) (*domain.AccountLockout, error)

	// UnlockAccount manually unlocks an account (admin action)
	UnlockAccount(ctx context.Context, tenantID, userID uuid.UUID, unlockedBy *uuid.UUID) error

	// CleanupExpired removes expired records
	CleanupExpired(ctx context.Context) error
}

LoginProtectionService handles brute force protection and account lockout

func NewLoginProtectionService

func NewLoginProtectionService(
	loginAttemptRepo repository.LoginAttemptRepository,
	lockoutRepo repository.AccountLockoutRepository,
	userRepo repository.UserRepository,
	config LoginProtectionConfig,
) LoginProtectionService

NewLoginProtectionService creates a new login protection service

type NopLogger

type NopLogger struct{}

NopLogger is a no-op logger that discards all log messages

func (*NopLogger) Debug

func (l *NopLogger) Debug(msg string, keysAndValues ...interface{})

func (*NopLogger) Error

func (l *NopLogger) Error(msg string, keysAndValues ...interface{})

func (*NopLogger) Info

func (l *NopLogger) Info(msg string, keysAndValues ...interface{})

func (*NopLogger) Warn

func (l *NopLogger) Warn(msg string, keysAndValues ...interface{})

type OAuthProvider

type OAuthProvider string

OAuthProvider represents an OAuth provider

const (
	ProviderGoogle    OAuthProvider = "google"
	ProviderGitHub    OAuthProvider = "github"
	ProviderFacebook  OAuthProvider = "facebook"
	ProviderApple     OAuthProvider = "apple"
	ProviderMicrosoft OAuthProvider = "microsoft"
	ProviderDiscord   OAuthProvider = "discord"
)

type OAuthService

type OAuthService interface {
	GetAuthURL(provider OAuthProvider, state string) (string, error)
	ExchangeCode(provider OAuthProvider, code string) (*oauth2.Token, error)
	GetUserInfo(provider OAuthProvider, token *oauth2.Token) (*OAuthUserInfo, error)
	GenerateState() (string, error)
}

OAuthService handles OAuth operations

func NewOAuthService

func NewOAuthService(cfg *config.OAuthConfig) OAuthService

NewOAuthService creates a new OAuth service

type OAuthUserInfo

type OAuthUserInfo struct {
	ProviderUserID string
	Email          string
	FirstName      string
	LastName       string
	Picture        string
}

OAuthUserInfo represents user information from OAuth provider

type PasswordHistoryConfig

type PasswordHistoryConfig struct {
	// Number of previous passwords to check against
	HistoryCount int
	// Minimum days before password can be reused (0 = never)
	MinPasswordAgeDays int
}

PasswordHistoryConfig holds configuration for password history

func DefaultPasswordHistoryConfig

func DefaultPasswordHistoryConfig() PasswordHistoryConfig

DefaultPasswordHistoryConfig returns sensible default configuration

type PasswordHistoryService

type PasswordHistoryService interface {
	// CheckPasswordReuse checks if the password was used recently
	CheckPasswordReuse(ctx context.Context, tenantID, userID uuid.UUID, newPassword string) error

	// RecordPassword records a password in history
	RecordPassword(ctx context.Context, tenantID, userID uuid.UUID, passwordHash string) error

	// CleanupOldHistory removes old password history entries
	CleanupOldHistory(ctx context.Context, tenantID, userID uuid.UUID) error
}

PasswordHistoryService handles password history for compliance

func NewPasswordHistoryService

func NewPasswordHistoryService(
	historyRepo repository.PasswordHistoryRepository,
	config PasswordHistoryConfig,
) PasswordHistoryService

NewPasswordHistoryService creates a new password history service

type PasswordService

type PasswordService interface {
	HashPassword(password string) (string, error)
	VerifyPassword(hashedPassword, password string) error
	ValidatePasswordStrength(password string) error
}

PasswordService handles password hashing and verification

func NewPasswordService

func NewPasswordService() PasswordService

NewPasswordService creates a new password service

type PasswordlessService

type PasswordlessService interface {
	GenerateToken(tenantID uuid.UUID, email string) (*domain.OTP, error)
	VerifyToken(tenantID uuid.UUID, token string) (*domain.OTP, error)
}

PasswordlessService handles passwordless authentication operations

func NewPasswordlessService

func NewPasswordlessService(otpRepo repository.OTPRepository) PasswordlessService

NewPasswordlessService creates a new passwordless service

type SessionConfig

type SessionConfig struct {
	// Session expiry duration
	SessionExpiry time.Duration
	// Idle timeout duration (HIPAA compliance)
	IdleTimeout time.Duration
	// Maximum concurrent sessions per user (0 = unlimited)
	MaxConcurrentSessions int
}

SessionConfig holds session configuration for compliance

func DefaultSessionConfig

func DefaultSessionConfig() SessionConfig

DefaultSessionConfig returns sensible default configuration

type TOTPService

type TOTPService interface {
	GenerateSecret(email string) (secret string, qrCodeURL string, err error)
	ValidateCode(secret, code string) bool
	GenerateBackupCodes(count int) ([]string, error)
}

TOTPService handles TOTP (Time-based One-Time Password) operations

func NewTOTPService

func NewTOTPService() TOTPService

NewTOTPService creates a new TOTP service

type TenantContextKey

type TenantContextKey struct{}

TenantContextKey is the key used to store tenant ID in context

type TokenType

type TokenType string

TokenType represents the type of JWT token

const (
	AccessToken  TokenType = "access"
	RefreshToken TokenType = "refresh"
)

type UserAgentKey

type UserAgentKey struct{}

UserAgentKey is the key used to store user agent in context

Jump to

Keyboard shortcuts

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