notification

package
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 40 Imported by: 0

README

Notification Plugin

The Notification plugin provides comprehensive template-based notification management for AuthSome, supporting both SaaS and standalone modes with multi-language templates.

Features

  • Template Management: Create, update, and manage notification templates via API
  • Multi-Language Support: Templates can be created in multiple languages
  • Organization-Scoped Templates: SaaS mode allows org-specific template overrides
  • Default Templates: Includes 9 pre-configured templates for common auth flows
  • Variable Substitution: Dynamic template rendering with Go template syntax
  • Multiple Channels: Email and SMS notifications (extensible for push)
  • Template Versioning: Track and audit template changes
  • Preview Mode: Test templates before deployment

Configuration

auth:
  notification:
    add_default_templates: true
    default_language: "en"
    allow_org_overrides: false  # true for SaaS mode
    auto_send_welcome: true
    retry_attempts: 3
    retry_delay: "5m"
    cleanup_after: "720h"  # 30 days
    
    rate_limits:
      email:
        max_requests: 100
        window: "1h"
      sms:
        max_requests: 50
        window: "1h"
    
    providers:
      email:
        provider: "smtp"
        from: "noreply@example.com"
        from_name: "AuthSome"
        config:
          host: "smtp.example.com"
          port: 587
          username: "smtp-user"
          password: "smtp-pass"
      sms:
        provider: "twilio"
        from: "+1234567890"
        config:
          account_sid: "your-account-sid"
          auth_token: "your-auth-token"

Default Templates

The plugin includes these default templates:

  1. auth.welcome - Welcome email for new users
  2. auth.verify_email - Email verification
  3. auth.password_reset - Password reset email
  4. auth.mfa_code - MFA verification code (email/SMS)
  5. auth.magic_link - Magic link sign-in
  6. auth.email_otp - Email OTP code
  7. auth.phone_otp - Phone OTP SMS
  8. auth.security_alert - Security event notifications

Usage in Other Plugins

Simple Adapter Usage
package myplugin

import (
	"context"
	notificationPlugin "github.com/xraph/authsome/plugins/notification"
)

type MyPlugin struct {
	notifAdapter *notificationPlugin.Adapter
}

func (p *MyPlugin) Init(dep interface{}) error {
	// Get notification service from registry
	registry := dep.(*registry.ServiceRegistry)
	templateSvc := registry.Get("notification.template").(*notificationPlugin.TemplateService)
	
	p.notifAdapter = notificationPlugin.NewAdapter(templateSvc)
	return nil
}

func (p *MyPlugin) SendVerificationCode(ctx context.Context, email, code string) error {
	return p.notifAdapter.SendEmailOTP(ctx, "default", email, code, 10)
}
Direct Service Usage
import (
	"github.com/xraph/authsome/core/notification"
	notificationPlugin "github.com/xraph/authsome/plugins/notification"
)

// Send with template
func sendWithTemplate(ctx context.Context, templateSvc *notificationPlugin.TemplateService) error {
	_, err := templateSvc.SendWithTemplate(ctx, &notificationPlugin.SendWithTemplateRequest{
		OrganizationID: "org_123",
		TemplateKey:    "auth.mfa_code",
		Type:           notification.NotificationTypeEmail,
		Recipient:      "user@example.com",
		Variables: map[string]interface{}{
			"user_name":      "John Doe",
			"code":           "123456",
			"expiry_minutes": 10,
			"app_name":       "MyApp",
		},
	})
	return err
}

// Send direct without template
func sendDirect(ctx context.Context, templateSvc *notificationPlugin.TemplateService) error {
	_, err := templateSvc.SendDirect(
		ctx,
		"org_123",
		notification.NotificationTypeEmail,
		"user@example.com",
		"Subject",
		"Email body",
		nil,
	)
	return err
}

API Endpoints

Template Management
# Create template
POST /auth/templates
{
  "organization_id": "org_123",
  "template_key": "custom.welcome",
  "name": "Custom Welcome Email",
  "type": "email",
  "language": "en",
  "subject": "Welcome {{.user_name}}!",
  "body": "Hi {{.user_name}}, welcome to {{.app_name}}!",
  "variables": ["user_name", "app_name"]
}

# List templates
GET /auth/templates?organization_id=org_123&type=email&language=en

# Get template
GET /auth/templates/:id

# Update template
PUT /auth/templates/:id
{
  "subject": "Updated subject",
  "active": true
}

# Delete template
DELETE /auth/templates/:id

# Preview template
POST /auth/templates/:id/preview
{
  "variables": {
    "user_name": "Test User",
    "app_name": "TestApp"
  }
}
Sending Notifications
# Send notification with template
POST /auth/notifications/send
{
  "organization_id": "org_123",
  "template_key": "auth.welcome",
  "type": "email",
  "recipient": "user@example.com",
  "variables": {
    "user_name": "John Doe",
    "user_email": "user@example.com",
    "app_name": "MyApp",
    "login_url": "https://app.example.com/login"
  }
}

# List notifications
GET /auth/notifications?organization_id=org_123&status=sent

# Get notification
GET /auth/notifications/:id

# Resend failed notification
POST /auth/notifications/:id/resend
Admin Endpoints

Requires admin role and notification:admin permission.

# List templates (admin)
GET /notification/admin/templates?appId=app_123&type=email
Authorization: Bearer <admin-token>

# Response:
{
  "templates": [...],
  "total": 15,
  "appId": "app_123"
}

# Get specific template (admin)
GET /notification/admin/templates/:id
Authorization: Bearer <admin-token>

# Update template (admin)
PUT /notification/admin/templates/:id
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "subject": "Updated {{.user_name}}!",
  "body": "New template body...",
  "active": true
}

# Send test notification (admin)
POST /notification/admin/templates/:id/test
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "recipient": "admin@example.com",
  "variables": {
    "user_name": "Test User",
    "code": "123456",
    "expiry_minutes": 10
  }
}

# Response:
{
  "message": "test notification sent successfully",
  "notification": {
    "id": "notif_123",
    "status": "sent",
    ...
  }
}

# Get notification statistics (admin)
GET /notification/admin/stats?appId=app_123
Authorization: Bearer <admin-token>

# Response:
{
  "appId": "app_123",
  "total": {
    "sent": 1250,
    "delivered": 1180,
    "failed": 45,
    "pending": 25
  },
  "byType": {
    "email": 800,
    "sms": 350,
    "push": 100
  },
  "last24h": {
    "sent": 85,
    "delivered": 82,
    "failed": 3
  }
}

Note: Admin endpoints are currently placeholders. Full implementation requires:

  • RBAC integration for permission checks
  • Audit logging for administrative actions
  • Real-time statistics from database
  • Template version control

See Plugin Admin Endpoint Guidelines for implementation details.

Template Syntax

Templates use Go's text/template syntax:

Subject: Welcome to {{.app_name}}, {{.user_name}}!

Body:
Hi {{.user_name}},

Your verification code is: {{.code}}

This code expires in {{.expiry_minutes}} minutes.

{{if .support_email}}
Need help? Contact us at {{.support_email}}
{{end}}

Best regards,
The {{.app_name}} Team
Available Functions
  • {{upper .text}} - Convert to uppercase
  • {{lower .text}} - Convert to lowercase
  • {{title .text}} - Title case
  • {{trim .text}} - Trim whitespace
  • {{truncate .text 100}} - Truncate to length
  • {{default "fallback" .value}} - Default value if empty

SaaS Mode Features

Organization-Specific Templates

In SaaS mode with allow_org_overrides: true:

# Override default template for org_123
POST /auth/templates
{
  "organization_id": "org_123",
  "template_key": "auth.welcome",  # Same key as default
  "name": "Org 123 Welcome Email",
  "type": "email",
  "language": "en",
  "subject": "Welcome to Org 123!",
  "body": "Custom welcome message..."
}

The plugin will automatically:

  1. Try org-specific template first (org_123)
  2. Fall back to default template if not found
  3. Support language fallback (requested lang → "en")
Multi-Language Support
# Create Spanish version
POST /auth/templates
{
  "organization_id": "default",
  "template_key": "auth.welcome",
  "name": "Bienvenida",
  "type": "email",
  "language": "es",
  "subject": "¡Bienvenido a {{.app_name}}!",
  "body": "Hola {{.user_name}}..."
}

# Request Spanish template
POST /auth/notifications/send
{
  "template_key": "auth.welcome",
  "type": "email",
  "language": "es",
  ...
}

Migration

The plugin automatically runs migrations to create:

  • notification_templates table
  • notifications table
  • Indexes for performance
  • Default templates (if enabled)

Observability

Audit Logging

All template operations are logged:

  • Template creation/updates/deletions
  • Notification sending
  • Template rendering failures
Metrics to Monitor
  • Notification send rate
  • Template rendering time
  • Delivery success rate
  • Failed notifications count
Cleanup

Old notifications are automatically cleaned up based on cleanup_after configuration.

Security Considerations

  1. Template Injection: Templates are validated before saving
  2. Rate Limiting: Configurable per channel
  3. PII Protection: Notifications shouldn't log sensitive data
  4. Organization Isolation: Templates are org-scoped in SaaS mode

Production Best Practices

  1. Test Templates: Use preview endpoint before activating
  2. Version Templates: Keep metadata for tracking changes
  3. Monitor Delivery: Track notification status
  4. Set up Webhooks: Provider callbacks for delivery status
  5. Configure Retries: Handle temporary failures
  6. Cache Templates: Templates are cached after first load

Extending

Custom Providers

Implement the notification.Provider interface:

type CustomProvider struct {}

func (p *CustomProvider) ID() string { return "custom" }
func (p *CustomProvider) Type() notification.NotificationType { return "email" }
func (p *CustomProvider) Send(ctx context.Context, n *notification.Notification) error { ... }
func (p *CustomProvider) GetStatus(ctx context.Context, id string) (notification.NotificationStatus, error) { ... }
func (p *CustomProvider) ValidateConfig() error { ... }

// Register
notificationSvc.RegisterProvider(&CustomProvider{})
Custom Templates

Add your own templates programmatically:

templateSvc.service.CreateTemplate(ctx, &notification.CreateTemplateRequest{
	OrganizationID: "default",
	TemplateKey:    "my.custom",
	Name:           "My Custom Template",
	Type:           notification.NotificationTypeEmail,
	Language:       "en",
	Subject:        "...",
	Body:           "...",
	Variables:      []string{"var1", "var2"},
})

Troubleshooting

Template Not Found
  • Check organization_id matches
  • Verify template_key is correct
  • Ensure template is active
  • Check language fallback
Rendering Failures
  • Validate template syntax
  • Ensure all variables are provided
  • Check for template function errors
Send Failures
  • Verify provider configuration
  • Check rate limits
  • Review provider credentials
  • Check network connectivity

See Also

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NewResendProvider     = providers.NewResendProvider
	NewMailerSendProvider = providers.NewMailerSendProvider
	NewPostmarkProvider   = providers.NewPostmarkProvider
)

Re-export provider constructors.

Functions

This section is empty.

Types

type AccountAutoSendConfig added in v0.0.6

type AccountAutoSendConfig struct {
	EmailChangeRequest bool `json:"email_change_request" yaml:"email_change_request"`
	EmailChanged       bool `json:"email_changed"        yaml:"email_changed"`
	PasswordChanged    bool `json:"password_changed"     yaml:"password_changed"`
	UsernameChanged    bool `json:"username_changed"     yaml:"username_changed"`
	Deleted            bool `json:"deleted"              yaml:"deleted"`
	Suspended          bool `json:"suspended"            yaml:"suspended"`
	Reactivated        bool `json:"reactivated"          yaml:"reactivated"`
}

AccountAutoSendConfig controls account lifecycle notifications.

type AccountAutoSendDTO added in v0.0.15

type AccountAutoSendDTO struct {
	EmailChangeRequest bool `json:"emailChangeRequest"`
	EmailChanged       bool `json:"emailChanged"`
	PasswordChanged    bool `json:"passwordChanged"`
	UsernameChanged    bool `json:"usernameChanged"`
	Deleted            bool `json:"deleted"`
	Suspended          bool `json:"suspended"`
	Reactivated        bool `json:"reactivated"`
}

AccountAutoSendDTO represents account lifecycle notification settings.

type Adapter

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

Adapter provides a simplified interface for plugins to send notifications.

func NewAdapter

func NewAdapter(templateSvc *TemplateService) *Adapter

NewAdapter creates a new notification adapter.

func (*Adapter) SendAccountDeleted added in v0.0.6

func (a *Adapter) SendAccountDeleted(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAccountDeleted sends notification when account is deleted.

func (*Adapter) SendAccountReactivated added in v0.0.6

func (a *Adapter) SendAccountReactivated(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAccountReactivated sends notification when account is reactivated.

func (*Adapter) SendAccountSuspended added in v0.0.6

func (a *Adapter) SendAccountSuspended(ctx context.Context, appID xid.ID, recipientEmail, userName, reason, timestamp string) error

SendAccountSuspended sends notification when account is suspended.

func (*Adapter) SendAllSessionsRevoked added in v0.0.6

func (a *Adapter) SendAllSessionsRevoked(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAllSessionsRevoked sends notification when all sessions are signed out.

func (*Adapter) SendCustom

func (a *Adapter) SendCustom(ctx context.Context, appID xid.ID, templateKey, recipient string, notifType notification.NotificationType, variables map[string]any) error

SendCustom sends a notification using a custom template.

func (*Adapter) SendDeviceRemoved added in v0.0.6

func (a *Adapter) SendDeviceRemoved(ctx context.Context, appID xid.ID, recipientEmail, userName, deviceName, timestamp string) error

SendDeviceRemoved sends notification when a device is removed from the account.

func (*Adapter) SendDirectEmail

func (a *Adapter) SendDirectEmail(ctx context.Context, appID xid.ID, recipient, subject, body string) error

SendDirectEmail sends an email without using a template.

func (*Adapter) SendDirectSMS

func (a *Adapter) SendDirectSMS(ctx context.Context, appID xid.ID, recipient, body string) error

SendDirectSMS sends an SMS without using a template.

func (*Adapter) SendEmailChangeRequest added in v0.0.6

func (a *Adapter) SendEmailChangeRequest(ctx context.Context, appID xid.ID, recipientEmail, userName, newEmail, confirmationUrl, timestamp string) error

SendEmailChangeRequest sends notification when user requests to change their email.

func (*Adapter) SendEmailChanged added in v0.0.6

func (a *Adapter) SendEmailChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, oldEmail, timestamp string) error

SendEmailChanged sends notification when email address is successfully changed.

func (*Adapter) SendEmailOTP

func (a *Adapter) SendEmailOTP(ctx context.Context, appID xid.ID, email, code string, expiryMinutes int) error

SendEmailOTP sends an email OTP code.

func (*Adapter) SendMFACode

func (a *Adapter) SendMFACode(ctx context.Context, appID xid.ID, recipient, code string, expiryMinutes int, notifType notification.NotificationType) error

SendMFACode sends an MFA verification code via email or SMS.

func (a *Adapter) SendMagicLink(ctx context.Context, appID xid.ID, email, userName, magicLink string, expiryMinutes int) error

SendMagicLink sends a magic link email.

func (*Adapter) SendNewDeviceLogin added in v0.0.6

func (a *Adapter) SendNewDeviceLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, deviceName, location, timestamp, ipAddress string) error

SendNewDeviceLogin sends notification when a user logs in from a new device.

func (*Adapter) SendNewLocationLogin added in v0.0.6

func (a *Adapter) SendNewLocationLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, location, timestamp, ipAddress string) error

SendNewLocationLogin sends notification when a user logs in from a new location.

func (*Adapter) SendOrgDeleted added in v0.0.6

func (a *Adapter) SendOrgDeleted(ctx context.Context, appID xid.ID, recipientEmail, userName, orgName string) error

SendOrgDeleted sends notification when an organization is deleted.

func (*Adapter) SendOrgInvite added in v0.0.6

func (a *Adapter) SendOrgInvite(ctx context.Context, appID xid.ID, recipientEmail, userName, inviterName, orgName, role, inviteURL string, expiresIn string) error

SendOrgInvite sends an organization invitation email.

func (*Adapter) SendOrgMemberAdded added in v0.0.6

func (a *Adapter) SendOrgMemberAdded(ctx context.Context, appID xid.ID, recipientEmail, userName, memberName, orgName, role string) error

SendOrgMemberAdded sends notification when a member is added to organization.

func (*Adapter) SendOrgMemberLeft added in v0.0.6

func (a *Adapter) SendOrgMemberLeft(ctx context.Context, appID xid.ID, recipientEmail, userName, memberName, orgName, timestamp string) error

SendOrgMemberLeft sends notification when a member leaves an organization.

func (*Adapter) SendOrgMemberRemoved added in v0.0.6

func (a *Adapter) SendOrgMemberRemoved(ctx context.Context, appID xid.ID, recipientEmail, userName, memberName, orgName, timestamp string) error

SendOrgMemberRemoved sends notification when a member is removed from organization.

func (*Adapter) SendOrgRoleChanged added in v0.0.6

func (a *Adapter) SendOrgRoleChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, orgName, oldRole, newRole string) error

SendOrgRoleChanged sends notification when a member's role is changed.

func (*Adapter) SendOrgTransfer added in v0.0.6

func (a *Adapter) SendOrgTransfer(ctx context.Context, appID xid.ID, recipientEmail, userName, orgName, transferredTo, timestamp string) error

SendOrgTransfer sends notification when organization ownership is transferred.

func (*Adapter) SendPasswordChanged added in v0.0.6

func (a *Adapter) SendPasswordChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendPasswordChanged sends notification when password is changed.

func (*Adapter) SendPasswordReset

func (a *Adapter) SendPasswordReset(ctx context.Context, appID xid.ID, email, userName, resetURL, resetCode string, expiryMinutes int) error

SendPasswordReset sends a password reset email.

func (*Adapter) SendPhoneOTP

func (a *Adapter) SendPhoneOTP(ctx context.Context, appID xid.ID, phone, code string) error

SendPhoneOTP sends a phone OTP code via SMS.

func (*Adapter) SendSecurityAlert

func (a *Adapter) SendSecurityAlert(ctx context.Context, appID xid.ID, email, userName, eventType, eventTime, location, device string) error

SendSecurityAlert sends a security alert notification.

func (*Adapter) SendSuspiciousLogin added in v0.0.6

func (a *Adapter) SendSuspiciousLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, reason, location, timestamp, ipAddress string) error

SendSuspiciousLogin sends notification when suspicious login activity is detected.

func (*Adapter) SendUsernameChanged added in v0.0.6

func (a *Adapter) SendUsernameChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, oldUsername, newUsername, timestamp string) error

SendUsernameChanged sends notification when username is changed.

func (*Adapter) SendVerificationEmail

func (a *Adapter) SendVerificationEmail(ctx context.Context, appID xid.ID, email, userName, verificationURL, verificationCode string, expiryMinutes int) error

SendVerificationEmail sends an email verification link.

func (*Adapter) SendWelcomeEmail

func (a *Adapter) SendWelcomeEmail(ctx context.Context, appID xid.ID, email, userName, loginURL string) error

SendWelcomeEmail sends a welcome email to new users.

func (*Adapter) WithAppName added in v0.0.6

func (a *Adapter) WithAppName(name string) *Adapter

WithAppName sets a static app name override.

func (*Adapter) WithAppService added in v0.0.6

func (a *Adapter) WithAppService(appSvc any) *Adapter

WithAppService sets the app service for dynamic app name lookup.

type AnalyticsDTO added in v0.0.15

type AnalyticsDTO struct {
	Overview     OverviewStatsDTO         `json:"overview"`
	ByTemplate   []TemplateAnalyticsDTO   `json:"byTemplate"`
	ByDay        []DailyAnalyticsDTO      `json:"byDay"`
	TopTemplates []TemplatePerformanceDTO `json:"topTemplates"`
}

AnalyticsDTO represents detailed analytics.

type AsyncAdapter added in v0.0.7

type AsyncAdapter struct {
	*Adapter
	// contains filtered or unexported fields
}

AsyncAdapter wraps the standard Adapter to provide async notification sending based on notification priority. Critical notifications are sent synchronously, while non-critical notifications are sent asynchronously to avoid blocking.

func NewAsyncAdapter added in v0.0.7

func NewAsyncAdapter(adapter *Adapter, config AsyncConfig, dispatcher *notification.Dispatcher, retry *notification.RetryService) *AsyncAdapter

NewAsyncAdapter creates a new async notification adapter.

func (*AsyncAdapter) SendAccountDeleted added in v0.0.7

func (a *AsyncAdapter) SendAccountDeleted(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAccountDeleted sends an account deleted notification - NORMAL priority (async).

func (*AsyncAdapter) SendAccountReactivated added in v0.0.7

func (a *AsyncAdapter) SendAccountReactivated(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAccountReactivated sends an account reactivated notification - NORMAL priority (async).

func (*AsyncAdapter) SendAccountSuspended added in v0.0.7

func (a *AsyncAdapter) SendAccountSuspended(ctx context.Context, appID xid.ID, email, userName, reason, timestamp string) error

SendAccountSuspended sends an account suspended notification - HIGH priority (async with logging).

func (*AsyncAdapter) SendAllSessionsRevoked added in v0.0.7

func (a *AsyncAdapter) SendAllSessionsRevoked(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendAllSessionsRevoked sends all sessions revoked notification - LOW priority (fire-and-forget).

func (*AsyncAdapter) SendDeviceRemoved added in v0.0.7

func (a *AsyncAdapter) SendDeviceRemoved(ctx context.Context, appID xid.ID, recipientEmail, userName, deviceName, timestamp string) error

SendDeviceRemoved sends a device removed notification - LOW priority (fire-and-forget).

func (*AsyncAdapter) SendEmailChangeRequest added in v0.0.7

func (a *AsyncAdapter) SendEmailChangeRequest(ctx context.Context, appID xid.ID, recipientEmail, userName, newEmail, confirmationUrl, timestamp string) error

SendEmailChangeRequest sends an email change request notification - HIGH priority (async with logging).

func (*AsyncAdapter) SendEmailChanged added in v0.0.7

func (a *AsyncAdapter) SendEmailChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, oldEmail, timestamp string) error

SendEmailChanged sends an email changed notification - NORMAL priority (async).

func (*AsyncAdapter) SendEmailOTP added in v0.0.7

func (a *AsyncAdapter) SendEmailOTP(ctx context.Context, appID xid.ID, email, code string, expiryMinutes int) error

SendEmailOTP sends an email OTP code - CRITICAL priority (sync).

func (*AsyncAdapter) SendMFACode added in v0.0.7

func (a *AsyncAdapter) SendMFACode(ctx context.Context, appID xid.ID, recipient, code string, expiryMinutes int, notifType notification.NotificationType) error

SendMFACode sends an MFA verification code - CRITICAL priority (sync).

func (a *AsyncAdapter) SendMagicLink(ctx context.Context, appID xid.ID, email, userName, magicLink string, expiryMinutes int) error

SendMagicLink sends a magic link email - CRITICAL priority (sync).

func (*AsyncAdapter) SendNewDeviceLogin added in v0.0.7

func (a *AsyncAdapter) SendNewDeviceLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, deviceName, location, timestamp, ipAddress string) error

SendNewDeviceLogin sends a new device login notification - LOW priority (fire-and-forget).

func (*AsyncAdapter) SendNewLocationLogin added in v0.0.7

func (a *AsyncAdapter) SendNewLocationLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, location, timestamp, ipAddress string) error

SendNewLocationLogin sends a new location login notification - LOW priority (fire-and-forget).

func (*AsyncAdapter) SendOrgInvite added in v0.0.7

func (a *AsyncAdapter) SendOrgInvite(ctx context.Context, appID xid.ID, recipientEmail, userName, inviterName, orgName, role, inviteURL, expiresIn string) error

SendOrgInvite sends an organization invite notification - HIGH priority (async with logging).

func (*AsyncAdapter) SendOrgMemberAdded added in v0.0.7

func (a *AsyncAdapter) SendOrgMemberAdded(ctx context.Context, appID xid.ID, recipientEmail, userName, memberName, orgName, role string) error

SendOrgMemberAdded sends an organization member added notification - NORMAL priority (async).

func (*AsyncAdapter) SendOrgMemberRemoved added in v0.0.7

func (a *AsyncAdapter) SendOrgMemberRemoved(ctx context.Context, appID xid.ID, recipientEmail, userName, memberName, orgName, timestamp string) error

SendOrgMemberRemoved sends an organization member removed notification - NORMAL priority (async).

func (*AsyncAdapter) SendPasswordChanged added in v0.0.7

func (a *AsyncAdapter) SendPasswordChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, timestamp string) error

SendPasswordChanged sends a password changed notification - NORMAL priority (async).

func (*AsyncAdapter) SendPasswordReset added in v0.0.7

func (a *AsyncAdapter) SendPasswordReset(ctx context.Context, appID xid.ID, email, userName, resetURL, resetCode string, expiryMinutes int) error

SendPasswordReset sends a password reset email - CRITICAL priority (sync).

func (*AsyncAdapter) SendPhoneOTP added in v0.0.7

func (a *AsyncAdapter) SendPhoneOTP(ctx context.Context, appID xid.ID, phone, code string) error

SendPhoneOTP sends a phone OTP code - CRITICAL priority (sync).

func (*AsyncAdapter) SendSecurityAlert added in v0.0.7

func (a *AsyncAdapter) SendSecurityAlert(ctx context.Context, appID xid.ID, email, userName, eventType, eventTime, location, device string) error

SendSecurityAlert sends a security alert notification - HIGH priority (async with logging).

func (*AsyncAdapter) SendSuspiciousLogin added in v0.0.7

func (a *AsyncAdapter) SendSuspiciousLogin(ctx context.Context, appID xid.ID, recipientEmail, userName, reason, location, timestamp, ipAddress string) error

SendSuspiciousLogin sends a suspicious login alert - HIGH priority (async with logging).

func (*AsyncAdapter) SendUsernameChanged added in v0.0.7

func (a *AsyncAdapter) SendUsernameChanged(ctx context.Context, appID xid.ID, recipientEmail, userName, oldUsername, newUsername, timestamp string) error

SendUsernameChanged sends a username changed notification - NORMAL priority (async).

func (*AsyncAdapter) SendVerificationEmail added in v0.0.7

func (a *AsyncAdapter) SendVerificationEmail(ctx context.Context, appID xid.ID, email, userName, verificationURL, verificationCode string, expiryMinutes int) error

SendVerificationEmail sends a verification email - HIGH priority (async with logging).

func (*AsyncAdapter) SendWelcomeEmail added in v0.0.7

func (a *AsyncAdapter) SendWelcomeEmail(ctx context.Context, appID xid.ID, email, userName, loginURL string) error

SendWelcomeEmail sends a welcome email - NORMAL priority (async).

type AsyncConfig added in v0.0.7

type AsyncConfig struct {
	// Enabled enables async processing for non-critical notifications
	Enabled bool `json:"enabled" yaml:"enabled"`
	// WorkerPoolSize is the number of workers for async processing
	WorkerPoolSize int `json:"worker_pool_size" yaml:"worker_pool_size"`
	// QueueSize is the buffer size for async queues
	QueueSize int `json:"queue_size" yaml:"queue_size"`
	// RetryEnabled enables retry for failed notifications
	RetryEnabled bool `json:"retry_enabled" yaml:"retry_enabled"`
	// MaxRetries is the maximum number of retry attempts
	MaxRetries int `json:"max_retries" yaml:"max_retries"`
	// RetryBackoff are the delays between retries (e.g., ["1m", "5m", "15m"])
	RetryBackoff []string `json:"retry_backoff" yaml:"retry_backoff"`
	// PersistFailures persists permanently failed notifications to DB
	PersistFailures bool `json:"persist_failures" yaml:"persist_failures"`
}

AsyncConfig controls asynchronous notification processing.

type AuthAutoSendConfig added in v0.0.6

type AuthAutoSendConfig struct {
	Welcome           bool `json:"welcome"            yaml:"welcome"`
	VerificationEmail bool `json:"verification_email" yaml:"verification_email"`
	MagicLink         bool `json:"magic_link"         yaml:"magic_link"`
	EmailOTP          bool `json:"email_otp"          yaml:"email_otp"`
	MFACode           bool `json:"mfa_code"           yaml:"mfa_code"`
	PasswordReset     bool `json:"password_reset"     yaml:"password_reset"`
}

AuthAutoSendConfig controls authentication-related notifications.

type AuthAutoSendDTO added in v0.0.15

type AuthAutoSendDTO struct {
	Welcome           bool `json:"welcome"`
	VerificationEmail bool `json:"verificationEmail"`
	MagicLink         bool `json:"magicLink"`
	EmailOTP          bool `json:"emailOtp"`
	MFACode           bool `json:"mfaCode"`
	PasswordReset     bool `json:"passwordReset"`
}

AuthAutoSendDTO represents authentication notification settings.

type AutoSendConfig added in v0.0.6

type AutoSendConfig struct {
	Auth         AuthAutoSendConfig         `json:"auth"         yaml:"auth"`
	Organization OrganizationAutoSendConfig `json:"organization" yaml:"organization"`
	Session      SessionAutoSendConfig      `json:"session"      yaml:"session"`
	Account      AccountAutoSendConfig      `json:"account"      yaml:"account"`
}

AutoSendConfig controls automatic notification sending for lifecycle events.

type ChannelsResponse

type ChannelsResponse struct {
	Channels any `json:"channels"`
	Count    int `json:"count"`
}

type Config

type Config struct {
	// AddDefaultTemplates automatically adds default templates on startup
	AddDefaultTemplates bool `json:"add_default_templates" yaml:"add_default_templates"`

	// DefaultLanguage is the default language for templates
	DefaultLanguage string `json:"default_language" yaml:"default_language"`

	// AllowAppOverrides allows apps to override default templates in SaaS mode
	AllowAppOverrides bool `json:"allow_app_overrides" yaml:"allow_app_overrides"`

	// AutoPopulateTemplates creates default templates for new apps
	AutoPopulateTemplates bool `json:"auto_populate_templates" yaml:"auto_populate_templates"`

	// AllowTemplateReset enables template reset functionality
	AllowTemplateReset bool `json:"allow_template_reset" yaml:"allow_template_reset"`

	// AutoSendWelcome automatically sends welcome email on user signup
	// DEPRECATED: Use AutoSend.Auth.Welcome instead
	AutoSendWelcome bool `json:"auto_send_welcome" yaml:"auto_send_welcome"`

	// AutoSend configuration for automatic notification sending
	AutoSend AutoSendConfig `json:"auto_send" yaml:"auto_send"`

	// AppName is the default application name used in notifications
	// If empty, will use the App name from the database
	AppName string `json:"app_name" yaml:"app_name"`

	// RetryAttempts is the number of retry attempts for failed notifications
	RetryAttempts int `json:"retry_attempts" yaml:"retry_attempts"`

	// RetryDelay is the delay between retry attempts
	RetryDelay time.Duration `json:"retry_delay" yaml:"retry_delay"`

	// CleanupAfter is the duration after which old notifications are deleted
	CleanupAfter time.Duration `json:"cleanup_after" yaml:"cleanup_after"`

	// RateLimits defines rate limits for notification sending
	RateLimits map[string]RateLimit `json:"rate_limits" yaml:"rate_limits"`

	// Providers configuration for email and SMS
	Providers ProvidersConfig `json:"providers" yaml:"providers"`

	// Async configuration for notification processing
	Async AsyncConfig `json:"async" yaml:"async"`
}

Config holds the notification plugin configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type CreateTemplateInput added in v0.0.15

type CreateTemplateInput struct {
	TemplateKey string         `json:"templateKey"`
	Name        string         `json:"name"`
	Type        string         `json:"type"`
	Language    string         `json:"language,omitempty"`
	Subject     string         `json:"subject,omitempty"`
	Body        string         `json:"body"`
	Variables   []string       `json:"variables,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

CreateTemplateInput is the input for creating a template.

type CreateTemplateResult added in v0.0.15

type CreateTemplateResult struct {
	Success  bool        `json:"success"`
	Template TemplateDTO `json:"template"`
	Message  string      `json:"message,omitempty"`
}

CreateTemplateResult is the output for creating a template.

type DailyAnalyticsDTO added in v0.0.15

type DailyAnalyticsDTO struct {
	Date           string  `json:"date"`
	TotalSent      int64   `json:"totalSent"`
	TotalDelivered int64   `json:"totalDelivered"`
	TotalOpened    int64   `json:"totalOpened"`
	TotalClicked   int64   `json:"totalClicked"`
	DeliveryRate   float64 `json:"deliveryRate"`
	OpenRate       float64 `json:"openRate"`
}

DailyAnalyticsDTO represents analytics for a specific day.

type DashboardExtension

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

DashboardExtension provides dashboard UI for notifications.

func NewDashboardExtension

func NewDashboardExtension(plugin *Plugin) *DashboardExtension

NewDashboardExtension creates a new dashboard extension.

func (*DashboardExtension) BridgeFunctions added in v0.0.15

func (e *DashboardExtension) BridgeFunctions() []ui.BridgeFunction

BridgeFunctions returns bridge functions for the notification plugin.

func (*DashboardExtension) DashboardWidgets

func (e *DashboardExtension) DashboardWidgets() []ui.DashboardWidget

DashboardWidgets returns the notification stats widget.

func (*DashboardExtension) ExtensionID

func (e *DashboardExtension) ExtensionID() string

ExtensionID returns the extension ID.

func (*DashboardExtension) NavigationItems

func (e *DashboardExtension) NavigationItems() []ui.NavigationItem

NavigationItems returns the main "Notifications" navigation item.

func (*DashboardExtension) RenderDashboardWidget

func (e *DashboardExtension) RenderDashboardWidget(basePath string, currentApp *app.App) g.Node

RenderDashboardWidget renders the notification stats widget for the main dashboard.

func (*DashboardExtension) Routes

func (e *DashboardExtension) Routes() []ui.Route

Routes returns routes for the notification plugin.

func (*DashboardExtension) ServeAnalytics added in v0.0.15

func (e *DashboardExtension) ServeAnalytics(ctx *router.PageContext) (g.Node, error)

ServeAnalytics renders the analytics page.

func (*DashboardExtension) ServeEmailBuilder added in v0.0.3

func (e *DashboardExtension) ServeEmailBuilder(ctx *router.PageContext) (g.Node, error)

ServeEmailBuilder renders the email builder for new templates.

func (*DashboardExtension) ServeEmailBuilderWithTemplate added in v0.0.3

func (e *DashboardExtension) ServeEmailBuilderWithTemplate(ctx *router.PageContext) (g.Node, error)

ServeEmailBuilderWithTemplate renders the email builder with an existing template.

func (*DashboardExtension) ServeHistoryList added in v0.0.15

func (e *DashboardExtension) ServeHistoryList(ctx *router.PageContext) (g.Node, error)

ServeHistoryList renders the notification history list page.

func (*DashboardExtension) ServeOverview added in v0.0.15

func (e *DashboardExtension) ServeOverview(ctx *router.PageContext) (g.Node, error)

ServeOverview renders the notifications overview page.

func (*DashboardExtension) ServeProviders added in v0.0.15

func (e *DashboardExtension) ServeProviders(ctx *router.PageContext) (g.Node, error)

ServeProviders renders the providers settings page.

func (*DashboardExtension) ServeSettings added in v0.0.15

func (e *DashboardExtension) ServeSettings(ctx *router.PageContext) (g.Node, error)

ServeSettings renders the notification settings page.

func (*DashboardExtension) ServeTemplatesList

func (e *DashboardExtension) ServeTemplatesList(ctx *router.PageContext) (g.Node, error)

ServeTemplatesList renders the templates list page.

func (*DashboardExtension) SettingsPages

func (e *DashboardExtension) SettingsPages() []ui.SettingsPage

SettingsPages returns settings pages for the notification plugin.

func (*DashboardExtension) SettingsSections

func (e *DashboardExtension) SettingsSections() []ui.SettingsSection

SettingsSections returns empty settings sections for now.

type DeclareABTestWinnerRequest added in v0.0.7

type DeclareABTestWinnerRequest struct {
	TemplateID string `path:"templateId" validate:"required"`
}

type DeleteProviderRequest added in v0.0.7

type DeleteProviderRequest struct {
	ID string `path:"id" validate:"required"`
}

type DeleteTemplateInput added in v0.0.15

type DeleteTemplateInput struct {
	TemplateID string `json:"templateId"`
}

DeleteTemplateInput is the input for deleting a template.

type DeleteTemplateRequest added in v0.0.7

type DeleteTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

type DeleteTemplateResult added in v0.0.15

type DeleteTemplateResult struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

DeleteTemplateResult is the output for deleting a template.

type EmailProviderConfig

type EmailProviderConfig struct {
	Provider string         `json:"provider"  yaml:"provider"` // smtp, sendgrid, ses, etc.
	From     string         `json:"from"      yaml:"from"`
	FromName string         `json:"from_name" yaml:"from_name"`
	ReplyTo  string         `json:"reply_to"  yaml:"reply_to"`
	Config   map[string]any `json:"config"    yaml:"config"`
}

EmailProviderConfig holds email provider configuration.

type EmailProviderDTO added in v0.0.15

type EmailProviderDTO struct {
	Type      string         `json:"type"` // "smtp", "sendgrid", "postmark", "mailersend", "resend"
	Enabled   bool           `json:"enabled"`
	Config    map[string]any `json:"config,omitempty"`
	FromName  string         `json:"fromName"`
	FromEmail string         `json:"fromEmail"`
}

EmailProviderDTO represents email provider configuration.

type ErrorResponse

type ErrorResponse = responses.ErrorResponse

ErrorResponse types - use shared responses from core.

type GetABTestResultsRequest added in v0.0.7

type GetABTestResultsRequest struct {
	TemplateID string `path:"templateId" validate:"required"`
}

GetABTestResultsRequest Test DTOs.

type GetAnalyticsInput added in v0.0.15

type GetAnalyticsInput struct {
	Days       *int    `json:"days,omitempty"`
	StartDate  *string `json:"startDate,omitempty"`
	EndDate    *string `json:"endDate,omitempty"`
	TemplateID *string `json:"templateId,omitempty"`
}

GetAnalyticsInput is the input for getting analytics data.

type GetAnalyticsResult added in v0.0.15

type GetAnalyticsResult struct {
	Analytics AnalyticsDTO `json:"analytics"`
}

GetAnalyticsResult is the output for getting analytics data.

type GetNotificationDetailInput added in v0.0.15

type GetNotificationDetailInput struct {
	NotificationID string `json:"notificationId"`
}

GetNotificationDetailInput is the input for getting a single notification.

type GetNotificationDetailResult added in v0.0.15

type GetNotificationDetailResult struct {
	Notification NotificationHistoryDTO `json:"notification"`
}

GetNotificationDetailResult is the output for getting a single notification.

type GetNotificationRequest added in v0.0.7

type GetNotificationRequest struct {
	ID string `path:"id" validate:"required"`
}

GetNotificationRequest DTOs.

type GetOverviewStatsInput added in v0.0.15

type GetOverviewStatsInput struct {
	Days      *int    `json:"days,omitempty"`      // Number of days to fetch stats for
	StartDate *string `json:"startDate,omitempty"` // ISO date
	EndDate   *string `json:"endDate,omitempty"`   // ISO date
}

GetOverviewStatsInput is the input for getting overview statistics.

type GetOverviewStatsResult added in v0.0.15

type GetOverviewStatsResult struct {
	Stats OverviewStatsDTO `json:"stats"`
}

GetOverviewStatsResult is the output for getting overview statistics.

type GetProviderRequest added in v0.0.7

type GetProviderRequest struct {
	ID string `path:"id" validate:"required"`
}

GetProviderRequest DTOs.

type GetProvidersInput added in v0.0.15

type GetProvidersInput struct {
}

GetProvidersInput is the input for getting providers configuration.

type GetProvidersResult added in v0.0.15

type GetProvidersResult struct {
	Providers ProvidersConfigDTO `json:"providers"`
}

GetProvidersResult is the output for getting providers configuration.

type GetSettingsInput added in v0.0.15

type GetSettingsInput struct {
}

GetSettingsInput is the input for bridgeGetSettings.

type GetSettingsResult added in v0.0.15

type GetSettingsResult struct {
	Settings NotificationSettingsDTO `json:"settings"`
}

GetSettingsResult is the output for bridgeGetSettings.

type GetTemplateAnalyticsRequest added in v0.0.7

type GetTemplateAnalyticsRequest struct {
	TemplateID string `path:"templateId" validate:"required"`
}

GetTemplateAnalyticsRequest DTOs.

type GetTemplateInput added in v0.0.15

type GetTemplateInput struct {
	TemplateID string `json:"templateId"`
}

GetTemplateInput is the input for getting a single template.

type GetTemplateRequest added in v0.0.7

type GetTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

GetTemplateRequest DTOs.

type GetTemplateResult added in v0.0.15

type GetTemplateResult struct {
	Template TemplateDTO `json:"template"`
}

GetTemplateResult is the output for getting a single template.

type GetTemplateVersionRequest added in v0.0.7

type GetTemplateVersionRequest struct {
	TemplateID string `path:"templateId" validate:"required"`
	VersionID  string `path:"versionId"  validate:"required"`
}

GetTemplateVersionRequest Version DTOs.

type Handler

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

Handler handles notification HTTP requests.

func NewHandler

func NewHandler(service *notification.Service, templateSvc *TemplateService, config Config) *Handler

NewHandler creates a new notification handler.

func (*Handler) CreateABTestVariant

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

CreateABTestVariant creates a new A/B test variant.

func (*Handler) CreateProvider

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

CreateProvider creates a new notification provider.

func (*Handler) CreateTemplate

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

CreateTemplate creates a new notification template.

func (*Handler) CreateTemplateVersion

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

CreateTemplateVersion creates a new version for a template.

func (*Handler) DeclareABTestWinner

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

DeclareABTestWinner declares a winner for an A/B test.

func (*Handler) DeleteProvider

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

DeleteProvider deletes a provider.

func (*Handler) DeleteTemplate

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

DeleteTemplate deletes a template.

func (*Handler) GetABTestResults

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

GetABTestResults retrieves A/B test results for a test group.

func (*Handler) GetAppAnalytics

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

GetAppAnalytics retrieves analytics for an app.

func (*Handler) GetNotification

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

GetNotification retrieves a notification by ID.

func (*Handler) GetOrgAnalytics

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

GetOrgAnalytics retrieves analytics for an organization.

func (*Handler) GetProvider

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

GetProvider retrieves a provider by ID.

func (*Handler) GetTemplate

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

GetTemplate retrieves a template by ID.

func (*Handler) GetTemplateAnalytics

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

GetTemplateAnalytics retrieves analytics for a template.

func (*Handler) GetTemplateDefaults

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

GetTemplateDefaults returns default template metadata.

func (*Handler) GetTemplateVersion

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

GetTemplateVersion retrieves a specific template version.

func (*Handler) HandleWebhook

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

HandleWebhook handles provider webhook callbacks.

func (*Handler) ListNotifications

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

ListNotifications lists all notifications with pagination.

func (*Handler) ListProviders

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

ListProviders lists all providers for an app/org.

func (*Handler) ListTemplateVersions

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

ListTemplateVersions lists all versions for a template.

func (*Handler) ListTemplates

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

ListTemplates lists all templates with pagination.

func (*Handler) PreviewTemplate

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

PreviewTemplate renders a template with provided variables.

func (*Handler) RenderTemplate

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

RenderTemplate renders a template string with variables (no template ID required).

func (*Handler) ResendNotification

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

ResendNotification resends a notification.

func (*Handler) ResetAllTemplates

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

ResetAllTemplates resets all templates for an app to defaults.

func (*Handler) ResetTemplate

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

ResetTemplate resets a template to default values.

func (*Handler) RestoreTemplateVersion

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

RestoreTemplateVersion restores a template to a previous version.

func (*Handler) SendNotification

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

SendNotification sends a notification.

func (*Handler) TrackNotificationEvent

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

TrackNotificationEvent tracks an analytics event.

func (*Handler) UpdateProvider

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

UpdateProvider updates a provider's configuration.

func (*Handler) UpdateTemplate

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

UpdateTemplate updates a template.

type ListNotificationsHistoryInput added in v0.0.15

type ListNotificationsHistoryInput struct {
	Page      int     `json:"page,omitempty"`
	Limit     int     `json:"limit,omitempty"`
	Type      *string `json:"type,omitempty"`      // email, sms, push
	Status    *string `json:"status,omitempty"`    // pending, sent, failed, delivered, bounced
	Recipient *string `json:"recipient,omitempty"` // Filter by recipient
}

ListNotificationsHistoryInput is the input for listing notification history.

type ListNotificationsHistoryResult added in v0.0.15

type ListNotificationsHistoryResult struct {
	Notifications []NotificationHistoryDTO `json:"notifications"`
	Pagination    PaginationDTO            `json:"pagination"`
}

ListNotificationsHistoryResult is the output for listing notification history.

type ListTemplatesInput added in v0.0.15

type ListTemplatesInput struct {
	Page     int     `json:"page,omitempty"`
	Limit    int     `json:"limit,omitempty"`
	Type     *string `json:"type,omitempty"`
	Language *string `json:"language,omitempty"`
	Active   *bool   `json:"active,omitempty"`
}

ListTemplatesInput is the input for listing templates.

type ListTemplatesResult added in v0.0.15

type ListTemplatesResult struct {
	Templates  []TemplateDTO `json:"templates"`
	Pagination PaginationDTO `json:"pagination"`
}

ListTemplatesResult is the output for listing templates.

type MailerSendConfig

type MailerSendConfig = providers.MailerSendConfig

Re-export provider config types.

type MessageResponse

type MessageResponse = responses.MessageResponse

type NotificationErrorResponse

type NotificationErrorResponse struct {
	Error string `example:"Error message" json:"error"`
}

NotificationErrorResponse types for notification routes.

type NotificationHistoryDTO added in v0.0.15

type NotificationHistoryDTO struct {
	ID          string         `json:"id"`
	AppID       string         `json:"appId"`
	TemplateID  *string        `json:"templateId,omitempty"`
	Type        string         `json:"type"`
	Recipient   string         `json:"recipient"`
	Subject     string         `json:"subject,omitempty"`
	Body        string         `json:"body"`
	Status      string         `json:"status"`
	Error       string         `json:"error,omitempty"`
	ProviderID  string         `json:"providerId,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	SentAt      *string        `json:"sentAt,omitempty"`      // ISO 8601
	DeliveredAt *string        `json:"deliveredAt,omitempty"` // ISO 8601
	CreatedAt   string         `json:"createdAt"`             // ISO 8601
	UpdatedAt   string         `json:"updatedAt"`             // ISO 8601
}

NotificationHistoryDTO represents a notification record in the history.

type NotificationListResponse

type NotificationListResponse struct {
	Notifications []any `json:"notifications"`
	Total         int   `example:"50"         json:"total"`
}

type NotificationPreviewResponse

type NotificationPreviewResponse struct {
	Subject string `example:"Welcome to AuthSome"                  json:"subject"`
	Body    string `example:"Hello {{name}}, welcome to AuthSome!" json:"body"`
}

type NotificationResponse

type NotificationResponse struct {
	Notification any `json:"notification"`
}

type NotificationSettingsDTO added in v0.0.15

type NotificationSettingsDTO struct {
	AppName      string                  `json:"appName"`
	Auth         AuthAutoSendDTO         `json:"auth"`
	Organization OrganizationAutoSendDTO `json:"organization"`
	Session      SessionAutoSendDTO      `json:"session"`
	Account      AccountAutoSendDTO      `json:"account"`
}

NotificationSettingsDTO represents notification plugin settings.

type NotificationStatusResponse

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

type NotificationTemplateListResponse

type NotificationTemplateListResponse struct {
	Templates []any `json:"templates"`
	Total     int   `example:"10"     json:"total"`
}

type NotificationTemplateResponse

type NotificationTemplateResponse struct {
	Template any `json:"template"`
}

type NotificationWebhookResponse

type NotificationWebhookResponse struct {
	Status string `example:"processed" json:"status"`
}

type NotificationsResponse

type NotificationsResponse struct {
	Notifications any `json:"notifications"`
	Count         int `json:"count"`
}

type OrganizationAutoSendConfig added in v0.0.6

type OrganizationAutoSendConfig struct {
	Invite        bool `json:"invite"         yaml:"invite"`
	MemberAdded   bool `json:"member_added"   yaml:"member_added"`
	MemberRemoved bool `json:"member_removed" yaml:"member_removed"`
	RoleChanged   bool `json:"role_changed"   yaml:"role_changed"`
	Transfer      bool `json:"transfer"       yaml:"transfer"`
	Deleted       bool `json:"deleted"        yaml:"deleted"`
	MemberLeft    bool `json:"member_left"    yaml:"member_left"`
}

OrganizationAutoSendConfig controls organization-related notifications.

type OrganizationAutoSendDTO added in v0.0.15

type OrganizationAutoSendDTO struct {
	Invite        bool `json:"invite"`
	MemberAdded   bool `json:"memberAdded"`
	MemberRemoved bool `json:"memberRemoved"`
	RoleChanged   bool `json:"roleChanged"`
	Transfer      bool `json:"transfer"`
	Deleted       bool `json:"deleted"`
	MemberLeft    bool `json:"memberLeft"`
}

OrganizationAutoSendDTO represents organization notification settings.

type OverviewStatsDTO added in v0.0.15

type OverviewStatsDTO struct {
	TotalSent      int64   `json:"totalSent"`
	TotalDelivered int64   `json:"totalDelivered"`
	TotalOpened    int64   `json:"totalOpened"`
	TotalClicked   int64   `json:"totalClicked"`
	TotalBounced   int64   `json:"totalBounced"`
	TotalFailed    int64   `json:"totalFailed"`
	DeliveryRate   float64 `json:"deliveryRate"`
	OpenRate       float64 `json:"openRate"`
	ClickRate      float64 `json:"clickRate"`
	BounceRate     float64 `json:"bounceRate"`
}

OverviewStatsDTO represents overview statistics.

type PaginationDTO added in v0.0.15

type PaginationDTO struct {
	CurrentPage int   `json:"currentPage"`
	TotalPages  int   `json:"totalPages"`
	TotalCount  int64 `json:"totalCount"`
	PageSize    int   `json:"pageSize"`
	HasNext     bool  `json:"hasNext"`
	HasPrev     bool  `json:"hasPrev"`
}

PaginationDTO represents pagination metadata.

type Plugin

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

Plugin implements the notification template management plugin.

func NewPlugin

func NewPlugin(opts ...PluginOption) *Plugin

NewPlugin creates a new notification plugin instance with optional configuration.

func (*Plugin) DashboardExtension

func (p *Plugin) DashboardExtension() ui.DashboardExtension

DashboardExtension returns the dashboard extension interface implementation.

func (*Plugin) GetService

func (p *Plugin) GetService() *notification.Service

GetService returns the notification service for use by other plugins.

func (*Plugin) GetTemplateService

func (p *Plugin) GetTemplateService() *TemplateService

GetTemplateService returns the template service for use by other plugins.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the plugin identifier.

func (*Plugin) Init

func (p *Plugin) Init(authInst core.Authsome) error

Init initializes the plugin with dependencies.

func (*Plugin) Migrate

func (p *Plugin) Migrate() error

Migrate runs database migrations.

func (*Plugin) RegisterHooks

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

RegisterHooks registers plugin hooks.

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 registers the notification service and adapter.

func (*Plugin) Stop added in v0.0.7

func (p *Plugin) Stop()

Stop gracefully stops the plugin's background services.

type PluginOption

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring the notification plugin.

func WithAddDefaultTemplates

func WithAddDefaultTemplates(add bool) PluginOption

WithAddDefaultTemplates sets whether to add default templates.

func WithAllowAppOverrides

func WithAllowAppOverrides(allow bool) PluginOption

WithAllowAppOverrides sets whether to allow organization overrides.

func WithAutoSendWelcome

func WithAutoSendWelcome(auto bool) PluginOption

WithAutoSendWelcome sets whether to auto-send welcome emails.

func WithDefaultConfig

func WithDefaultConfig(cfg Config) PluginOption

WithDefaultConfig sets the default configuration for the plugin.

func WithDefaultLanguage

func WithDefaultLanguage(lang string) PluginOption

WithDefaultLanguage sets the default language.

func WithEmailProvider

func WithEmailProvider(provider, from, fromName string) PluginOption

WithEmailProvider sets the email provider configuration.

func WithRetryConfig

func WithRetryConfig(attempts int, delay time.Duration) PluginOption

WithRetryConfig sets the retry configuration.

func WithSMSProvider

func WithSMSProvider(provider, from string) PluginOption

WithSMSProvider sets the SMS provider configuration.

type PostmarkConfig

type PostmarkConfig = providers.PostmarkConfig

Re-export provider config types.

type PreviewTemplateInput added in v0.0.15

type PreviewTemplateInput struct {
	TemplateID string         `json:"templateId"`
	Variables  map[string]any `json:"variables,omitempty"`
}

PreviewTemplateInput is the input for previewing a template.

type PreviewTemplateRequest added in v0.0.7

type PreviewTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

type PreviewTemplateResult added in v0.0.15

type PreviewTemplateResult struct {
	Subject    string `json:"subject"`
	Body       string `json:"body"`
	RenderedAt string `json:"renderedAt"`
}

PreviewTemplateResult is the output for previewing a template.

type ProvidersConfig

type ProvidersConfig struct {
	Email EmailProviderConfig `json:"email"         yaml:"email"`
	SMS   *SMSProviderConfig  `json:"sms,omitempty" yaml:"sms,omitempty"` // Optional SMS provider
}

ProvidersConfig holds provider configurations.

type ProvidersConfigDTO added in v0.0.15

type ProvidersConfigDTO struct {
	EmailProvider EmailProviderDTO `json:"emailProvider"`
	SMSProvider   SMSProviderDTO   `json:"smsProvider"`
}

ProvidersConfigDTO represents providers configuration.

type RateLimit

type RateLimit struct {
	MaxRequests int           `json:"max_requests" yaml:"max_requests"`
	Window      time.Duration `json:"window"       yaml:"window"`
}

RateLimit defines rate limiting configuration.

type RenderTemplateRequest added in v0.0.7

type RenderTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

type ResendConfig

type ResendConfig = providers.ResendConfig

Re-export provider config types.

type ResendNotificationRequest added in v0.0.7

type ResendNotificationRequest struct {
	ID string `path:"id" validate:"required"`
}

type ResetTemplateRequest added in v0.0.7

type ResetTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

type RestoreTemplateVersionRequest added in v0.0.7

type RestoreTemplateVersionRequest struct {
	TemplateID string `path:"templateId" validate:"required"`
	VersionID  string `path:"versionId"  validate:"required"`
}

type SMSProviderConfig

type SMSProviderConfig struct {
	Provider string         `json:"provider" yaml:"provider"` // twilio, vonage, aws-sns, etc.
	From     string         `json:"from"     yaml:"from"`
	Config   map[string]any `json:"config"   yaml:"config"`
}

SMSProviderConfig holds SMS provider configuration.

type SMSProviderDTO added in v0.0.15

type SMSProviderDTO struct {
	Type    string         `json:"type"` // "twilio", "vonage", "aws-sns"
	Enabled bool           `json:"enabled"`
	Config  map[string]any `json:"config,omitempty"`
}

SMSProviderDTO represents SMS provider configuration.

type SaveBuilderTemplateInput added in v0.0.15

type SaveBuilderTemplateInput struct {
	TemplateID  string `json:"templateId,omitempty"` // Empty for new template
	Name        string `json:"name"`
	TemplateKey string `json:"templateKey"`
	Subject     string `json:"subject"`
	BuilderJSON string `json:"builderJson"` // JSON of builder.Document
}

SaveBuilderTemplateInput is the input for saving a template from the visual builder.

type SaveBuilderTemplateResult added in v0.0.15

type SaveBuilderTemplateResult struct {
	Success    bool   `json:"success"`
	TemplateID string `json:"templateId,omitempty"`
	Message    string `json:"message"`
}

SaveBuilderTemplateResult is the output for saving a builder template.

type SendWithTemplateRequest

type SendWithTemplateRequest struct {
	AppID       xid.ID                        `json:"appId"`
	TemplateKey string                        `json:"templateKey"`
	Type        notification.NotificationType `json:"type"`
	Recipient   string                        `json:"recipient"`
	Variables   map[string]any                `json:"variables"`
	Language    string                        `json:"language,omitempty"`
	Metadata    map[string]any                `json:"metadata,omitempty"`
}

SendWithTemplateRequest represents a request to send a notification using a template.

type SessionAutoSendConfig added in v0.0.6

type SessionAutoSendConfig struct {
	NewDevice       bool `json:"new_device"       yaml:"new_device"`
	NewLocation     bool `json:"new_location"     yaml:"new_location"`
	SuspiciousLogin bool `json:"suspicious_login" yaml:"suspicious_login"`
	DeviceRemoved   bool `json:"device_removed"   yaml:"device_removed"`
	AllRevoked      bool `json:"all_revoked"      yaml:"all_revoked"`
}

SessionAutoSendConfig controls session/device security notifications.

type SessionAutoSendDTO added in v0.0.15

type SessionAutoSendDTO struct {
	NewDevice       bool `json:"newDevice"`
	NewLocation     bool `json:"newLocation"`
	SuspiciousLogin bool `json:"suspiciousLogin"`
	DeviceRemoved   bool `json:"deviceRemoved"`
	AllRevoked      bool `json:"allRevoked"`
}

SessionAutoSendDTO represents session/security notification settings.

type StatusResponse

type StatusResponse = responses.StatusResponse

type SuccessResponse

type SuccessResponse = responses.SuccessResponse

type TemplateAnalyticsDTO added in v0.0.15

type TemplateAnalyticsDTO struct {
	TemplateID     string  `json:"templateId"`
	TemplateName   string  `json:"templateName"`
	TotalSent      int64   `json:"totalSent"`
	TotalDelivered int64   `json:"totalDelivered"`
	TotalOpened    int64   `json:"totalOpened"`
	TotalClicked   int64   `json:"totalClicked"`
	DeliveryRate   float64 `json:"deliveryRate"`
	OpenRate       float64 `json:"openRate"`
	ClickRate      float64 `json:"clickRate"`
}

TemplateAnalyticsDTO represents analytics for a specific template.

type TemplateDTO added in v0.0.15

type TemplateDTO struct {
	ID          string         `json:"id"`
	AppID       string         `json:"appId"`
	TemplateKey string         `json:"templateKey"`
	Name        string         `json:"name"`
	Type        string         `json:"type"`
	Language    string         `json:"language"`
	Subject     string         `json:"subject,omitempty"`
	Body        string         `json:"body"`
	Variables   []string       `json:"variables"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	Active      bool           `json:"active"`
	IsDefault   bool           `json:"isDefault"`
	IsModified  bool           `json:"isModified"`
	CreatedAt   string         `json:"createdAt"`
	UpdatedAt   string         `json:"updatedAt"`
}

TemplateDTO represents a notification template.

type TemplateDefault

type TemplateDefault struct {
	TemplateKey string
	Type        string
	Subject     string
	BodyText    string
	BodyHTML    string
	Variables   []string
	Description string
}

TemplateDefault represents a default template.

func DefaultTemplates

func DefaultTemplates() []TemplateDefault

DefaultTemplates returns the default notification templates.

type TemplateEngine

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

TemplateEngine provides template rendering functionality.

func NewTemplateEngine

func NewTemplateEngine() *TemplateEngine

NewTemplateEngine creates a new template engine.

func (*TemplateEngine) ExtractVariables

func (e *TemplateEngine) ExtractVariables(templateStr string) ([]string, error)

ExtractVariables extracts variable names from a template.

func (*TemplateEngine) Render

func (e *TemplateEngine) Render(templateStr string, variables map[string]any) (string, error)

Render renders a template with the given variables.

func (*TemplateEngine) ValidateTemplate

func (e *TemplateEngine) ValidateTemplate(templateStr string) error

ValidateTemplate validates a template for syntax errors.

type TemplatePerformanceDTO added in v0.0.15

type TemplatePerformanceDTO struct {
	TemplateID   string  `json:"templateId"`
	TemplateName string  `json:"templateName"`
	TotalSent    int64   `json:"totalSent"`
	OpenRate     float64 `json:"openRate"`
	ClickRate    float64 `json:"clickRate"`
}

TemplatePerformanceDTO represents template performance ranking.

type TemplateService

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

TemplateService provides template-aware notification functionality.

func NewTemplateService

func NewTemplateService(
	notificationSvc *notification.Service,
	repo notification.Repository,
	config Config,
) *TemplateService

NewTemplateService creates a new template service.

func (*TemplateService) RenderTemplate

func (s *TemplateService) RenderTemplate(ctx context.Context, templateID xid.ID, variables map[string]any) (subject, body string, err error)

RenderTemplate renders a template with variables without sending.

func (*TemplateService) SendDirect

func (s *TemplateService) SendDirect(ctx context.Context, appID xid.ID, notifType notification.NotificationType, recipient, subject, body string, metadata map[string]any) (*notification.Notification, error)

SendDirect sends a notification without using a template.

func (*TemplateService) SendEmail

func (s *TemplateService) SendEmail(ctx context.Context, appID xid.ID, templateKey, to string, variables map[string]any) error

SendEmail sends an email notification.

func (*TemplateService) SendSMS

func (s *TemplateService) SendSMS(ctx context.Context, appID xid.ID, templateKey, to string, variables map[string]any) error

SendSMS sends an SMS notification.

func (*TemplateService) SendWithTemplate

SendWithTemplate sends a notification using a template.

type TemplatesResponse

type TemplatesResponse struct {
	Templates any `json:"templates"`
	Count     int `json:"count"`
}

type TestProviderInput added in v0.0.15

type TestProviderInput struct {
	ProviderType string `json:"providerType"` // "email" or "sms"
	Recipient    string `json:"recipient"`
}

TestProviderInput is the input for testing a provider.

type TestProviderResult added in v0.0.15

type TestProviderResult struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

TestProviderResult is the output for testing a provider.

type TestSendTemplateInput added in v0.0.15

type TestSendTemplateInput struct {
	TemplateID string         `json:"templateId"`
	Recipient  string         `json:"recipient"`
	Variables  map[string]any `json:"variables,omitempty"`
}

TestSendTemplateInput is the input for test sending a template.

type TestSendTemplateResult added in v0.0.15

type TestSendTemplateResult struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

TestSendTemplateResult is the output for test sending a template.

type UpdateProviderRequest added in v0.0.7

type UpdateProviderRequest struct {
	ID string `path:"id" validate:"required"`
}

type UpdateProvidersInput added in v0.0.15

type UpdateProvidersInput struct {
	EmailProvider *EmailProviderDTO `json:"emailProvider,omitempty"`
	SMSProvider   *SMSProviderDTO   `json:"smsProvider,omitempty"`
}

UpdateProvidersInput is the input for updating providers configuration.

type UpdateProvidersResult added in v0.0.15

type UpdateProvidersResult struct {
	Success   bool               `json:"success"`
	Providers ProvidersConfigDTO `json:"providers"`
	Message   string             `json:"message,omitempty"`
}

UpdateProvidersResult is the output for updating providers configuration.

type UpdateSettingsInput added in v0.0.15

type UpdateSettingsInput struct {
	AppName      string                   `json:"appName,omitempty"`
	Auth         *AuthAutoSendDTO         `json:"auth,omitempty"`
	Organization *OrganizationAutoSendDTO `json:"organization,omitempty"`
	Session      *SessionAutoSendDTO      `json:"session,omitempty"`
	Account      *AccountAutoSendDTO      `json:"account,omitempty"`
}

UpdateSettingsInput is the input for bridgeUpdateSettings.

type UpdateSettingsResult added in v0.0.15

type UpdateSettingsResult struct {
	Success  bool                    `json:"success"`
	Settings NotificationSettingsDTO `json:"settings"`
	Message  string                  `json:"message,omitempty"`
}

UpdateSettingsResult is the output for bridgeUpdateSettings.

type UpdateTemplateInput added in v0.0.15

type UpdateTemplateInput struct {
	TemplateID string         `json:"templateId"`
	Name       *string        `json:"name,omitempty"`
	Subject    *string        `json:"subject,omitempty"`
	Body       *string        `json:"body,omitempty"`
	Variables  []string       `json:"variables,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	Active     *bool          `json:"active,omitempty"`
}

UpdateTemplateInput is the input for updating a template.

type UpdateTemplateRequest added in v0.0.7

type UpdateTemplateRequest struct {
	ID string `path:"id" validate:"required"`
}

type UpdateTemplateResult added in v0.0.15

type UpdateTemplateResult struct {
	Success  bool        `json:"success"`
	Template TemplateDTO `json:"template"`
	Message  string      `json:"message,omitempty"`
}

UpdateTemplateResult is the output for updating a template.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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