notification

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 35 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 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]interface{}) 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 interface{}) *Adapter

WithAppService sets the app service for dynamic app name lookup

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 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 interface{} `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 DashboardExtension

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

DashboardExtension implements the ui.DashboardExtension interface This allows the notification plugin to add its own screens to the dashboard

func NewDashboardExtension

func NewDashboardExtension(plugin *Plugin) *DashboardExtension

NewDashboardExtension creates a new dashboard extension for notification plugin

func (*DashboardExtension) DashboardWidgets

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

DashboardWidgets returns widgets to show on the main dashboard

func (*DashboardExtension) ExtensionID

func (e *DashboardExtension) ExtensionID() string

ExtensionID returns the unique identifier for this extension

func (*DashboardExtension) GetSampleTemplate added in v0.0.3

func (e *DashboardExtension) GetSampleTemplate(c forge.Context) error

GetSampleTemplate returns a sample template by name

func (*DashboardExtension) HandleUpdateSettings added in v0.0.6

func (e *DashboardExtension) HandleUpdateSettings(c forge.Context) error

HandleUpdateSettings handles the settings update POST request

func (*DashboardExtension) NavigationItems

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

NavigationItems returns navigation items to register

func (*DashboardExtension) PreviewBuilderTemplate added in v0.0.3

func (e *DashboardExtension) PreviewBuilderTemplate(c forge.Context) error

PreviewBuilderTemplate generates HTML preview from builder JSON

func (*DashboardExtension) PreviewTemplate

func (e *DashboardExtension) PreviewTemplate(c forge.Context) error

PreviewTemplate handles template preview requests

func (*DashboardExtension) RenderDashboardWidget

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

RenderDashboardWidget renders the notification stats widget

func (*DashboardExtension) Routes

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

Routes returns routes to register under /dashboard/app/:appId/

func (*DashboardExtension) SaveBuilderTemplate added in v0.0.3

func (e *DashboardExtension) SaveBuilderTemplate(c forge.Context) error

SaveBuilderTemplate saves a template created with the visual builder

func (*DashboardExtension) SaveNotificationSettings

func (e *DashboardExtension) SaveNotificationSettings(c forge.Context) error

SaveNotificationSettings handles saving notification settings

func (*DashboardExtension) ServeAnalyticsSettings

func (e *DashboardExtension) ServeAnalyticsSettings(c forge.Context) error

ServeAnalyticsSettings renders the analytics page

func (*DashboardExtension) ServeCreateTemplate

func (e *DashboardExtension) ServeCreateTemplate(c forge.Context) error

ServeCreateTemplate renders the create template page

func (*DashboardExtension) ServeEditTemplate

func (e *DashboardExtension) ServeEditTemplate(c forge.Context) error

ServeEditTemplate renders the edit template page

func (*DashboardExtension) ServeEmailBuilder added in v0.0.3

func (e *DashboardExtension) ServeEmailBuilder(c forge.Context) error

ServeEmailBuilder serves the visual email template builder page

func (*DashboardExtension) ServeEmailBuilderWithTemplate added in v0.0.3

func (e *DashboardExtension) ServeEmailBuilderWithTemplate(c forge.Context) error

ServeEmailBuilderWithTemplate serves the builder with an existing template

func (*DashboardExtension) ServeNotificationSettings

func (e *DashboardExtension) ServeNotificationSettings(c forge.Context) error

ServeNotificationSettings renders the notification settings page

func (*DashboardExtension) ServeNotificationsOverview

func (e *DashboardExtension) ServeNotificationsOverview(c forge.Context) error

ServeNotificationsOverview renders the notifications overview page

func (*DashboardExtension) ServeProviderSettings

func (e *DashboardExtension) ServeProviderSettings(c forge.Context) error

ServeProviderSettings renders the provider settings page

func (*DashboardExtension) ServeTemplatesList

func (e *DashboardExtension) ServeTemplatesList(c forge.Context) error

ServeTemplatesList renders the templates list page

func (*DashboardExtension) SetRegistry

func (e *DashboardExtension) SetRegistry(registry *dashboard.ExtensionRegistry)

SetRegistry sets the extension registry reference (called by dashboard after registration)

func (*DashboardExtension) SettingsPages

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

SettingsPages returns full settings pages for the sidebar layout

func (*DashboardExtension) SettingsSections

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

SettingsSections returns settings sections for backward compatibility Deprecated: Use SettingsPages() instead

func (*DashboardExtension) TestProvider

func (e *DashboardExtension) TestProvider(c forge.Context) error

TestProvider handles provider test requests by actually sending a test notification

func (*DashboardExtension) TestSendTemplate

func (e *DashboardExtension) TestSendTemplate(c forge.Context) error

TestSendTemplate handles test send requests

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 DeleteTemplateRequest added in v0.0.7

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

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]interface{} `json:"config" yaml:"config"`
}

EmailProviderConfig holds email provider configuration

type ErrorResponse

type ErrorResponse = responses.ErrorResponse

Response types - use shared responses from core

type GetABTestResultsRequest added in v0.0.7

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

AB Test DTOs

type GetNotificationRequest added in v0.0.7

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

Notification DTOs

type GetProviderRequest added in v0.0.7

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

Provider DTOs

type GetTemplateAnalyticsRequest added in v0.0.7

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

Analytics DTOs

type GetTemplateRequest added in v0.0.7

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

Template DTOs

type GetTemplateVersionRequest added in v0.0.7

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

Template 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 MailerSendConfig

type MailerSendConfig = providers.MailerSendConfig

Re-export provider config types

type MessageResponse

type MessageResponse = responses.MessageResponse

type NotificationErrorResponse

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

Response types for notification routes

type NotificationListResponse

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

type NotificationPreviewResponse

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

type NotificationResponse

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

type NotificationStatusResponse

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

type NotificationTemplateListResponse

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

type NotificationTemplateResponse

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

type NotificationWebhookResponse

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

type NotificationsResponse

type NotificationsResponse struct {
	Notifications interface{} `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 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

WithAllowOrgOverrides 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 PreviewTemplateRequest added in v0.0.7

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

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 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]interface{} `json:"config" yaml:"config"`
}

SMSProviderConfig holds SMS provider configuration

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]interface{}        `json:"variables"`
	Language    string                        `json:"language,omitempty"`
	Metadata    map[string]interface{}        `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 StatusResponse

type StatusResponse = responses.StatusResponse

type SuccessResponse

type SuccessResponse = responses.SuccessResponse

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]interface{}) (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 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]interface{}) (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]interface{}) (*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]interface{}) 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]interface{}) error

SendSMS sends an SMS notification

func (*TemplateService) SendWithTemplate

SendWithTemplate sends a notification using a template

type TemplatesResponse

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

type UpdateProviderRequest added in v0.0.7

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

type UpdateTemplateRequest added in v0.0.7

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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