notification

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 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 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) 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) 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) 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) 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) 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

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
	AutoSendWelcome bool `json:"auto_send_welcome" yaml:"auto_send_welcome"`

	// 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"`
}

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) 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 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 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 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 TODO: Implement when service registry is available

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 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 ResendConfig

type ResendConfig = providers.ResendConfig

Re-export provider config types

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 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"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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