consent

package
v0.0.2 Latest Latest
Warning

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

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

README

Enterprise-grade consent and privacy management plugin for AuthSome with full GDPR/CCPA compliance, cookie consent management, data portability (GDPR Article 20), and right to be forgotten (GDPR Article 17) implementation.

Features

  • ✅ Granular consent tracking per user and organization
  • ✅ Consent versioning and policy management
  • ✅ Consent expiry and renewal workflows
  • ✅ Immutable audit trail for all consent changes
  • ✅ Multi-organization support (SaaS mode)
  • ✅ Standalone mode support
  • ✅ Cookie consent banner integration
  • ✅ Granular cookie categories (essential, functional, analytics, marketing, personalization, third-party)
  • ✅ Anonymous user consent tracking
  • ✅ Consent validity period management
  • ✅ Cookie consent versioning
GDPR Compliance
Article 20 - Right to Data Portability
  • ✅ User-initiated data export requests
  • ✅ Multiple export formats (JSON, CSV, XML, PDF)
  • ✅ Configurable data sections (profile, sessions, consents, audit logs)
  • ✅ Rate limiting for export requests
  • ✅ Secure download URLs with expiry
  • ✅ Automatic cleanup of expired exports
Article 17 - Right to be Forgotten
  • ✅ User-initiated deletion requests
  • ✅ Admin approval workflow for deletions
  • ✅ Grace period before deletion
  • ✅ Data archiving before deletion
  • ✅ Partial or full data deletion
  • ✅ Legal retention exemptions
  • ✅ Audit trail preservation
Data Processing Agreements (DPA)
  • ✅ DPA/BAA creation and management
  • ✅ Digital signature generation
  • ✅ Multiple agreement types (DPA, BAA, GDPR, CCPA)
  • ✅ Version tracking and expiry management
Privacy Settings
  • ✅ Per-organization privacy configuration
  • ✅ GDPR mode and CCPA mode
  • ✅ Configurable data retention periods
  • ✅ Consent requirement toggles
  • ✅ Data Protection Officer (DPO) contact management

Installation

1. Install Plugin
import (
	"github.com/xraph/authsome"
	"github.com/xraph/authsome/plugins/enterprise/consent"
)

func main() {
	auth := authsome.New(/* ... */)
	
	// Register consent plugin
	consentPlugin := consent.NewPlugin()
	auth.RegisterPlugin(consentPlugin)
	
	// Initialize
	if err := auth.Init(); err != nil {
		log.Fatal(err)
	}
}
2. Configuration

Add to your config.yaml:

auth:
  consent:
    enabled: true
    gdprEnabled: true
    ccpaEnabled: false
    
    cookieConsent:
      enabled: true
      defaultStyle: "banner"  # banner, modal, popup
      requireExplicit: true   # No implied consent
      validityPeriod: "8760h" # 1 year
      allowAnonymous: true
      bannerVersion: "1.0"
      categories:
        - essential
        - functional
        - analytics
        - marketing
        - personalization
        - third_party
    
    dataExport:
      enabled: true
      allowedFormats:
        - json
        - csv
      defaultFormat: json
      maxRequests: 5          # Max exports per period
      requestPeriod: "720h"   # 30 days
      expiryHours: 72         # Download URL valid for 3 days
      storagePath: "/var/lib/authsome/consent/exports"
      includeSections:
        - profile
        - sessions
        - consents
        - audit
      autoCleanup: true
      cleanupInterval: "24h"
      maxExportSize: 104857600  # 100MB
    
    dataDeletion:
      enabled: true
      requireAdminApproval: true
      gracePeriodDays: 30      # GDPR allows up to 30 days
      archiveBeforeDeletion: true
      archivePath: "/var/lib/authsome/consent/archives"
      retentionExemptions:
        - legal_hold
        - active_investigation
        - contractual_obligation
      notifyBeforeDeletion: true
      allowPartialDeletion: true
      preserveLegalData: true
      autoProcessAfterGrace: false
    
    audit:
      enabled: true
      retentionDays: 2555      # 7 years (common legal requirement)
      immutable: true
      logAllChanges: true
      logIpAddress: true
      logUserAgent: true
      signLogs: true
      exportFormat: json
      archiveOldLogs: true
      archiveInterval: "2160h"  # 90 days
    
    expiry:
      enabled: true
      defaultValidityDays: 365
      renewalReminderDays: 30
      autoExpireCheck: true
      expireCheckInterval: "24h"
      allowRenewal: true
      requireReConsent: false
    
    dashboard:
      enabled: true
      path: "/auth/consent"
      showConsentHistory: true
      showCookiePreferences: true
      showDataExport: true
      showDataDeletion: true
      showAuditLog: true
      showPolicies: true
    
    notifications:
      enabled: true
      notifyOnGrant: false
      notifyOnRevoke: true
      notifyOnExpiry: true
      notifyExportReady: true
      notifyDeletionApproved: true
      notifyDeletionComplete: true
      notifyDpoEmail: "dpo@example.com"
      channels:
        - email
3. Database Migration

The plugin automatically creates the following tables:

  • consent_records - User consent records
  • consent_policies - Consent policies and terms
  • consent_audit_logs - Immutable audit trail
  • cookie_consents - Cookie consent preferences
  • data_export_requests - Data export requests
  • data_deletion_requests - Deletion requests
  • data_processing_agreements - DPAs and BAAs
  • privacy_settings - Per-organization privacy settings

API Reference

POST /auth/consent/records
{
  "userId": "user_123",
  "consentType": "marketing",
  "purpose": "email_campaigns",
  "granted": true,
  "version": "1.0",
  "expiresIn": 365,
  "metadata": {
    "source": "signup_form"
  }
}
List User Consents
GET /auth/consent/records
GET /auth/consent/summary

Response:

{
  "userId": "user_123",
  "organizationId": "org_456",
  "totalConsents": 5,
  "grantedConsents": 4,
  "revokedConsents": 1,
  "expiredConsents": 0,
  "pendingRenewals": 1,
  "consentsByType": {
    "marketing": {
      "type": "marketing",
      "granted": true,
      "version": "1.0",
      "grantedAt": "2024-01-01T00:00:00Z",
      "expiresAt": "2025-01-01T00:00:00Z",
      "needsRenewal": false
    }
  },
  "hasPendingDeletion": false,
  "hasPendingExport": false
}
POST /auth/consent/revoke
{
  "consentType": "marketing",
  "purpose": "email_campaigns"
}
Create Policy
POST /auth/consent/policies
{
  "consentType": "terms",
  "name": "Terms of Service",
  "description": "Standard terms of service",
  "version": "2.0",
  "content": "Full policy text here...",
  "required": true,
  "renewable": true,
  "validityPeriod": 365,
  "metadata": {}
}
Get Latest Policy
GET /auth/consent/policies/latest/:type
POST /auth/consent/cookies
{
  "essential": true,
  "functional": true,
  "analytics": false,
  "marketing": false,
  "personalization": true,
  "thirdParty": false,
  "sessionId": "anonymous_session_id",
  "bannerVersion": "1.0"
}
GET /auth/consent/cookies
Data Export (GDPR Article 20)
Request Data Export
POST /auth/consent/export
{
  "format": "json",
  "includeSections": ["profile", "consents", "audit"]
}

Response:

{
  "id": "export_123",
  "userId": "user_123",
  "organizationId": "org_456",
  "status": "pending",
  "format": "json",
  "includeSections": ["profile", "consents", "audit"],
  "createdAt": "2024-01-01T00:00:00Z"
}
Get Export Status
GET /auth/consent/export/:id

Response:

{
  "id": "export_123",
  "status": "completed",
  "exportUrl": "/auth/consent/export/export_123/download",
  "exportSize": 1024000,
  "expiresAt": "2024-01-04T00:00:00Z",
  "completedAt": "2024-01-01T00:05:00Z"
}
Download Export
GET /auth/consent/export/:id/download

Returns the export file.

Data Deletion (GDPR Article 17)
Request Data Deletion
POST /auth/consent/deletion
{
  "reason": "I want my data deleted per GDPR Article 17",
  "deleteSections": ["all"]
}

Response:

{
  "id": "deletion_123",
  "userId": "user_123",
  "organizationId": "org_456",
  "status": "pending",
  "requestReason": "I want my data deleted per GDPR Article 17",
  "deleteSections": ["all"],
  "createdAt": "2024-01-01T00:00:00Z"
}
Approve Deletion (Admin)
POST /auth/consent/deletion/:id/approve
Process Deletion (Admin)
POST /auth/consent/deletion/:id/process
Privacy Settings
Get Privacy Settings
GET /auth/consent/settings
Update Privacy Settings (Admin)
PUT /auth/consent/settings
{
  "consentRequired": true,
  "cookieConsentEnabled": true,
  "gdprMode": true,
  "ccpaMode": false,
  "dataRetentionDays": 2555,
  "requireExplicitConsent": true,
  "allowDataPortability": true,
  "requireAdminApprovalForDeletion": true,
  "deletionGracePeriodDays": 30,
  "contactEmail": "privacy@example.com",
  "dpoEmail": "dpo@example.com"
}
Data Processing Agreements
Create DPA
POST /auth/consent/dpa
{
  "agreementType": "dpa",
  "version": "1.0",
  "content": "Full DPA text...",
  "signedByName": "John Doe",
  "signedByTitle": "CTO",
  "signedByEmail": "john@example.com",
  "effectiveDate": "2024-01-01T00:00:00Z",
  "expiryDate": "2025-01-01T00:00:00Z"
}

Usage Examples

// Get plugin instance
consentPlugin := auth.GetPlugin("consent").(*consent.Plugin)

// Check if user has granted consent
granted, err := consentPlugin.GetUserConsentStatus(
    ctx,
    "user_123",
    "org_456",
    "marketing",
    "email_campaigns",
)

if !granted {
    // User hasn't granted consent
    return errors.New("consent required")
}
// Protect routes with consent requirement
router.POST("/marketing/subscribe", 
    consentPlugin.RequireConsent("marketing", "email_campaigns")(
        handler.Subscribe,
    ),
)
policy, err := consentPlugin.Service().CreatePolicy(ctx, orgID, adminUserID, &consent.CreatePolicyRequest{
    ConsentType: "privacy",
    Name:        "Privacy Policy",
    Version:     "2.0",
    Content:     policyContent,
    Required:    true,
    Renewable:   false,
})
Request Data Export
export, err := consentPlugin.Service().RequestDataExport(ctx, userID, orgID, &consent.DataExportRequestInput{
    Format:          "json",
    IncludeSections: []string{"profile", "consents", "audit"},
})
Request Data Deletion
deletion, err := consentPlugin.Service().RequestDataDeletion(ctx, userID, orgID, &consent.DataDeletionRequestInput{
    Reason:         "GDPR Article 17 request",
    DeleteSections: []string{"all"},
})

Multi-Tenancy Support

The consent plugin fully supports AuthSome's multi-tenancy:

Standalone Mode
  • Single default organization
  • Organization-agnostic consent management
  • Shared privacy settings
SaaS Mode
  • Per-organization privacy settings
  • Organization-scoped consents
  • Organization-specific consent policies
  • Isolated data export and deletion requests

GDPR Compliance Checklist

Article 6 (Lawfulness of processing)

  • Consent records with explicit grant/revoke
  • Purpose specification
  • Audit trail

Article 7 (Conditions for consent)

  • Explicit consent collection
  • Easy consent withdrawal
  • Versioned consent policies

Article 13/14 (Information to be provided)

  • Privacy policy management
  • Terms of service versioning
  • Contact information (DPO)

Article 17 (Right to erasure)

  • User-initiated deletion requests
  • Admin approval workflow
  • Grace period
  • Data archiving
  • Retention exemptions

Article 20 (Right to data portability)

  • User data export
  • Multiple formats (JSON, CSV, XML)
  • Secure download mechanism

Article 30 (Records of processing activities)

  • Immutable audit logs
  • 7-year retention
  • Cryptographic signing

CCPA Compliance

Right to Know

  • Data export functionality

Right to Delete

  • Deletion request workflow

Right to Opt-Out

  • Consent revocation
  • Cookie consent management

Do Not Sell

  • Third-party consent tracking
  • Marketing consent management

Security Considerations

Data Protection
  • Immutable audit logs
  • Cryptographic log signing
  • Digital signatures for DPAs
  • Secure file storage
Access Control
  • User-scoped consent access
  • Admin-only operations (approval, processing)
  • Organization isolation in SaaS mode
Privacy by Design
  • Default privacy settings
  • Explicit consent required
  • No implied consent in GDPR mode
  • Automatic expiry checking

Performance

Optimizations
  • Indexed database queries
  • Efficient consent lookups
  • Background processing for exports
  • Automatic cleanup of expired data
Scalability
  • Async data export processing
  • Batch consent expiry checks
  • Configurable cleanup intervals

Troubleshooting

Export Fails
  • Check storage path permissions
  • Verify max export size limits
  • Check rate limits
Deletion Not Processing
  • Verify grace period has passed
  • Check retention exemptions
  • Ensure admin approval if required
  • Check organization ID
  • Verify consent type and purpose match
  • Check if consent has expired

Contributing

See CONTRIBUTING.md for guidelines.

License

Part of the AuthSome project. See LICENSE.

Support

For issues and questions:

Documentation

Index

Constants

View Source
const (
	PluginID      = "consent"
	PluginName    = "Consent & Privacy Management"
	PluginVersion = "1.0.0"
)

Variables

View Source
var (
	// Consent Record Errors
	ErrConsentNotFound      = errors.New("consent record not found")
	ErrConsentAlreadyExists = errors.New("consent record already exists")
	ErrConsentExpired       = errors.New("consent has expired")
	ErrConsentRevoked       = errors.New("consent has been revoked")
	ErrInvalidConsentType   = errors.New("invalid consent type")
	ErrConsentRequired      = errors.New("consent is required")

	// Policy Errors
	ErrPolicyNotFound       = errors.New("consent policy not found")
	ErrPolicyAlreadyExists  = errors.New("consent policy already exists")
	ErrPolicyInactive       = errors.New("consent policy is not active")
	ErrInvalidPolicyVersion = errors.New("invalid policy version")
	ErrPolicyRequired       = errors.New("policy acceptance is required")

	// DPA Errors
	ErrDPANotFound      = errors.New("data processing agreement not found")
	ErrDPAExpired       = errors.New("data processing agreement has expired")
	ErrDPANotActive     = errors.New("data processing agreement is not active")
	ErrInvalidSignature = errors.New("invalid digital signature")

	// Cookie Consent Errors
	ErrCookieConsentNotFound    = errors.New("cookie consent not found")
	ErrInvalidCookiePreferences = errors.New("invalid cookie preferences")

	// Data Export Errors
	ErrExportNotFound       = errors.New("data export request not found")
	ErrExportAlreadyPending = errors.New("data export request already pending")
	ErrExportFailed         = errors.New("data export failed")
	ErrExportExpired        = errors.New("data export has expired")
	ErrInvalidExportFormat  = errors.New("invalid export format")

	// Data Deletion Errors
	ErrDeletionNotFound       = errors.New("data deletion request not found")
	ErrDeletionAlreadyPending = errors.New("data deletion request already pending")
	ErrDeletionFailed         = errors.New("data deletion failed")
	ErrDeletionNotApproved    = errors.New("data deletion request not approved")
	ErrRetentionExempt        = errors.New("data is exempt from deletion due to legal retention")

	// Privacy Settings Errors
	ErrPrivacySettingsNotFound = errors.New("privacy settings not found")
	ErrInvalidRetentionPeriod  = errors.New("invalid data retention period")

	// General Errors
	ErrUnauthorized         = errors.New("unauthorized access")
	ErrInvalidRequest       = errors.New("invalid request")
	ErrOrganizationNotFound = errors.New("organization not found")
	ErrUserNotFound         = errors.New("user not found")
)

Functions

This section is empty.

Types

type AgreementType

type AgreementType string

AgreementType represents different types of data processing agreements

const (
	AgreementTypeDPA  AgreementType = "dpa"  // Data Processing Agreement
	AgreementTypeBAA  AgreementType = "baa"  // Business Associate Agreement (HIPAA)
	AgreementTypeCCPA AgreementType = "ccpa" // California Consumer Privacy Act
	AgreementTypeGDPR AgreementType = "gdpr" // General Data Protection Regulation
)

type BunRepository

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

BunRepository implements Repository using Bun ORM

func (*BunRepository) CreateAuditLog

func (r *BunRepository) CreateAuditLog(ctx context.Context, log *ConsentAuditLog) error

func (*BunRepository) CreateConsent

func (r *BunRepository) CreateConsent(ctx context.Context, consent *ConsentRecord) error

func (*BunRepository) CreateCookieConsent

func (r *BunRepository) CreateCookieConsent(ctx context.Context, consent *CookieConsent) error

func (*BunRepository) CreateDPA

func (r *BunRepository) CreateDPA(ctx context.Context, dpa *DataProcessingAgreement) error

func (*BunRepository) CreateDeletionRequest

func (r *BunRepository) CreateDeletionRequest(ctx context.Context, request *DataDeletionRequest) error

func (*BunRepository) CreateExportRequest

func (r *BunRepository) CreateExportRequest(ctx context.Context, request *DataExportRequest) error

func (*BunRepository) CreatePolicy

func (r *BunRepository) CreatePolicy(ctx context.Context, policy *ConsentPolicy) error

func (*BunRepository) CreatePrivacySettings

func (r *BunRepository) CreatePrivacySettings(ctx context.Context, settings *PrivacySettings) error

func (*BunRepository) DeleteConsent

func (r *BunRepository) DeleteConsent(ctx context.Context, id string) error

func (*BunRepository) DeleteExpiredExports

func (r *BunRepository) DeleteExpiredExports(ctx context.Context, beforeDate time.Time) (int, error)

func (*BunRepository) DeletePolicy

func (r *BunRepository) DeletePolicy(ctx context.Context, id string) error

func (*BunRepository) ExpireConsents

func (r *BunRepository) ExpireConsents(ctx context.Context, beforeDate time.Time) (int, error)

func (*BunRepository) GetActiveDPA

func (r *BunRepository) GetActiveDPA(ctx context.Context, orgID, agreementType string) (*DataProcessingAgreement, error)

func (*BunRepository) GetAuditLogsByConsent

func (r *BunRepository) GetAuditLogsByConsent(ctx context.Context, consentID string) ([]*ConsentAuditLog, error)

func (*BunRepository) GetConsent

func (r *BunRepository) GetConsent(ctx context.Context, id string) (*ConsentRecord, error)

func (*BunRepository) GetConsentByUserAndType

func (r *BunRepository) GetConsentByUserAndType(ctx context.Context, userID, orgID, consentType, purpose string) (*ConsentRecord, error)

func (*BunRepository) GetConsentStats

func (r *BunRepository) GetConsentStats(ctx context.Context, orgID string, startDate, endDate time.Time) (map[string]interface{}, error)

func (*BunRepository) GetCookieConsent

func (r *BunRepository) GetCookieConsent(ctx context.Context, userID, orgID string) (*CookieConsent, error)

func (*BunRepository) GetCookieConsentBySession

func (r *BunRepository) GetCookieConsentBySession(ctx context.Context, sessionID, orgID string) (*CookieConsent, error)

func (*BunRepository) GetDPA

func (*BunRepository) GetDeletionRequest

func (r *BunRepository) GetDeletionRequest(ctx context.Context, id string) (*DataDeletionRequest, error)

func (*BunRepository) GetExportRequest

func (r *BunRepository) GetExportRequest(ctx context.Context, id string) (*DataExportRequest, error)

func (*BunRepository) GetLatestPolicy

func (r *BunRepository) GetLatestPolicy(ctx context.Context, orgID, consentType string) (*ConsentPolicy, error)

func (*BunRepository) GetPendingDeletionRequest

func (r *BunRepository) GetPendingDeletionRequest(ctx context.Context, userID, orgID string) (*DataDeletionRequest, error)

func (*BunRepository) GetPolicy

func (r *BunRepository) GetPolicy(ctx context.Context, id string) (*ConsentPolicy, error)

func (*BunRepository) GetPolicyByTypeAndVersion

func (r *BunRepository) GetPolicyByTypeAndVersion(ctx context.Context, orgID, consentType, version string) (*ConsentPolicy, error)

func (*BunRepository) GetPrivacySettings

func (r *BunRepository) GetPrivacySettings(ctx context.Context, orgID string) (*PrivacySettings, error)

func (*BunRepository) ListAuditLogs

func (r *BunRepository) ListAuditLogs(ctx context.Context, userID, orgID string, limit int) ([]*ConsentAuditLog, error)

func (*BunRepository) ListConsentsByUser

func (r *BunRepository) ListConsentsByUser(ctx context.Context, userID, orgID string) ([]*ConsentRecord, error)

func (*BunRepository) ListDPAs

func (r *BunRepository) ListDPAs(ctx context.Context, orgID string, status *string) ([]*DataProcessingAgreement, error)

func (*BunRepository) ListDeletionRequests

func (r *BunRepository) ListDeletionRequests(ctx context.Context, userID, orgID string, status *string) ([]*DataDeletionRequest, error)

func (*BunRepository) ListExportRequests

func (r *BunRepository) ListExportRequests(ctx context.Context, userID, orgID string, status *string) ([]*DataExportRequest, error)

func (*BunRepository) ListPolicies

func (r *BunRepository) ListPolicies(ctx context.Context, orgID string, active *bool) ([]*ConsentPolicy, error)

func (*BunRepository) UpdateConsent

func (r *BunRepository) UpdateConsent(ctx context.Context, consent *ConsentRecord) error

func (*BunRepository) UpdateCookieConsent

func (r *BunRepository) UpdateCookieConsent(ctx context.Context, consent *CookieConsent) error

func (*BunRepository) UpdateDPA

func (r *BunRepository) UpdateDPA(ctx context.Context, dpa *DataProcessingAgreement) error

func (*BunRepository) UpdateDeletionRequest

func (r *BunRepository) UpdateDeletionRequest(ctx context.Context, request *DataDeletionRequest) error

func (*BunRepository) UpdateExportRequest

func (r *BunRepository) UpdateExportRequest(ctx context.Context, request *DataExportRequest) error

func (*BunRepository) UpdatePolicy

func (r *BunRepository) UpdatePolicy(ctx context.Context, policy *ConsentPolicy) error

func (*BunRepository) UpdatePrivacySettings

func (r *BunRepository) UpdatePrivacySettings(ctx context.Context, settings *PrivacySettings) error

type Config

type Config struct {
	// Enable consent plugin
	Enabled bool `json:"enabled" yaml:"enabled"`

	// GDPR compliance mode
	GDPREnabled bool `json:"gdprEnabled" yaml:"gdprEnabled"`

	// CCPA compliance mode
	CCPAEnabled bool `json:"ccpaEnabled" yaml:"ccpaEnabled"`

	// Cookie consent configuration
	CookieConsent CookieConsentConfig `json:"cookieConsent" yaml:"cookieConsent"`

	// Data export configuration
	DataExport DataExportConfig `json:"dataExport" yaml:"dataExport"`

	// Data deletion configuration
	DataDeletion DataDeletionConfig `json:"dataDeletion" yaml:"dataDeletion"`

	// Consent audit configuration
	Audit ConsentAuditConfig `json:"audit" yaml:"audit"`

	// Consent expiry configuration
	Expiry ConsentExpiryConfig `json:"expiry" yaml:"expiry"`

	// Dashboard configuration
	Dashboard ConsentDashboardConfig `json:"dashboard" yaml:"dashboard"`

	// Notifications
	Notifications ConsentNotificationsConfig `json:"notifications" yaml:"notifications"`
}

Config holds the consent plugin configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default consent configuration

func (*Config) Validate

func (c *Config) Validate()

Validate ensures the configuration has sensible defaults

type ConsentAction

type ConsentAction string

ConsentAction represents actions in audit log

const (
	ActionGranted ConsentAction = "granted"
	ActionRevoked ConsentAction = "revoked"
	ActionUpdated ConsentAction = "updated"
	ActionExpired ConsentAction = "expired"
	ActionRenewed ConsentAction = "renewed"
)

type ConsentAuditConfig

type ConsentAuditConfig struct {
	Enabled         bool          `json:"enabled" yaml:"enabled"`
	RetentionDays   int           `json:"retentionDays" yaml:"retentionDays"` // How long to keep audit logs
	Immutable       bool          `json:"immutable" yaml:"immutable"`         // Prevent audit log modification
	LogAllChanges   bool          `json:"logAllChanges" yaml:"logAllChanges"` // Log all consent changes
	LogIPAddress    bool          `json:"logIpAddress" yaml:"logIpAddress"`
	LogUserAgent    bool          `json:"logUserAgent" yaml:"logUserAgent"`
	SignLogs        bool          `json:"signLogs" yaml:"signLogs"`         // Cryptographic signing
	ExportFormat    string        `json:"exportFormat" yaml:"exportFormat"` // json, csv
	ArchiveOldLogs  bool          `json:"archiveOldLogs" yaml:"archiveOldLogs"`
	ArchiveInterval time.Duration `json:"archiveInterval" yaml:"archiveInterval"`
}

ConsentAuditConfig configures consent audit trail

type ConsentAuditLog

type ConsentAuditLog struct {
	bun.BaseModel `bun:"table:consent_audit_logs,alias:cal"`

	ID             xid.ID    `json:"id" bun:"id,pk,type:varchar(20)"`
	UserID         string    `json:"userId" bun:"user_id,notnull,type:varchar(20)"`
	OrganizationID string    `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	ConsentID      string    `json:"consentId" bun:"consent_id,type:varchar(20)"` // Reference to consent record
	Action         string    `json:"action" bun:"action,notnull"`                 // granted, revoked, updated, expired
	ConsentType    string    `json:"consentType" bun:"consent_type,notnull"`
	Purpose        string    `json:"purpose" bun:"purpose"`
	PreviousValue  JSONBMap  `json:"previousValue" bun:"previous_value,type:jsonb"`
	NewValue       JSONBMap  `json:"newValue" bun:"new_value,type:jsonb"`
	IPAddress      string    `json:"ipAddress" bun:"ip_address"`
	UserAgent      string    `json:"userAgent" bun:"user_agent"`
	Reason         string    `json:"reason" bun:"reason"` // Reason for change
	CreatedAt      time.Time `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
}

ConsentAuditLog provides immutable audit trail for consent changes

type ConsentAuditLogsResponse

type ConsentAuditLogsResponse struct {
	AuditLogs []interface{} `json:"audit_logs"`
}

type ConsentCookieResponse

type ConsentCookieResponse struct {
	Preferences interface{} `json:"preferences"`
}

type ConsentDashboardConfig

type ConsentDashboardConfig struct {
	Enabled               bool   `json:"enabled" yaml:"enabled"`
	Path                  string `json:"path" yaml:"path"` // e.g., /auth/consent
	ShowConsentHistory    bool   `json:"showConsentHistory" yaml:"showConsentHistory"`
	ShowCookiePreferences bool   `json:"showCookiePreferences" yaml:"showCookiePreferences"`
	ShowDataExport        bool   `json:"showDataExport" yaml:"showDataExport"`
	ShowDataDeletion      bool   `json:"showDataDeletion" yaml:"showDataDeletion"`
	ShowAuditLog          bool   `json:"showAuditLog" yaml:"showAuditLog"`
	ShowPolicies          bool   `json:"showPolicies" yaml:"showPolicies"`
}

ConsentDashboardConfig configures the consent dashboard

type ConsentDeletionResponse

type ConsentDeletionResponse struct {
	ID     string `json:"id" example:"deletion_123"`
	Status string `json:"status" example:"pending"`
}

type ConsentExpiryConfig

type ConsentExpiryConfig struct {
	Enabled             bool          `json:"enabled" yaml:"enabled"`
	DefaultValidityDays int           `json:"defaultValidityDays" yaml:"defaultValidityDays"` // Default consent validity
	RenewalReminderDays int           `json:"renewalReminderDays" yaml:"renewalReminderDays"` // Days before expiry to remind
	AutoExpireCheck     bool          `json:"autoExpireCheck" yaml:"autoExpireCheck"`         // Automatically check and expire
	ExpireCheckInterval time.Duration `json:"expireCheckInterval" yaml:"expireCheckInterval"`
	AllowRenewal        bool          `json:"allowRenewal" yaml:"allowRenewal"`
	RequireReConsent    bool          `json:"requireReConsent" yaml:"requireReConsent"` // Require explicit re-consent
}

ConsentExpiryConfig configures consent expiry management

type ConsentExportFileResponse

type ConsentExportFileResponse struct {
	ContentType string `json:"content_type" example:"application/zip"`
	Data        []byte `json:"data"`
}

type ConsentExportResponse

type ConsentExportResponse struct {
	ID     string `json:"id" example:"export_123"`
	Status string `json:"status" example:"processing"`
}

type ConsentNotificationsConfig

type ConsentNotificationsConfig struct {
	Enabled                bool     `json:"enabled" yaml:"enabled"`
	NotifyOnGrant          bool     `json:"notifyOnGrant" yaml:"notifyOnGrant"`
	NotifyOnRevoke         bool     `json:"notifyOnRevoke" yaml:"notifyOnRevoke"`
	NotifyOnExpiry         bool     `json:"notifyOnExpiry" yaml:"notifyOnExpiry"`
	NotifyExportReady      bool     `json:"notifyExportReady" yaml:"notifyExportReady"`
	NotifyDeletionApproved bool     `json:"notifyDeletionApproved" yaml:"notifyDeletionApproved"`
	NotifyDeletionComplete bool     `json:"notifyDeletionComplete" yaml:"notifyDeletionComplete"`
	NotifyDPOEmail         string   `json:"notifyDpoEmail" yaml:"notifyDpoEmail"` // Data Protection Officer email
	Channels               []string `json:"channels" yaml:"channels"`             // email, sms, webhook
}

ConsentNotificationsConfig configures consent notifications

type ConsentPolicy

type ConsentPolicy struct {
	bun.BaseModel `bun:"table:consent_policies,alias:cp"`

	ID             xid.ID     `json:"id" bun:"id,pk,type:varchar(20)"`
	OrganizationID string     `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	ConsentType    string     `json:"consentType" bun:"consent_type,notnull"`
	Name           string     `json:"name" bun:"name,notnull"`
	Description    string     `json:"description" bun:"description"`
	Version        string     `json:"version" bun:"version,notnull"`
	Content        string     `json:"content" bun:"content,type:text"`                // Full policy text
	Required       bool       `json:"required" bun:"required"`                        // Block access if not granted
	Renewable      bool       `json:"renewable" bun:"renewable"`                      // Allow re-consent
	ValidityPeriod *int       `json:"validityPeriod,omitempty" bun:"validity_period"` // Days until re-consent required
	Active         bool       `json:"active" bun:"active,notnull,default:true"`
	PublishedAt    *time.Time `json:"publishedAt,omitempty" bun:"published_at"`
	Metadata       JSONBMap   `json:"metadata" bun:"metadata,type:jsonb"`
	CreatedBy      string     `json:"createdBy" bun:"created_by,type:varchar(20)"`
	CreatedAt      time.Time  `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt      time.Time  `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

ConsentPolicy defines consent policies per organization

type ConsentPolicyResponse

type ConsentPolicyResponse struct {
	ID string `json:"id" example:"policy_123"`
}

type ConsentRecord

type ConsentRecord struct {
	bun.BaseModel `bun:"table:consent_records,alias:cr"`

	ID             xid.ID     `json:"id" bun:"id,pk,type:varchar(20)"`
	UserID         string     `json:"userId" bun:"user_id,notnull,type:varchar(20)"`
	OrganizationID string     `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	ConsentType    string     `json:"consentType" bun:"consent_type,notnull"` // cookies, marketing, analytics, terms, privacy, data_processing
	Purpose        string     `json:"purpose" bun:"purpose,notnull"`          // specific purpose description
	Granted        bool       `json:"granted" bun:"granted,notnull"`
	Version        string     `json:"version" bun:"version,notnull"` // version of policy/terms
	IPAddress      string     `json:"ipAddress" bun:"ip_address"`
	UserAgent      string     `json:"userAgent" bun:"user_agent"`
	Metadata       JSONBMap   `json:"metadata" bun:"metadata,type:jsonb"`
	ExpiresAt      *time.Time `json:"expiresAt,omitempty" bun:"expires_at"` // consent expiry
	GrantedAt      time.Time  `json:"grantedAt" bun:"granted_at,notnull"`
	RevokedAt      *time.Time `json:"revokedAt,omitempty" bun:"revoked_at"`
	CreatedAt      time.Time  `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt      time.Time  `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

ConsentRecord tracks user consent for various purposes

type ConsentRecordResponse

type ConsentRecordResponse struct {
	ID string `json:"id" example:"consent_123"`
}

type ConsentReport

type ConsentReport struct {
	OrganizationID        string                  `json:"organizationId"`
	ReportPeriodStart     time.Time               `json:"reportPeriodStart"`
	ReportPeriodEnd       time.Time               `json:"reportPeriodEnd"`
	TotalUsers            int                     `json:"totalUsers"`
	UsersWithConsent      int                     `json:"usersWithConsent"`
	ConsentRate           float64                 `json:"consentRate"`
	ConsentsByType        map[string]ConsentStats `json:"consentsByType"`
	PendingDeletions      int                     `json:"pendingDeletions"`
	CompletedDeletions    int                     `json:"completedDeletions"`
	DataExportsThisPeriod int                     `json:"dataExportsThisPeriod"`
	DPAsActive            int                     `json:"dpasActive"`
	DPAsExpiringSoon      int                     `json:"dpasExpiringSoon"`
}

ConsentReport provides analytics and reporting data

type ConsentReportResponse

type ConsentReportResponse struct {
	ID string `json:"id" example:"report_123"`
}

type ConsentSettingsResponse

type ConsentSettingsResponse struct {
	Settings interface{} `json:"settings"`
}

type ConsentStats

type ConsentStats struct {
	Type            string  `json:"type"`
	TotalConsents   int     `json:"totalConsents"`
	GrantedCount    int     `json:"grantedCount"`
	RevokedCount    int     `json:"revokedCount"`
	ExpiredCount    int     `json:"expiredCount"`
	GrantRate       float64 `json:"grantRate"`
	AverageLifetime int     `json:"averageLifetime"` // Days
}

ConsentStats provides statistics for a consent type

type ConsentStatusResponse

type ConsentStatusResponse struct {
	Status string `json:"status" example:"success"`
}

DTOs for consent routes

type ConsentSummary

type ConsentSummary struct {
	UserID             string                       `json:"userId"`
	OrganizationID     string                       `json:"organizationId"`
	TotalConsents      int                          `json:"totalConsents"`
	GrantedConsents    int                          `json:"grantedConsents"`
	RevokedConsents    int                          `json:"revokedConsents"`
	ExpiredConsents    int                          `json:"expiredConsents"`
	PendingRenewals    int                          `json:"pendingRenewals"`
	ConsentsByType     map[string]ConsentTypeStatus `json:"consentsByType"`
	LastConsentUpdate  *time.Time                   `json:"lastConsentUpdate,omitempty"`
	HasPendingDeletion bool                         `json:"hasPendingDeletion"`
	HasPendingExport   bool                         `json:"hasPendingExport"`
}

ConsentSummary provides a summary of user's consent status

type ConsentType

type ConsentType string

ConsentType represents different types of consent

const (
	ConsentTypeCookies        ConsentType = "cookies"
	ConsentTypeMarketing      ConsentType = "marketing"
	ConsentTypeAnalytics      ConsentType = "analytics"
	ConsentTypeTerms          ConsentType = "terms"
	ConsentTypePrivacy        ConsentType = "privacy"
	ConsentTypeDataProcessing ConsentType = "data_processing"
	ConsentTypeThirdParty     ConsentType = "third_party"
	ConsentTypeCommunications ConsentType = "communications"
)

type ConsentTypeStatus

type ConsentTypeStatus struct {
	Type         string     `json:"type"`
	Granted      bool       `json:"granted"`
	Version      string     `json:"version"`
	GrantedAt    time.Time  `json:"grantedAt"`
	ExpiresAt    *time.Time `json:"expiresAt,omitempty"`
	NeedsRenewal bool       `json:"needsRenewal"`
}

ConsentTypeStatus represents consent status for a specific type

type ConsentsResponse

type ConsentsResponse struct {
	Consents interface{} `json:"consents"`
	Count    int         `json:"count"`
}

type CookieConsent

type CookieConsent struct {
	bun.BaseModel `bun:"table:cookie_consents,alias:cc"`

	ID                   xid.ID    `json:"id" bun:"id,pk,type:varchar(20)"`
	UserID               string    `json:"userId" bun:"user_id,type:varchar(20)"` // Nullable for anonymous users
	OrganizationID       string    `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	SessionID            string    `json:"sessionId" bun:"session_id"`                     // Track anonymous sessions
	Essential            bool      `json:"essential" bun:"essential,notnull,default:true"` // Always true
	Functional           bool      `json:"functional" bun:"functional"`
	Analytics            bool      `json:"analytics" bun:"analytics"`
	Marketing            bool      `json:"marketing" bun:"marketing"`
	Personalization      bool      `json:"personalization" bun:"personalization"`
	ThirdParty           bool      `json:"thirdParty" bun:"third_party"`
	IPAddress            string    `json:"ipAddress" bun:"ip_address"`
	UserAgent            string    `json:"userAgent" bun:"user_agent"`
	ConsentBannerVersion string    `json:"consentBannerVersion" bun:"consent_banner_version"`
	ExpiresAt            time.Time `json:"expiresAt" bun:"expires_at,notnull"`
	CreatedAt            time.Time `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt            time.Time `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

CookieConsent tracks cookie consent preferences

type CookieConsentConfig

type CookieConsentConfig struct {
	Enabled         bool          `json:"enabled" yaml:"enabled"`
	DefaultStyle    string        `json:"defaultStyle" yaml:"defaultStyle"`       // banner, modal, popup
	RequireExplicit bool          `json:"requireExplicit" yaml:"requireExplicit"` // No implied consent
	ValidityPeriod  time.Duration `json:"validityPeriod" yaml:"validityPeriod"`   // How long consent is valid
	AllowAnonymous  bool          `json:"allowAnonymous" yaml:"allowAnonymous"`   // Track consent for non-authenticated users
	BannerVersion   string        `json:"bannerVersion" yaml:"bannerVersion"`     // Current banner version
	Categories      []string      `json:"categories" yaml:"categories"`           // essential, functional, analytics, marketing, personalization, third_party
}

CookieConsentConfig configures cookie consent management

type CookieConsentRequest

type CookieConsentRequest struct {
	Essential       bool   `json:"essential"`
	Functional      bool   `json:"functional"`
	Analytics       bool   `json:"analytics"`
	Marketing       bool   `json:"marketing"`
	Personalization bool   `json:"personalization"`
	ThirdParty      bool   `json:"thirdParty"`
	SessionID       string `json:"sessionId,omitempty"` // For anonymous users
	BannerVersion   string `json:"bannerVersion,omitempty"`
}

CookieConsentRequest represents a cookie consent preference

type CreateConsentRequest

type CreateConsentRequest struct {
	UserID      string                 `json:"userId" validate:"required"`
	ConsentType string                 `json:"consentType" validate:"required"`
	Purpose     string                 `json:"purpose" validate:"required"`
	Granted     bool                   `json:"granted"`
	Version     string                 `json:"version" validate:"required"`
	ExpiresIn   *int                   `json:"expiresIn,omitempty"` // Days until expiry
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

CreateConsentRequest represents a request to record consent

type CreateDPARequest

type CreateDPARequest struct {
	AgreementType string                 `json:"agreementType" validate:"required"`
	Version       string                 `json:"version" validate:"required"`
	Content       string                 `json:"content" validate:"required"`
	SignedByName  string                 `json:"signedByName" validate:"required"`
	SignedByTitle string                 `json:"signedByTitle" validate:"required"`
	SignedByEmail string                 `json:"signedByEmail" validate:"required,email"`
	EffectiveDate time.Time              `json:"effectiveDate" validate:"required"`
	ExpiryDate    *time.Time             `json:"expiryDate,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

CreateDPARequest represents a request to create a data processing agreement

type CreatePolicyRequest

type CreatePolicyRequest struct {
	ConsentType    string                 `json:"consentType" validate:"required"`
	Name           string                 `json:"name" validate:"required"`
	Description    string                 `json:"description"`
	Version        string                 `json:"version" validate:"required"`
	Content        string                 `json:"content" validate:"required"`
	Required       bool                   `json:"required"`
	Renewable      bool                   `json:"renewable"`
	ValidityPeriod *int                   `json:"validityPeriod,omitempty"` // Days
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
}

CreatePolicyRequest represents a request to create a consent policy

type DataDeletionConfig

type DataDeletionConfig struct {
	Enabled               bool     `json:"enabled" yaml:"enabled"`
	RequireAdminApproval  bool     `json:"requireAdminApproval" yaml:"requireAdminApproval"`
	GracePeriodDays       int      `json:"gracePeriodDays" yaml:"gracePeriodDays"` // Days before actual deletion
	ArchiveBeforeDeletion bool     `json:"archiveBeforeDeletion" yaml:"archiveBeforeDeletion"`
	ArchivePath           string   `json:"archivePath" yaml:"archivePath"`
	RetentionExemptions   []string `json:"retentionExemptions" yaml:"retentionExemptions"` // Reasons to exempt from deletion
	NotifyBeforeDeletion  bool     `json:"notifyBeforeDeletion" yaml:"notifyBeforeDeletion"`
	AllowPartialDeletion  bool     `json:"allowPartialDeletion" yaml:"allowPartialDeletion"`   // Allow deleting specific sections
	PreserveLegalData     bool     `json:"preserveLegalData" yaml:"preserveLegalData"`         // Keep data required by law
	AutoProcessAfterGrace bool     `json:"autoProcessAfterGrace" yaml:"autoProcessAfterGrace"` // Auto-process after grace period
}

DataDeletionConfig configures right to be forgotten

type DataDeletionRequest

type DataDeletionRequest struct {
	bun.BaseModel `bun:"table:data_deletion_requests,alias:ddr"`

	ID              xid.ID     `json:"id" bun:"id,pk,type:varchar(20)"`
	UserID          string     `json:"userId" bun:"user_id,notnull,type:varchar(20)"`
	OrganizationID  string     `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	Status          string     `json:"status" bun:"status,notnull"` // pending, approved, processing, completed, rejected
	RequestReason   string     `json:"requestReason" bun:"request_reason,type:text"`
	RetentionExempt bool       `json:"retentionExempt" bun:"retention_exempt"` // Legal hold or other exemption
	ExemptionReason string     `json:"exemptionReason" bun:"exemption_reason"`
	DeleteSections  []string   `json:"deleteSections" bun:"delete_sections,type:text[]"` // all, profile, sessions, consents
	IPAddress       string     `json:"ipAddress" bun:"ip_address"`
	ApprovedBy      string     `json:"approvedBy" bun:"approved_by,type:varchar(20)"` // Admin who approved
	ApprovedAt      *time.Time `json:"approvedAt,omitempty" bun:"approved_at"`
	CompletedAt     *time.Time `json:"completedAt,omitempty" bun:"completed_at"`
	RejectedAt      *time.Time `json:"rejectedAt,omitempty" bun:"rejected_at"`
	ErrorMessage    string     `json:"errorMessage,omitempty" bun:"error_message"`
	ArchivePath     string     `json:"archivePath" bun:"archive_path"` // Backup before deletion
	CreatedAt       time.Time  `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt       time.Time  `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

DataDeletionRequest tracks GDPR right to be forgotten requests

type DataDeletionRequestInput

type DataDeletionRequestInput struct {
	Reason         string   `json:"reason" validate:"required"`
	DeleteSections []string `json:"deleteSections,omitempty"` // all, profile, sessions, consents
}

DataDeletionRequestInput represents a data deletion request

type DataExportConfig

type DataExportConfig struct {
	Enabled         bool          `json:"enabled" yaml:"enabled"`
	AllowedFormats  []string      `json:"allowedFormats" yaml:"allowedFormats"` // json, csv, xml, pdf
	DefaultFormat   string        `json:"defaultFormat" yaml:"defaultFormat"`
	MaxRequests     int           `json:"maxRequests" yaml:"maxRequests"`         // Max requests per user per period
	RequestPeriod   time.Duration `json:"requestPeriod" yaml:"requestPeriod"`     // Period for max requests (e.g., 30 days)
	ExpiryHours     int           `json:"expiryHours" yaml:"expiryHours"`         // How long export URL is valid
	StoragePath     string        `json:"storagePath" yaml:"storagePath"`         // Where to store exports
	IncludeSections []string      `json:"includeSections" yaml:"includeSections"` // Default sections: profile, sessions, consents, audit
	AutoCleanup     bool          `json:"autoCleanup" yaml:"autoCleanup"`         // Auto-delete expired exports
	CleanupInterval time.Duration `json:"cleanupInterval" yaml:"cleanupInterval"`
	MaxExportSize   int64         `json:"maxExportSize" yaml:"maxExportSize"` // Max export size in bytes
}

DataExportConfig configures data portability features

type DataExportRequest

type DataExportRequest struct {
	bun.BaseModel `bun:"table:data_export_requests,alias:der"`

	ID              xid.ID     `json:"id" bun:"id,pk,type:varchar(20)"`
	UserID          string     `json:"userId" bun:"user_id,notnull,type:varchar(20)"`
	OrganizationID  string     `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	Status          string     `json:"status" bun:"status,notnull"`                        // pending, processing, completed, failed
	Format          string     `json:"format" bun:"format,notnull"`                        // json, csv, xml
	IncludeSections []string   `json:"includeSections" bun:"include_sections,type:text[]"` // profile, sessions, consents, audit
	ExportURL       string     `json:"exportUrl" bun:"export_url"`
	ExportPath      string     `json:"exportPath" bun:"export_path"`
	ExportSize      int64      `json:"exportSize" bun:"export_size"`         // bytes
	ExpiresAt       *time.Time `json:"expiresAt,omitempty" bun:"expires_at"` // URL expiry
	IPAddress       string     `json:"ipAddress" bun:"ip_address"`
	CompletedAt     *time.Time `json:"completedAt,omitempty" bun:"completed_at"`
	ErrorMessage    string     `json:"errorMessage,omitempty" bun:"error_message"`
	CreatedAt       time.Time  `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt       time.Time  `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

DataExportRequest tracks GDPR data export requests

type DataExportRequestInput

type DataExportRequestInput struct {
	Format          string   `json:"format" validate:"required,oneof=json csv xml pdf"`
	IncludeSections []string `json:"includeSections,omitempty"` // profile, sessions, consents, audit, all
}

DataExportRequestInput represents a data export request

type DataProcessingAgreement

type DataProcessingAgreement struct {
	bun.BaseModel `bun:"table:data_processing_agreements,alias:dpa"`

	ID               xid.ID     `json:"id" bun:"id,pk,type:varchar(20)"`
	OrganizationID   string     `json:"organizationId" bun:"organization_id,notnull,type:varchar(20)"`
	AgreementType    string     `json:"agreementType" bun:"agreement_type,notnull"` // dpa, baa, ccpa, gdpr
	Version          string     `json:"version" bun:"version,notnull"`
	Content          string     `json:"content" bun:"content,type:text"`
	SignedBy         string     `json:"signedBy" bun:"signed_by,type:varchar(20)"` // User ID who signed
	SignedByName     string     `json:"signedByName" bun:"signed_by_name"`
	SignedByTitle    string     `json:"signedByTitle" bun:"signed_by_title"`
	SignedByEmail    string     `json:"signedByEmail" bun:"signed_by_email"`
	IPAddress        string     `json:"ipAddress" bun:"ip_address"`
	DigitalSignature string     `json:"digitalSignature" bun:"digital_signature,type:text"` // Cryptographic signature
	EffectiveDate    time.Time  `json:"effectiveDate" bun:"effective_date,notnull"`
	ExpiryDate       *time.Time `json:"expiryDate,omitempty" bun:"expiry_date"`
	Status           string     `json:"status" bun:"status,notnull"` // active, expired, revoked
	Metadata         JSONBMap   `json:"metadata" bun:"metadata,type:jsonb"`
	CreatedAt        time.Time  `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt        time.Time  `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

DataProcessingAgreement tracks DPA acceptance

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
	Error   string `json:"error,omitempty"`
}

ErrorResponse is a generic error response

type ExportFormat

type ExportFormat string

ExportFormat represents data export formats

const (
	FormatJSON ExportFormat = "json"
	FormatCSV  ExportFormat = "csv"
	FormatXML  ExportFormat = "xml"
	FormatPDF  ExportFormat = "pdf"
)

type Handler

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

Handler handles HTTP requests for consent management

func NewHandler

func NewHandler(service *Service) *Handler

NewHandler creates a new consent handler

func (*Handler) ApproveDeletionRequest

func (h *Handler) ApproveDeletionRequest(c forge.Context) error

ApproveDeletionRequest handles POST /consent/data-deletions/:id/approve (Admin only)

func (*Handler) CreateConsent

func (h *Handler) CreateConsent(c forge.Context) error

CreateConsent handles POST /consent/records

func (*Handler) CreateConsentPolicy

func (h *Handler) CreateConsentPolicy(c forge.Context) error

CreateConsentPolicy handles POST /consent/policies

func (*Handler) DownloadDataExport

func (h *Handler) DownloadDataExport(c forge.Context) error

DownloadDataExport handles GET /consent/data-exports/:id/download

func (*Handler) GenerateConsentReport

func (h *Handler) GenerateConsentReport(c forge.Context) error

GenerateConsentReport handles GET /consent/reports

func (*Handler) GetConsent

func (h *Handler) GetConsent(c forge.Context) error

GetConsent handles GET /consent/records/:id

func (*Handler) GetConsentAuditLogs

func (h *Handler) GetConsentAuditLogs(c forge.Context) error

GetConsentAuditLogs handles GET /consent/audit-logs

func (*Handler) GetConsentPolicy

func (h *Handler) GetConsentPolicy(c forge.Context) error

GetConsentPolicy handles GET /consent/policies/:id

func (*Handler) GetCookieConsent

func (h *Handler) GetCookieConsent(c forge.Context) error

GetCookieConsent handles GET /consent/cookies

func (*Handler) GetDataDeletion

func (h *Handler) GetDataDeletion(c forge.Context) error

GetDataDeletion handles GET /consent/data-deletions/:id

func (*Handler) GetDataExport

func (h *Handler) GetDataExport(c forge.Context) error

GetDataExport handles GET /consent/data-exports/:id

func (*Handler) GetPrivacySettings

func (h *Handler) GetPrivacySettings(c forge.Context) error

GetPrivacySettings handles GET /consent/privacy-settings

func (*Handler) ListConsentsByUser

func (h *Handler) ListConsentsByUser(c forge.Context) error

ListConsentsByUser handles GET /consent/records/user

func (*Handler) RecordCookieConsent

func (h *Handler) RecordCookieConsent(c forge.Context) error

RecordCookieConsent handles POST /consent/cookies

func (*Handler) RequestDataDeletion

func (h *Handler) RequestDataDeletion(c forge.Context) error

RequestDataDeletion handles POST /consent/data-deletions

func (*Handler) RequestDataExport

func (h *Handler) RequestDataExport(c forge.Context) error

RequestDataExport handles POST /consent/data-exports

func (*Handler) RevokeConsent

func (h *Handler) RevokeConsent(c forge.Context) error

RevokeConsent handles POST /consent/records/:id/revoke

func (*Handler) UpdateConsent

func (h *Handler) UpdateConsent(c forge.Context) error

UpdateConsent handles PATCH /consent/records/:id

func (*Handler) UpdatePrivacySettings

func (h *Handler) UpdatePrivacySettings(c forge.Context) error

UpdatePrivacySettings handles PATCH /consent/privacy-settings (Admin only)

type JSONBMap

type JSONBMap map[string]interface{}

JSONBMap is a helper type for JSONB fields

type MessageResponse

type MessageResponse = responses.MessageResponse

Response types - use shared responses from core

type Plugin

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

Plugin implements the AuthSome plugin interface for consent and privacy management

func NewPlugin

func NewPlugin() *Plugin

NewPlugin creates a new consent plugin instance

func (*Plugin) Description

func (p *Plugin) Description() string

Description returns the plugin description

func (*Plugin) GetUserConsentStatus

func (p *Plugin) GetUserConsentStatus(ctx context.Context, userID, orgID, consentType, purpose string) (bool, error)

GetUserConsentStatus returns consent status for a user (for use by other plugins)

func (*Plugin) Health

func (p *Plugin) Health(ctx context.Context) error

Health checks plugin health

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique plugin identifier

func (*Plugin) Init

func (p *Plugin) Init(auth interface{}) error

Init initializes the plugin with dependencies from AuthSome

func (*Plugin) Migrate

func (p *Plugin) Migrate() error

Migrate performs database migrations

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns the human-readable plugin name

func (*Plugin) RegisterHooks

func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error

RegisterHooks registers plugin hooks with the hook registry

func (*Plugin) RegisterRoutes

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes registers HTTP routes for the plugin

func (*Plugin) RegisterServiceDecorators

func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error

RegisterServiceDecorators allows plugins to replace core services with decorated versions

func (*Plugin) RequireConsent

func (p *Plugin) RequireConsent(consentType, purpose string) func(next func(forge.Context) error) func(forge.Context) error

RequireConsent middleware that checks if user has granted required consent

func (*Plugin) Service

func (p *Plugin) Service() *Service

Service returns the consent service for programmatic access (optional public method)

func (*Plugin) Shutdown

func (p *Plugin) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the plugin

func (*Plugin) Version

func (p *Plugin) Version() string

Version returns the plugin version

type PrivacySettings

type PrivacySettings struct {
	bun.BaseModel `bun:"table:privacy_settings,alias:ps"`

	ID                              xid.ID    `json:"id" bun:"id,pk,type:varchar(20)"`
	OrganizationID                  string    `json:"organizationId" bun:"organization_id,notnull,unique,type:varchar(20)"`
	ConsentRequired                 bool      `json:"consentRequired" bun:"consent_required,notnull,default:true"`
	CookieConsentEnabled            bool      `json:"cookieConsentEnabled" bun:"cookie_consent_enabled,notnull,default:true"`
	CookieConsentStyle              string    `json:"cookieConsentStyle" bun:"cookie_consent_style"` // banner, modal, popup
	DataRetentionDays               int       `json:"dataRetentionDays" bun:"data_retention_days"`
	AnonymousConsentEnabled         bool      `json:"anonymousConsentEnabled" bun:"anonymous_consent_enabled"`
	GDPRMode                        bool      `json:"gdprMode" bun:"gdpr_mode,notnull,default:false"`
	CCPAMode                        bool      `json:"ccpaMode" bun:"ccpa_mode,notnull,default:false"`
	AutoDeleteAfterDays             int       `json:"autoDeleteAfterDays" bun:"auto_delete_after_days"`
	RequireExplicitConsent          bool      `json:"requireExplicitConsent" bun:"require_explicit_consent"` // No implied consent
	AllowDataPortability            bool      `json:"allowDataPortability" bun:"allow_data_portability,notnull,default:true"`
	ExportFormat                    []string  `json:"exportFormat" bun:"export_format,type:text[]"` // json, csv, xml
	DataExportExpiryHours           int       `json:"dataExportExpiryHours" bun:"data_export_expiry_hours"`
	RequireAdminApprovalForDeletion bool      `json:"requireAdminApprovalForDeletion" bun:"require_admin_approval_for_deletion"`
	DeletionGracePeriodDays         int       `json:"deletionGracePeriodDays" bun:"deletion_grace_period_days"`
	ContactEmail                    string    `json:"contactEmail" bun:"contact_email"`
	ContactPhone                    string    `json:"contactPhone" bun:"contact_phone"`
	DPOEmail                        string    `json:"dpoEmail" bun:"dpo_email"` // Data Protection Officer
	Metadata                        JSONBMap  `json:"metadata" bun:"metadata,type:jsonb"`
	CreatedAt                       time.Time `json:"createdAt" bun:"created_at,notnull,default:current_timestamp"`
	UpdatedAt                       time.Time `json:"updatedAt" bun:"updated_at,notnull,default:current_timestamp"`
}

PrivacySettings stores per-organization privacy configurations

type PrivacySettingsRequest

type PrivacySettingsRequest struct {
	ConsentRequired                 *bool    `json:"consentRequired,omitempty"`
	CookieConsentEnabled            *bool    `json:"cookieConsentEnabled,omitempty"`
	CookieConsentStyle              string   `json:"cookieConsentStyle,omitempty"`
	DataRetentionDays               *int     `json:"dataRetentionDays,omitempty"`
	AnonymousConsentEnabled         *bool    `json:"anonymousConsentEnabled,omitempty"`
	GDPRMode                        *bool    `json:"gdprMode,omitempty"`
	CCPAMode                        *bool    `json:"ccpaMode,omitempty"`
	AutoDeleteAfterDays             *int     `json:"autoDeleteAfterDays,omitempty"`
	RequireExplicitConsent          *bool    `json:"requireExplicitConsent,omitempty"`
	AllowDataPortability            *bool    `json:"allowDataPortability,omitempty"`
	ExportFormat                    []string `json:"exportFormat,omitempty"`
	DataExportExpiryHours           *int     `json:"dataExportExpiryHours,omitempty"`
	RequireAdminApprovalForDeletion *bool    `json:"requireAdminApprovalForDeletion,omitempty"`
	DeletionGracePeriodDays         *int     `json:"deletionGracePeriodDays,omitempty"`
	ContactEmail                    string   `json:"contactEmail,omitempty"`
	ContactPhone                    string   `json:"contactPhone,omitempty"`
	DPOEmail                        string   `json:"dpoEmail,omitempty"`
}

PrivacySettingsRequest represents a request to update privacy settings

type Repository

type Repository interface {
	// Consent Records
	CreateConsent(ctx context.Context, consent *ConsentRecord) error
	GetConsent(ctx context.Context, id string) (*ConsentRecord, error)
	GetConsentByUserAndType(ctx context.Context, userID, orgID, consentType, purpose string) (*ConsentRecord, error)
	ListConsentsByUser(ctx context.Context, userID, orgID string) ([]*ConsentRecord, error)
	UpdateConsent(ctx context.Context, consent *ConsentRecord) error
	DeleteConsent(ctx context.Context, id string) error
	ExpireConsents(ctx context.Context, beforeDate time.Time) (int, error)

	// Consent Policies
	CreatePolicy(ctx context.Context, policy *ConsentPolicy) error
	GetPolicy(ctx context.Context, id string) (*ConsentPolicy, error)
	GetPolicyByTypeAndVersion(ctx context.Context, orgID, consentType, version string) (*ConsentPolicy, error)
	GetLatestPolicy(ctx context.Context, orgID, consentType string) (*ConsentPolicy, error)
	ListPolicies(ctx context.Context, orgID string, active *bool) ([]*ConsentPolicy, error)
	UpdatePolicy(ctx context.Context, policy *ConsentPolicy) error
	DeletePolicy(ctx context.Context, id string) error

	// Data Processing Agreements
	CreateDPA(ctx context.Context, dpa *DataProcessingAgreement) error
	GetDPA(ctx context.Context, id string) (*DataProcessingAgreement, error)
	GetActiveDPA(ctx context.Context, orgID, agreementType string) (*DataProcessingAgreement, error)
	ListDPAs(ctx context.Context, orgID string, status *string) ([]*DataProcessingAgreement, error)
	UpdateDPA(ctx context.Context, dpa *DataProcessingAgreement) error

	// Consent Audit Logs
	CreateAuditLog(ctx context.Context, log *ConsentAuditLog) error
	ListAuditLogs(ctx context.Context, userID, orgID string, limit int) ([]*ConsentAuditLog, error)
	GetAuditLogsByConsent(ctx context.Context, consentID string) ([]*ConsentAuditLog, error)

	// Cookie Consents
	CreateCookieConsent(ctx context.Context, consent *CookieConsent) error
	GetCookieConsent(ctx context.Context, userID, orgID string) (*CookieConsent, error)
	GetCookieConsentBySession(ctx context.Context, sessionID, orgID string) (*CookieConsent, error)
	UpdateCookieConsent(ctx context.Context, consent *CookieConsent) error

	// Data Export Requests
	CreateExportRequest(ctx context.Context, request *DataExportRequest) error
	GetExportRequest(ctx context.Context, id string) (*DataExportRequest, error)
	ListExportRequests(ctx context.Context, userID, orgID string, status *string) ([]*DataExportRequest, error)
	UpdateExportRequest(ctx context.Context, request *DataExportRequest) error
	DeleteExpiredExports(ctx context.Context, beforeDate time.Time) (int, error)

	// Data Deletion Requests
	CreateDeletionRequest(ctx context.Context, request *DataDeletionRequest) error
	GetDeletionRequest(ctx context.Context, id string) (*DataDeletionRequest, error)
	ListDeletionRequests(ctx context.Context, userID, orgID string, status *string) ([]*DataDeletionRequest, error)
	UpdateDeletionRequest(ctx context.Context, request *DataDeletionRequest) error
	GetPendingDeletionRequest(ctx context.Context, userID, orgID string) (*DataDeletionRequest, error)

	// Privacy Settings
	CreatePrivacySettings(ctx context.Context, settings *PrivacySettings) error
	GetPrivacySettings(ctx context.Context, orgID string) (*PrivacySettings, error)
	UpdatePrivacySettings(ctx context.Context, settings *PrivacySettings) error

	// Analytics
	GetConsentStats(ctx context.Context, orgID string, startDate, endDate time.Time) (map[string]interface{}, error)
}

Repository defines the interface for consent data access

func NewBunRepository

func NewBunRepository(db *bun.DB) Repository

NewBunRepository creates a new Bun-based repository

type RequestStatus

type RequestStatus string

RequestStatus represents the status of data export/deletion requests

const (
	StatusPending    RequestStatus = "pending"
	StatusApproved   RequestStatus = "approved"
	StatusProcessing RequestStatus = "processing"
	StatusCompleted  RequestStatus = "completed"
	StatusFailed     RequestStatus = "failed"
	StatusRejected   RequestStatus = "rejected"
)

type Service

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

Service provides consent management operations

func NewService

func NewService(
	repo Repository,
	config *Config,
	userService *user.Service,
) *Service

NewService creates a new consent service

func (*Service) ApproveDeletionRequest

func (s *Service) ApproveDeletionRequest(ctx context.Context, requestID, approverID, orgID string) error

ApproveDeletionRequest approves a deletion request

func (*Service) CreateConsent

func (s *Service) CreateConsent(ctx context.Context, orgID, userID string, req *CreateConsentRequest) (*ConsentRecord, error)

CreateConsent records a new consent

func (*Service) CreateDPA

func (s *Service) CreateDPA(ctx context.Context, orgID, signedBy string, req *CreateDPARequest) (*DataProcessingAgreement, error)

CreateDPA creates a new data processing agreement

func (*Service) CreatePolicy

func (s *Service) CreatePolicy(ctx context.Context, orgID, createdBy string, req *CreatePolicyRequest) (*ConsentPolicy, error)

CreatePolicy creates a new consent policy

func (*Service) ExpireConsents

func (s *Service) ExpireConsents(ctx context.Context) (int, error)

ExpireConsents automatically expires consents that have passed their expiry date

func (*Service) GenerateConsentReport

func (s *Service) GenerateConsentReport(ctx context.Context, orgID string, startDate, endDate time.Time) (*ConsentReport, error)

GenerateConsentReport generates analytics report

func (*Service) GetConsent

func (s *Service) GetConsent(ctx context.Context, id string) (*ConsentRecord, error)

GetConsent retrieves a consent record

func (*Service) GetConsentSummary

func (s *Service) GetConsentSummary(ctx context.Context, userID, orgID string) (*ConsentSummary, error)

GetConsentSummary provides a summary of user's consent status

func (*Service) GetCookieConsent

func (s *Service) GetCookieConsent(ctx context.Context, userID, orgID string) (*CookieConsent, error)

GetCookieConsent retrieves cookie consent preferences

func (*Service) GetDeletionRequest

func (s *Service) GetDeletionRequest(ctx context.Context, id string) (*DataDeletionRequest, error)

GetDeletionRequest retrieves a deletion request

func (*Service) GetExportRequest

func (s *Service) GetExportRequest(ctx context.Context, id string) (*DataExportRequest, error)

GetExportRequest retrieves an export request

func (*Service) GetLatestPolicy

func (s *Service) GetLatestPolicy(ctx context.Context, orgID, consentType string) (*ConsentPolicy, error)

GetLatestPolicy retrieves the latest active policy for a consent type

func (*Service) GetPolicy

func (s *Service) GetPolicy(ctx context.Context, id string) (*ConsentPolicy, error)

GetPolicy retrieves a consent policy

func (*Service) GetPrivacySettings

func (s *Service) GetPrivacySettings(ctx context.Context, orgID string) (*PrivacySettings, error)

GetPrivacySettings retrieves privacy settings for an organization

func (*Service) ListConsentsByUser

func (s *Service) ListConsentsByUser(ctx context.Context, userID, orgID string) ([]*ConsentRecord, error)

ListConsentsByUser lists all consents for a user

func (*Service) ListDeletionRequests

func (s *Service) ListDeletionRequests(ctx context.Context, userID, orgID string) ([]*DataDeletionRequest, error)

ListDeletionRequests lists deletion requests

func (*Service) ListExportRequests

func (s *Service) ListExportRequests(ctx context.Context, userID, orgID string) ([]*DataExportRequest, error)

ListExportRequests lists export requests for a user

func (*Service) ListPolicies

func (s *Service) ListPolicies(ctx context.Context, orgID string, activeOnly bool) ([]*ConsentPolicy, error)

ListPolicies lists policies for an organization

func (*Service) ProcessDeletionRequest

func (s *Service) ProcessDeletionRequest(ctx context.Context, requestID string) error

ProcessDeletionRequest processes an approved deletion request (GDPR Article 17)

func (*Service) PublishPolicy

func (s *Service) PublishPolicy(ctx context.Context, id, orgID string) error

PublishPolicy activates a policy

func (*Service) RecordCookieConsent

func (s *Service) RecordCookieConsent(ctx context.Context, orgID, userID string, req *CookieConsentRequest) (*CookieConsent, error)

RecordCookieConsent records cookie consent preferences

func (*Service) RequestDataDeletion

func (s *Service) RequestDataDeletion(ctx context.Context, userID, orgID string, req *DataDeletionRequestInput) (*DataDeletionRequest, error)

RequestDataDeletion creates a data deletion request

func (*Service) RequestDataExport

func (s *Service) RequestDataExport(ctx context.Context, userID, orgID string, req *DataExportRequestInput) (*DataExportRequest, error)

RequestDataExport creates a data export request

func (*Service) RevokeConsent

func (s *Service) RevokeConsent(ctx context.Context, userID, orgID, consentType, purpose string) error

RevokeConsent revokes a consent record

func (*Service) UpdateConsent

func (s *Service) UpdateConsent(ctx context.Context, id, userID, orgID string, req *UpdateConsentRequest) (*ConsentRecord, error)

UpdateConsent updates a consent record

func (*Service) UpdateCookieConsent

func (s *Service) UpdateCookieConsent(ctx context.Context, id, userID, orgID string, req *CookieConsentRequest) (*CookieConsent, error)

UpdateCookieConsent updates cookie consent preferences

func (*Service) UpdatePolicy

func (s *Service) UpdatePolicy(ctx context.Context, id, orgID, updatedBy string, req *UpdatePolicyRequest) (*ConsentPolicy, error)

UpdatePolicy updates a consent policy

func (*Service) UpdatePrivacySettings

func (s *Service) UpdatePrivacySettings(ctx context.Context, orgID, updatedBy string, req *PrivacySettingsRequest) (*PrivacySettings, error)

UpdatePrivacySettings updates privacy settings for an organization

type UpdateConsentRequest

type UpdateConsentRequest struct {
	Granted  *bool                  `json:"granted,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
	Reason   string                 `json:"reason,omitempty"`
}

UpdateConsentRequest represents a request to update consent

type UpdatePolicyRequest

type UpdatePolicyRequest struct {
	Name           string                 `json:"name,omitempty"`
	Description    string                 `json:"description,omitempty"`
	Content        string                 `json:"content,omitempty"`
	Required       *bool                  `json:"required,omitempty"`
	Renewable      *bool                  `json:"renewable,omitempty"`
	ValidityPeriod *int                   `json:"validityPeriod,omitempty"`
	Active         *bool                  `json:"active,omitempty"`
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
}

UpdatePolicyRequest represents a request to update a policy

Jump to

Keyboard shortcuts

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