Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat: add platform notifications (daily reports, invitations, etc.)

Jonas Kaninda15a5776a6a24
diff --git a/.env.example b/.env.example
index 7bab4a5..2483bf5 100644
--- a/.env.example
+++ b/.env.example
@@ -85,4 +85,14 @@ POSTA_OAUTH_CALLBACK_URL=https://posta.example.com
# Encryption key for SMTP server passwords (AES-256-GCM)
# If empty, passwords are stored with base64 encoding only
-# POSTA_ENCRYPTION_KEY=
\ No newline at end of file
+# POSTA_ENCRYPTION_KEY=
+
+# System SMTP server used for platform notifications (daily reports, invitations, etc.)
+# Required: Host and From must be set for SMTP to be active
+POSTA_SYSTEM_SMTP_HOST=smtp.example.com
+POSTA_SYSTEM_SMTP_PORT=587
+POSTA_SYSTEM_SMTP_PASSWORD=secret
+# Encryption mode: none, ssl, starttls
+POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
\ No newline at end of file
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index ea69041..1647c43 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -27,6 +27,7 @@ import (
"github.com/goposta/posta/internal/metrics"
"github.com/goposta/posta/internal/routes"
"github.com/goposta/posta/internal/services/crypto"
+ "github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/retry"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
@@ -99,16 +100,31 @@ func runServer(cli *okapicli.CLI) {
logger.Info("blob storage initialized", "provider", cfg.BlobProvider)
}
+ // Notification service
+ userRepo := repositories.NewUserRepository(res.db)
+ userSettingRepo := repositories.NewUserSettingRepository(res.db)
+ appName := "Posta"
+ notifier := notification.NewService(cfg.SystemSMTP, appName, cfg.AppWebURL, userRepo, userSettingRepo)
+ if notifier.IsConfigured() {
+ logger.Info("system notification service enabled")
+ }
+
if cfg.EmbeddedWorker && !cfg.DevMode {
res.producer = worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
- startEmbeddedWorker(res.db, cfg, res.blobStore)
+ startEmbeddedWorker(res.db, cfg, res.blobStore, notifier)
}
if !cfg.DevMode {
- res.cronManager = initCronManager(res.db, cfg)
+ res.cronManager = initCronManager(res.db, cfg, notifier)
}
- routes.InitRoutes(app, res.db, res.redis, cfg, res.producer, res.cronManager, res.blobStore, context.Background())
+ routes.InitRoutes(app, res.db,
+ res.redis,
+ cfg,
+ res.producer,
+ res.cronManager,
+ res.blobStore,
+ context.Background(), notifier)
if res.cronManager != nil {
res.cronManager.Start(context.Background())
@@ -164,7 +180,7 @@ func newWebhookDispatcher(db *gorm.DB, cfg *config.Config) *webhook.Dispatcher {
}
// startEmbeddedWorker starts an in-process asynq worker for email delivery.
-func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store) {
+func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store, notifier *notification.Service) {
dispatcher := newWebhookDispatcher(db, cfg)
handler := worker.NewEmailSendHandler(
@@ -218,10 +234,18 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store)
campaignDispatcher,
)
+ // Daily report handler
+ dailyReportHandler := worker.NewDailyReportHandler(
+ notifier,
+ repositories.NewAnalyticsRepository(db),
+ repositories.NewBounceRepository(db),
+ )
+
mux := asynq.NewServeMux()
mux.HandleFunc(worker.TypeEmailSend, handler.ProcessTask)
mux.HandleFunc(worker.TypeCampaignStart, campaignProcessor.HandleCampaignStart)
mux.HandleFunc(worker.TypeCampaignBatch, campaignProcessor.HandleCampaignBatch)
+ mux.HandleFunc(jobs.TypeDailyReport, dailyReportHandler.ProcessTask)
go func() {
if err := srv.Run(mux); err != nil {
@@ -233,7 +257,7 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store)
}
// initCronManager creates and registers scheduled jobs.
-func initCronManager(db *gorm.DB, cfg *config.Config) *cronpkg.Manager {
+func initCronManager(db *gorm.DB, cfg *config.Config, notifier *notification.Service) *cronpkg.Manager {
cronClient := asynq.NewClient(asynq.RedisClientOpt{
Addr: cfg.Redis.Addr,
Password: cfg.Redis.Password,
@@ -250,6 +274,12 @@ func initCronManager(db *gorm.DB, cfg *config.Config) *cronpkg.Manager {
))
manager.Register(jobs.NewDailyReportJob(repositories.NewUserSettingRepository(db)))
manager.Register(jobs.NewAccountCleanupJob(repositories.NewUserRepository(db)))
+ manager.Register(jobs.NewAPIKeyExpiryJob(db, notifier))
+ manager.Register(jobs.NewBounceAlertJob(
+ db, notifier,
+ repositories.NewBounceRepository(db),
+ repositories.NewSuppressionRepository(db),
+ ))
return manager
}
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 6cc60a0..264df01 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -19,8 +19,10 @@ package main
import (
"github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/cron/jobs"
"github.com/goposta/posta/internal/metrics"
"github.com/goposta/posta/internal/services/crypto"
+ "github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/tracking"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
@@ -118,10 +120,23 @@ func runWorker() error {
campaignDispatcher,
)
+ // Notification service + daily report handler
+ notifier := notification.NewService(
+ cfg.SystemSMTP, "Posta", cfg.AppWebURL,
+ repositories.NewUserRepository(db),
+ repositories.NewUserSettingRepository(db),
+ )
+ dailyReportHandler := worker.NewDailyReportHandler(
+ notifier,
+ repositories.NewAnalyticsRepository(db),
+ repositories.NewBounceRepository(db),
+ )
+
mux := asynq.NewServeMux()
mux.HandleFunc(worker.TypeEmailSend, handler.ProcessTask)
mux.HandleFunc(worker.TypeCampaignStart, campaignProcessor.HandleCampaignStart)
mux.HandleFunc(worker.TypeCampaignBatch, campaignProcessor.HandleCampaignBatch)
+ mux.HandleFunc(jobs.TypeDailyReport, dailyReportHandler.ProcessTask)
logger.Info("Posta worker started",
"version", config.Version,
diff --git a/examples/.env.example b/examples/.env.example
index 7bab4a5..2483bf5 100644
--- a/examples/.env.example
+++ b/examples/.env.example
@@ -85,4 +85,14 @@ POSTA_OAUTH_CALLBACK_URL=https://posta.example.com
# Encryption key for SMTP server passwords (AES-256-GCM)
# If empty, passwords are stored with base64 encoding only
-# POSTA_ENCRYPTION_KEY=
\ No newline at end of file
+# POSTA_ENCRYPTION_KEY=
+
+# System SMTP server used for platform notifications (daily reports, invitations, etc.)
+# Required: Host and From must be set for SMTP to be active
+POSTA_SYSTEM_SMTP_HOST=smtp.example.com
+POSTA_SYSTEM_SMTP_PORT=587
+POSTA_SYSTEM_SMTP_PASSWORD=secret
+# Encryption mode: none, ssl, starttls
+POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
\ No newline at end of file
diff --git a/internal/config/config.go b/internal/config/config.go
index 45f4008..9c383ea 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -65,6 +65,9 @@ type Config struct {
GoogleOAuthClientSecret string
OAuthCallbackBaseURL string
+ // System SMTP for platform notifications (daily reports, invitations, etc.)
+ SystemSMTP SystemSMTPConfig
+
// Encryption key for SMTP password encryption (if empty, base64 encoding is used)
EncryptionKey string
@@ -79,6 +82,19 @@ type Config struct {
BlobS3PathStyle bool
BlobFSPath string
}
+type SystemSMTPConfig struct {
+ Host string
+ Port int
+ Username string
+ Password string
+ From string
+ Encryption string // none, ssl, starttls
+}
+
+func (s SystemSMTPConfig) IsConfigured() bool {
+ return s.Host != "" && s.From != ""
+}
+
type DatabaseConfig struct {
DB *gorm.DB
host string
@@ -151,6 +167,15 @@ func New() *Config {
GoogleOAuthClientSecret: goutils.Env("POSTA_GOOGLE_OAUTH_CLIENT_SECRET", ""),
OAuthCallbackBaseURL: goutils.Env("POSTA_OAUTH_CALLBACK_URL", ""),
+ SystemSMTP: SystemSMTPConfig{
+ Host: goutils.Env("POSTA_SYSTEM_SMTP_HOST", ""),
+ Port: goutils.EnvInt("POSTA_SYSTEM_SMTP_PORT", 587),
+ Username: goutils.Env("POSTA_SYSTEM_SMTP_USERNAME", ""),
+ Password: goutils.Env("POSTA_SYSTEM_SMTP_PASSWORD", ""),
+ From: goutils.Env("POSTA_SYSTEM_SMTP_FROM", ""),
+ Encryption: goutils.Env("POSTA_SYSTEM_SMTP_ENCRYPTION", "starttls"),
+ },
+
EncryptionKey: goutils.Env("POSTA_ENCRYPTION_KEY", ""),
BlobProvider: goutils.Env("POSTA_BLOB_PROVIDER", ""),
diff --git a/internal/cron/jobs/api_key_expiry.go b/internal/cron/jobs/api_key_expiry.go
new file mode 100644
index 0000000..7ec6cd3
--- /dev/null
+++ b/internal/cron/jobs/api_key_expiry.go
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package jobs
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// APIKeyExpiryJob checks for API keys expiring within 7 days and notifies users.
+type APIKeyExpiryJob struct {
+ db *gorm.DB
+ notifier *notification.Service
+}
+
+func NewAPIKeyExpiryJob(db *gorm.DB, notifier *notification.Service) *APIKeyExpiryJob {
+ return &APIKeyExpiryJob{db: db, notifier: notifier}
+}
+
+func (j *APIKeyExpiryJob) Name() string { return "api-key-expiry" }
+func (j *APIKeyExpiryJob) Schedule() string { return "0 8 * * *" } // daily at 08:00 UTC
+
+type expiringKey struct {
+ Name string
+ ExpiresAt string
+}
+
+func (j *APIKeyExpiryJob) Run(_ context.Context, _ *asynq.Client) error {
+ if j.notifier == nil || !j.notifier.IsConfigured() {
+ return nil
+ }
+
+ // Find API keys expiring within the next 7 days
+ now := time.Now().UTC()
+ deadline := now.AddDate(0, 0, 7)
+
+ var keys []models.APIKey
+ if err := j.db.Where("expires_at IS NOT NULL AND expires_at > ? AND expires_at <= ? AND revoked = ?", now, deadline, false).
+ Find(&keys).Error; err != nil {
+ logger.Error("api-key-expiry: failed to query", "error", err)
+ return err
+ }
+
+ if len(keys) == 0 {
+ return nil
+ }
+
+ // Group by user
+ userKeys := make(map[uint][]expiringKey)
+ for _, k := range keys {
+ userKeys[k.UserID] = append(userKeys[k.UserID], expiringKey{
+ Name: k.Name,
+ ExpiresAt: k.ExpiresAt.Format("January 2, 2006"),
+ })
+ }
+
+ sent := 0
+ for userID, ks := range userKeys {
+ subject := fmt.Sprintf("%d API key(s) expiring soon", len(ks))
+ if len(ks) == 1 {
+ subject = "API key expiring soon"
+ }
+ if err := j.notifier.SendToUser(userID, subject, notification.TemplateAPIKeyExpiry, map[string]any{
+ "Keys": ks,
+ "KeyCount": len(ks),
+ }); err != nil {
+ logger.Error("api-key-expiry: failed to send", "user_id", userID, "error", err)
+ continue
+ }
+ sent++
+ }
+
+ logger.Info("api-key-expiry: notifications sent", "count", sent)
+ return nil
+}
diff --git a/internal/cron/jobs/bounce_alert.go b/internal/cron/jobs/bounce_alert.go
new file mode 100644
index 0000000..6e1fd47
--- /dev/null
+++ b/internal/cron/jobs/bounce_alert.go
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package jobs
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+const bounceRateThreshold = 5.0 // percent
+
+// BounceAlertJob checks for users with high bounce rates and sends alerts.
+type BounceAlertJob struct {
+ db *gorm.DB
+ notifier *notification.Service
+ bounceRepo *repositories.BounceRepository
+ suppressionRepo *repositories.SuppressionRepository
+}
+
+func NewBounceAlertJob(
+ db *gorm.DB,
+ notifier *notification.Service,
+ bounceRepo *repositories.BounceRepository,
+ suppressionRepo *repositories.SuppressionRepository,
+) *BounceAlertJob {
+ return &BounceAlertJob{
+ db: db,
+ notifier: notifier,
+ bounceRepo: bounceRepo,
+ suppressionRepo: suppressionRepo,
+ }
+}
+
+func (j *BounceAlertJob) Name() string { return "bounce-alert" }
+func (j *BounceAlertJob) Schedule() string { return "0 9 * * *" } // daily at 09:00 UTC
+
+func (j *BounceAlertJob) Run(_ context.Context, _ *asynq.Client) error {
+ if j.notifier == nil || !j.notifier.IsConfigured() {
+ return nil
+ }
+
+ now := time.Now().UTC()
+ from := now.Add(-24 * time.Hour)
+
+ // Find users who sent emails in the last 24 hours
+ type userEmailCount struct {
+ UserID uint `gorm:"column:user_id"`
+ Total int64 `gorm:"column:total"`
+ }
+ var counts []userEmailCount
+ if err := j.db.Model(&models.Email{}).
+ Select("user_id, COUNT(*) as total").
+ Where("created_at >= ? AND workspace_id IS NULL", from).
+ Group("user_id").
+ Having("COUNT(*) >= ?", 10). // Only alert for users with meaningful volume
+ Find(&counts).Error; err != nil {
+ logger.Error("bounce-alert: failed to query email counts", "error", err)
+ return err
+ }
+
+ sent := 0
+ for _, uc := range counts {
+ bounceCount, err := j.bounceRepo.CountByUserAndDateRange(uc.UserID, from, now)
+ if err != nil {
+ continue
+ }
+
+ bounceRate := float64(bounceCount) / float64(uc.Total) * 100
+ if bounceRate < bounceRateThreshold {
+ continue
+ }
+
+ // Count new suppressions
+ var suppressionCount int64
+ j.db.Model(&models.Suppression{}).
+ Where("user_id = ? AND created_at >= ?", uc.UserID, from).
+ Count(&suppressionCount)
+
+ if err := j.notifier.SendToUser(uc.UserID, "Bounce Rate Alert", notification.TemplateBounceAlert, map[string]any{
+ "BounceRate": fmt.Sprintf("%.1f", bounceRate),
+ "Threshold": fmt.Sprintf("%.0f", bounceRateThreshold),
+ "TotalEmails": uc.Total,
+ "BounceCount": bounceCount,
+ "SuppressionCount": suppressionCount,
+ }); err != nil {
+ logger.Error("bounce-alert: failed to send", "user_id", uc.UserID, "error", err)
+ continue
+ }
+ sent++
+ }
+
+ logger.Info("bounce-alert: notifications sent", "count", sent)
+ return nil
+}
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 6697c72..d63fa14 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -253,6 +253,37 @@ func (h *AdminHandler) DeleteUser(c *okapi.Context, req *AdminDeleteUserRequest)
})
}
+// ForceDeleteUser permanently deletes a disabled user and all their data (admin only).
+// The user must be disabled (Active=false) before they can be force-deleted.
+func (h *AdminHandler) ForceDeleteUser(c *okapi.Context, req *AdminDeleteUserRequest) error {
+ currentUserID := c.GetInt("user_id")
+ if req.ID == currentUserID {
+ return c.AbortBadRequest("cannot delete your own account")
+ }
+
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ if user.Active {
+ return c.AbortBadRequest("user must be disabled before force deletion")
+ }
+
+ if err := h.userRepo.DeleteAllUserData(uint(req.ID)); err != nil {
+ return c.AbortInternalServerError("failed to delete user data")
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "user.force_deleted", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("User ID %d permanently deleted by admin", req.ID),
+ map[string]any{"deleted_user_id": req.ID})
+ }
+
+ return c.NoContent()
+}
+
// CancelUserDeletion cancels a scheduled account deletion (admin only).
func (h *AdminHandler) CancelUserDeletion(c *okapi.Context, req *AdminDeleteUserRequest) error {
user, err := h.userRepo.FindByID(uint(req.ID))
diff --git a/internal/handlers/api_key_handler.go b/internal/handlers/api_key_handler.go
index bdd68b3..8e20987 100644
--- a/internal/handlers/api_key_handler.go
+++ b/internal/handlers/api_key_handler.go
@@ -18,10 +18,12 @@
package handlers
import (
+ "fmt"
"time"
"github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/services/auth"
+ "github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
@@ -34,7 +36,14 @@ type APIKeyHandler struct {
audit *audit.Logger
quota QuotaChecker
db *gorm.DB
+ notifier *notification.Service
}
+
+// SetNotifier sets the notification service for API key creation alerts.
+func (h *APIKeyHandler) SetNotifier(n *notification.Service) {
+ h.notifier = n
+}
+
type CreateAPIKeyRequest struct {
Body struct {
Name string `json:"name" required:"true"`
@@ -101,6 +110,23 @@ func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) error
h.audit.Log(scope.UserID, c.GetString("email"), c.RealIP(), "apikey.created", "API key created: "+req.Body.Name, nil)
+ // Send API key created notification (best-effort)
+ if h.notifier != nil {
+ expiresStr := "Never"
+ if key.ExpiresAt != nil {
+ expiresStr = key.ExpiresAt.Format("January 2, 2006")
+ }
+ go func() {
+ _ = h.notifier.SendToUser(scope.UserID, fmt.Sprintf("New API key created: %s", key.Name), notification.TemplateAPIKeyCreated, map[string]any{
+ "KeyName": key.Name,
+ "KeyPrefix": key.KeyPrefix,
+ "ExpiresAt": expiresStr,
+ "CreatedAt": key.CreatedAt.Format("January 2, 2006 at 15:04 UTC"),
+ "IPAddress": c.RealIP(),
+ })
+ }()
+ }
+
return created(c, okapi.M{
"key": rawKey,
"id": key.ID,
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index d87bdce..5085c07 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -62,6 +62,7 @@ func NewOAuthHandler(
}
type OAuthProviderInfo struct {
+ ID uint `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Type string `json:"type"`
@@ -90,6 +91,7 @@ func (h *OAuthHandler) ListProviders(c *okapi.Context) error {
var result []OAuthProviderInfo
for _, p := range providers {
result = append(result, OAuthProviderInfo{
+ ID: p.ID,
Slug: p.Slug,
Name: p.Name,
Type: string(p.Type),
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index 16cb1c8..55340db 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -28,6 +28,7 @@ import (
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/eventbus"
+ "github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
@@ -43,6 +44,7 @@ type UserHandler struct {
seeder *seeder.Seeder
bus *eventbus.EventBus
settings *settings.Provider
+ notifier *notification.Service
}
func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {
@@ -64,6 +66,11 @@ func (h *UserHandler) SetSettings(s *settings.Provider) {
h.settings = s
}
+// SetNotifier sets the notification service for sending welcome and password change emails.
+func (h *UserHandler) SetNotifier(n *notification.Service) {
+ h.notifier = n
+}
+
type LoginRequest struct {
Body struct {
Email string `json:"email" required:"true" format:"email"`
@@ -189,6 +196,13 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
fmt.Sprintf("User %q registered", user.Email), nil)
}
+ // Send welcome email (best-effort)
+ if h.notifier != nil {
+ go func() {
+ _ = h.notifier.SendToUser(user.ID, "Welcome to Posta!", notification.TemplateWelcome, nil)
+ }()
+ }
+
// Auto-login: generate JWT token
token, _, err := h.generateTokenWithSession(c, user)
if err != nil {
@@ -262,6 +276,15 @@ func (h *UserHandler) ChangePassword(c *okapi.Context, req *ChangePasswordReques
return c.AbortInternalServerError("failed to update password")
}
+ // Send password change notification (best-effort)
+ if h.notifier != nil {
+ go func() {
+ _ = h.notifier.SendToUser(user.ID, "Your password has been changed", notification.TemplatePasswordChanged, map[string]any{
+ "ChangedAt": time.Now().UTC().Format("January 2, 2006 at 15:04 UTC"),
+ })
+ }()
+ }
+
return ok(c, okapi.M{"message": "password updated successfully"})
}
diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.go
index 777b643..23ef1cb 100644
--- a/internal/handlers/workspace_handler.go
+++ b/internal/handlers/workspace_handler.go
@@ -26,6 +26,7 @@ import (
"time"
"github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
@@ -36,6 +37,8 @@ type WorkspaceHandler struct {
userRepo *repositories.UserRepository
db *gorm.DB
planService planService
+ notifier *notification.Service
+ appURL string
}
// planService is an optional interface for resolving workspace plans and quotas.
@@ -327,10 +330,37 @@ func (h *WorkspaceHandler) UpdateMemberRole(c *okapi.Context, req *UpdateMemberR
return c.AbortBadRequest("cannot assign owner role")
}
+ oldRole := member.Role
+
if err := h.workspaceRepo.UpdateMemberRole(uint(wsID), uint(req.MemberID), req.Body.Role); err != nil {
return c.AbortInternalServerError("failed to update member role")
}
+ // Send role change notification (best-effort)
+ if h.notifier != nil && req.Body.Role != oldRole {
+ ws, _ := h.workspaceRepo.FindByID(uint(wsID))
+ changer, _ := h.userRepo.FindByID(uint(c.GetInt("user_id")))
+ wsName := ""
+ changerName := "An administrator"
+ if ws != nil {
+ wsName = ws.Name
+ }
+ if changer != nil {
+ changerName = changer.Name
+ if changerName == "" {
+ changerName = changer.Email
+ }
+ }
+ go func() {
+ _ = h.notifier.SendToUser(uint(req.MemberID), fmt.Sprintf("Your role in %s has been updated", wsName), notification.TemplateRoleChanged, map[string]any{
+ "WorkspaceName": wsName,
+ "OldRole": string(oldRole),
+ "NewRole": string(req.Body.Role),
+ "ChangedBy": changerName,
+ })
+ }()
+ }
+
return ok(c, okapi.M{"message": "member role updated"})
}
@@ -393,6 +423,37 @@ func (h *WorkspaceHandler) InviteMember(c *okapi.Context, req *InviteMemberReque
return c.AbortInternalServerError("failed to create invitation")
}
+ // Send invitation email (best-effort, don't fail the request)
+ if h.notifier != nil {
+ ws, _ := h.workspaceRepo.FindByID(uint(wsID))
+ inviter, _ := h.userRepo.FindByID(uint(inviterID))
+ wsName := ""
+ inviterName := "A team member"
+ if ws != nil {
+ wsName = ws.Name
+ }
+ if inviter != nil {
+ inviterName = inviter.Name
+ if inviterName == "" {
+ inviterName = inviter.Email
+ }
+ }
+ roleArticle := "a"
+ if inv.Role == "admin" || inv.Role == "editor" || inv.Role == "owner" {
+ roleArticle = "an"
+ }
+ go func() {
+ _ = h.notifier.Send(email, fmt.Sprintf("You've been invited to %s", wsName), notification.TemplateInvitation, map[string]any{
+ "WorkspaceName": wsName,
+ "InviterName": inviterName,
+ "Role": string(inv.Role),
+ "RoleArticle": roleArticle,
+ "AcceptURL": fmt.Sprintf("%s/invitations?token=%s", h.appURL, inv.Token),
+ "ExpiresAt": inv.ExpiresAt.Format("January 2, 2006"),
+ })
+ }()
+ }
+
return created(c, InvitationResponse{
ID: inv.ID,
WorkspaceID: inv.WorkspaceID,
@@ -730,6 +791,12 @@ func (h *WorkspaceHandler) SetPlanService(ps planService) {
h.planService = ps
}
+// SetNotifier sets the notification service for sending invitation and role change emails.
+func (h *WorkspaceHandler) SetNotifier(n *notification.Service, appURL string) {
+ h.notifier = n
+ h.appURL = appURL
+}
+
// GetPlan returns the effective plan for the current workspace.
func (h *WorkspaceHandler) GetPlan(c *okapi.Context) error {
wsID := uint(c.GetInt("workspace_id"))
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index ccf9d84..7156dc1 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -66,19 +66,19 @@ func sessionValidator(store *sessionpkg.Store) func(c *okapi.Context, claims jwt
}
}
-func sessionAwareUnauthorized(c *okapi.Context) error {
- if c.GetBool(sessionRevokedKey) {
- return c.AbortUnauthorized("session has been revoked")
- }
- return c.AbortForbidden("Insufficient permissions")
-}
+// func sessionAwareUnauthorized(c *okapi.Context) error {
+// if c.GetBool(sessionRevokedKey) {
+// return c.AbortUnauthorized("session has been revoked")
+// }
+// return c.AbortForbidden("Insufficient permissions")
+// }
// JWTAuth creates user JWT auth middleware. If sessionStore is non-nil, revoked sessions are rejected.
func JWTAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
auth := baseJWTAuth(cfg)
if len(sessionStore) > 0 && sessionStore[0] != nil {
auth.ValidateClaims = sessionValidator(sessionStore[0])
- auth.OnUnauthorized = sessionAwareUnauthorized
+ // auth.OnUnauthorized = sessionAwareUnauthorized
}
return auth
}
@@ -89,7 +89,7 @@ func JWTAdminAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.J
auth.ClaimsExpression = "Equals(`role`,`admin`)"
if len(sessionStore) > 0 && sessionStore[0] != nil {
auth.ValidateClaims = sessionValidator(sessionStore[0])
- auth.OnUnauthorized = sessionAwareUnauthorized
+ // auth.OnUnauthorized = sessionAwareUnauthorized
}
return auth
}
@@ -101,7 +101,7 @@ func JWTAdminQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) ok
auth.TokenLookup = "query:token"
if len(sessionStore) > 0 && sessionStore[0] != nil {
auth.ValidateClaims = sessionValidator(sessionStore[0])
- auth.OnUnauthorized = sessionAwareUnauthorized
+ // auth.OnUnauthorized = sessionAwareUnauthorized
}
return auth
}
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 0f18be1..7a2b81b 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -97,6 +97,21 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodDelete,
+ Path: "/users/{id:int}/force",
+ Handler: okapi.H(r.h.admin.ForceDeleteUser),
+ Group: adminGroup,
+ Tags: []string{"Admin"},
+ Summary: "Force delete user",
+ Description: "Permanently delete a disabled user and all their data. The user must be disabled before force deletion.",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
{
Method: http.MethodPost,
Path: "/users/{id:int}/cancel-deletion",
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 8337c35..6b115ba 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -36,6 +36,7 @@ import (
"github.com/goposta/posta/internal/services/cache"
"github.com/goposta/posta/internal/services/email"
"github.com/goposta/posta/internal/services/eventbus"
+ "github.com/goposta/posta/internal/services/notification"
planpkg "github.com/goposta/posta/internal/services/plan"
"github.com/goposta/posta/internal/services/ratelimit"
"github.com/goposta/posta/internal/services/seeder"
@@ -110,7 +111,7 @@ type routerHandlers struct {
plan *handlers.PlanHandler
}
-func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context) {
+func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) {
// Repositories
userRepo := repositories.NewUserRepository(db)
apiKeyRepo := repositories.NewAPIKeyRepository(db)
@@ -246,6 +247,13 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.domain.SetQuota(planService, db)
r.h.smtp.SetQuota(planService, db)
+ // Notifications
+ if len(notifier) > 0 && notifier[0] != nil {
+ r.h.user.SetNotifier(notifier[0])
+ r.h.workspace.SetNotifier(notifier[0], cfg.AppWebURL)
+ r.h.apiKey.SetNotifier(notifier[0])
+ }
+
// Email content privacy
r.h.email.SetSettings(settingsProvider)
r.h.admin.SetEmailSettings(settingsProvider)
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
new file mode 100644
index 0000000..faa61db
--- /dev/null
+++ b/internal/services/notification/service.go
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package notification
+
+import (
+ "bytes"
+ "embed"
+ "fmt"
+ "html/template"
+
+ "github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/email"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+)
+
+//go:embed templates/*.tmpl
+var templateFS embed.FS
+
+// Template names used throughout the notification system.
+const (
+ TemplateDailyReport = "daily_report"
+ TemplateInvitation = "workspace_invitation"
+ TemplateWelcome = "welcome"
+ TemplatePasswordChanged = "password_changed"
+ TemplateAPIKeyCreated = "api_key_created"
+ TemplateAPIKeyExpiry = "api_key_expiry"
+ TemplateBounceAlert = "bounce_alert"
+ TemplateRoleChanged = "role_changed"
+)
+
+// Service sends platform notification emails via the system SMTP server.
+type Service struct {
+ smtpCfg config.SystemSMTPConfig
+ appName string
+ appURL string
+ sender *email.SMTPSender
+ userRepo *repositories.UserRepository
+ userSettingRepo *repositories.UserSettingRepository
+ templates map[string]*template.Template
+}
+
+// NewService creates a new notification service.
+func NewService(
+ smtpCfg config.SystemSMTPConfig,
+ appName, appURL string,
+ userRepo *repositories.UserRepository,
+ userSettingRepo *repositories.UserSettingRepository,
+) *Service {
+ s := &Service{
+ smtpCfg: smtpCfg,
+ appName: appName,
+ appURL: appURL,
+ sender: email.NewSMTPSender(),
+ userRepo: userRepo,
+ userSettingRepo: userSettingRepo,
+ templates: make(map[string]*template.Template),
+ }
+ s.loadTemplates()
+ return s
+}
+
+func (s *Service) loadTemplates() {
+ names := []string{
+ TemplateDailyReport,
+ TemplateInvitation,
+ TemplateWelcome,
+ TemplatePasswordChanged,
+ TemplateAPIKeyCreated,
+ TemplateAPIKeyExpiry,
+ TemplateBounceAlert,
+ TemplateRoleChanged,
+ }
+ for _, name := range names {
+ tmpl := template.Must(template.ParseFS(templateFS,
+ "templates/base.tmpl",
+ fmt.Sprintf("templates/%s.tmpl", name),
+ ))
+ s.templates[name] = tmpl
+ }
+}
+
+// IsConfigured returns true if the system SMTP is configured.
+func (s *Service) IsConfigured() bool {
+ return s.smtpCfg.IsConfigured()
+}
+
+// Send renders a template and sends an email to the given address.
+func (s *Service) Send(to, subject, templateName string, data map[string]any) error {
+ if !s.IsConfigured() {
+ logger.Debug("notification service: system SMTP not configured, skipping", "template", templateName, "to", to)
+ return nil
+ }
+
+ if data == nil {
+ data = make(map[string]any)
+ }
+ data["AppName"] = s.appName
+ data["AppURL"] = s.appURL
+ data["Subject"] = subject
+
+ html, err := s.render(templateName, data)
+ if err != nil {
+ return fmt.Errorf("notification render %s: %w", templateName, err)
+ }
+
+ server := s.systemServer()
+ if err := s.sender.Send(server, s.smtpCfg.From, []string{to}, subject, html, "", nil, nil, "", false); err != nil {
+ return fmt.Errorf("notification send to %s: %w", to, err)
+ }
+
+ return nil
+}
+
+// SendToUser sends a notification to a user, respecting their notification preferences.
+func (s *Service) SendToUser(userID uint, subject, templateName string, data map[string]any) error {
+ if !s.IsConfigured() {
+ return nil
+ }
+
+ user, err := s.userRepo.FindByID(userID)
+ if err != nil {
+ return fmt.Errorf("notification: user %d not found: %w", userID, err)
+ }
+
+ settings, err := s.userSettingRepo.FindByUserID(userID)
+ if err != nil {
+ return fmt.Errorf("notification: settings for user %d: %w", userID, err)
+ }
+
+ if !settings.EmailNotifications {
+ logger.Debug("notification service: email notifications disabled for user", "user_id", userID)
+ return nil
+ }
+
+ to := settings.NotificationEmail
+ if to == "" {
+ to = user.Email
+ }
+
+ if data == nil {
+ data = make(map[string]any)
+ }
+ data["UserName"] = user.Name
+ if data["UserName"] == "" {
+ data["UserName"] = user.Email
+ }
+
+ return s.Send(to, subject, templateName, data)
+}
+
+func (s *Service) render(templateName string, data map[string]any) (string, error) {
+ tmpl, ok := s.templates[templateName]
+ if !ok {
+ return "", fmt.Errorf("unknown notification template: %s", templateName)
+ }
+ var buf bytes.Buffer
+ if err := tmpl.ExecuteTemplate(&buf, "base", data); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+func (s *Service) systemServer() *models.SMTPServer {
+ return &models.SMTPServer{
+ Host: s.smtpCfg.Host,
+ Port: s.smtpCfg.Port,
+ Username: s.smtpCfg.Username,
+ Password: s.smtpCfg.Password,
+ Encryption: s.smtpCfg.Encryption,
+ }
+}
diff --git a/internal/services/notification/templates/api_key_created.tmpl b/internal/services/notification/templates/api_key_created.tmpl
new file mode 100644
index 0000000..187969d
--- /dev/null
+++ b/internal/services/notification/templates/api_key_created.tmpl
@@ -0,0 +1,42 @@
+{{ define "content" }}
+<h2>New API Key Created</h2>
+<p>Hi {{ .UserName }},</p>
+<p>A new API key has been created on your account:</p>
+
+<table class="stats-table">
+ <tr>
+ <th>Detail</th>
+ <th>Value</th>
+ </tr>
+ <tr>
+ <td>Name</td>
+ <td><strong>{{ .KeyName }}</strong></td>
+ </tr>
+ <tr>
+ <td>Prefix</td>
+ <td><code>{{ .KeyPrefix }}</code></td>
+ </tr>
+ <tr>
+ <td>Expires</td>
+ <td>{{ .ExpiresAt }}</td>
+ </tr>
+ <tr>
+ <td>Created</td>
+ <td>{{ .CreatedAt }}</td>
+ </tr>
+ <tr>
+ <td>IP Address</td>
+ <td>{{ .IPAddress }}</td>
+ </tr>
+</table>
+
+<div class="alert-box alert-warning">
+ <strong>Wasn't you?</strong> If you did not create this key, please revoke it immediately and review your account security.
+</div>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 24px 0;">
+ <a href="{{ .AppURL }}/api-keys" class="btn">Manage API Keys</a>
+</p>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/api_key_expiry.tmpl b/internal/services/notification/templates/api_key_expiry.tmpl
new file mode 100644
index 0000000..e5ee894
--- /dev/null
+++ b/internal/services/notification/templates/api_key_expiry.tmpl
@@ -0,0 +1,26 @@
+{{ define "content" }}
+<h2>API Key Expiring Soon</h2>
+<p>Hi {{ .UserName }},</p>
+<p>The following API {{ if eq .KeyCount 1 }}key is{{ else }}keys are{{ end }} expiring within the next 7 days:</p>
+
+<table class="stats-table">
+ <tr>
+ <th>Key Name</th>
+ <th>Expires</th>
+ </tr>
+ {{ range .Keys }}
+ <tr>
+ <td>{{ .Name }}</td>
+ <td>{{ .ExpiresAt }}</td>
+ </tr>
+ {{ end }}
+</table>
+
+<p>Please regenerate {{ if eq .KeyCount 1 }}this key{{ else }}these keys{{ end }} to avoid service interruption.</p>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 24px 0;">
+ <a href="{{ .AppURL }}/api-keys" class="btn">Manage API Keys</a>
+</p>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/base.tmpl b/internal/services/notification/templates/base.tmpl
new file mode 100644
index 0000000..a9c2505
--- /dev/null
+++ b/internal/services/notification/templates/base.tmpl
@@ -0,0 +1,45 @@
+{{ define "base" }}<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>{{ .Subject }}</title>
+<style>
+ body { margin: 0; padding: 0; background-color: #f4f4f7; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; }
+ .wrapper { width: 100%; background-color: #f4f4f7; padding: 40px 0; }
+ .container { max-width: 580px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
+ .header { background-color: #7c3aed; padding: 24px 32px; text-align: center; }
+ .header h1 { color: #ffffff; margin: 0; font-size: 20px; font-weight: 600; }
+ .body { padding: 32px; color: #374151; font-size: 15px; line-height: 1.6; }
+ .body h2 { color: #111827; font-size: 18px; margin: 0 0 16px; }
+ .body p { margin: 0 0 16px; }
+ .btn { display: inline-block; padding: 12px 28px; background-color: #7c3aed; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px; }
+ .footer { padding: 24px 32px; text-align: center; font-size: 12px; color: #9ca3af; border-top: 1px solid #e5e7eb; }
+ .stats-table { width: 100%; border-collapse: collapse; margin: 16px 0; }
+ .stats-table th, .stats-table td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #e5e7eb; font-size: 14px; }
+ .stats-table th { color: #6b7280; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; }
+ .stats-table td { color: #111827; }
+ .highlight { font-size: 28px; font-weight: 700; color: #7c3aed; }
+ .muted { color: #6b7280; font-size: 13px; }
+ .alert-box { padding: 16px; border-radius: 6px; margin: 16px 0; }
+ .alert-warning { background-color: #fef3c7; border: 1px solid #fbbf24; color: #92400e; }
+ .alert-danger { background-color: #fee2e2; border: 1px solid #fca5a5; color: #991b1b; }
+ .alert-info { background-color: #eff6ff; border: 1px solid #93c5fd; color: #1e40af; }
+</style>
+</head>
+<body>
+<div class="wrapper">
+ <div class="container">
+ <div class="header">
+ <h1>{{ .AppName }}</h1>
+ </div>
+ <div class="body">
+ {{ template "content" . }}
+ </div>
+ <div class="footer">
+ {{ if .AppURL }}<a href="{{ .AppURL }}" style="color: #7c3aed; text-decoration: none;">{{ .AppName }}</a> &mdash; {{ end }}This is an automated notification.
+ </div>
+ </div>
+</div>
+</body>
+</html>{{ end }}
diff --git a/internal/services/notification/templates/bounce_alert.tmpl b/internal/services/notification/templates/bounce_alert.tmpl
new file mode 100644
index 0000000..9a8c3eb
--- /dev/null
+++ b/internal/services/notification/templates/bounce_alert.tmpl
@@ -0,0 +1,35 @@
+{{ define "content" }}
+<h2>Bounce Rate Alert</h2>
+<p>Hi {{ .UserName }},</p>
+
+<div class="alert-box alert-danger">
+ Your bounce rate in the last 24 hours is <strong>{{ .BounceRate }}%</strong>, which exceeds the {{ .Threshold }}% threshold.
+</div>
+
+<table class="stats-table">
+ <tr>
+ <th>Metric</th>
+ <th style="text-align: right;">Count</th>
+ </tr>
+ <tr>
+ <td>Total Emails (24h)</td>
+ <td style="text-align: right;">{{ .TotalEmails }}</td>
+ </tr>
+ <tr>
+ <td>Bounces</td>
+ <td style="text-align: right; color: #dc2626;">{{ .BounceCount }}</td>
+ </tr>
+ <tr>
+ <td>New Suppressions</td>
+ <td style="text-align: right; color: #d97706;">{{ .SuppressionCount }}</td>
+ </tr>
+</table>
+
+<p>High bounce rates can damage your sender reputation. Consider reviewing your recipient lists and removing invalid addresses.</p>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 24px 0;">
+ <a href="{{ .AppURL }}/bounces" class="btn">Review Bounces</a>
+</p>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/daily_report.tmpl b/internal/services/notification/templates/daily_report.tmpl
new file mode 100644
index 0000000..b2794e5
--- /dev/null
+++ b/internal/services/notification/templates/daily_report.tmpl
@@ -0,0 +1,45 @@
+{{ define "content" }}
+<h2>Daily Email Report</h2>
+<p>Here's your email activity summary for <strong>{{ .ReportDate }}</strong>.</p>
+
+<table class="stats-table">
+ <tr>
+ <th>Metric</th>
+ <th style="text-align: right;">Count</th>
+ </tr>
+ <tr>
+ <td>Total Emails</td>
+ <td style="text-align: right;"><strong>{{ .TotalEmails }}</strong></td>
+ </tr>
+ <tr>
+ <td>Sent</td>
+ <td style="text-align: right; color: #059669;">{{ .SentEmails }}</td>
+ </tr>
+ <tr>
+ <td>Failed</td>
+ <td style="text-align: right; color: #dc2626;">{{ .FailedEmails }}</td>
+ </tr>
+ <tr>
+ <td>Bounced</td>
+ <td style="text-align: right; color: #d97706;">{{ .BouncedEmails }}</td>
+ </tr>
+ <tr>
+ <td>Suppressed</td>
+ <td style="text-align: right; color: #6b7280;">{{ .SuppressedEmails }}</td>
+ </tr>
+</table>
+
+{{ if gt .TotalEmails 0 }}
+<p>Delivery rate: <span class="highlight">{{ .DeliveryRate }}%</span></p>
+{{ else }}
+<p class="muted">No emails were sent during this period.</p>
+{{ end }}
+
+{{ if .AppURL }}
+<p style="text-align: center; margin-top: 24px;">
+ <a href="{{ .AppURL }}" class="btn">View Dashboard</a>
+</p>
+{{ end }}
+
+<p class="muted" style="margin-top: 24px;">You receive this report because you enabled daily reports in your notification settings.</p>
+{{ end }}
diff --git a/internal/services/notification/templates/password_changed.tmpl b/internal/services/notification/templates/password_changed.tmpl
new file mode 100644
index 0000000..dd3386a
--- /dev/null
+++ b/internal/services/notification/templates/password_changed.tmpl
@@ -0,0 +1,15 @@
+{{ define "content" }}
+<h2>Password Changed</h2>
+<p>Hi {{ .UserName }},</p>
+<p>Your password was successfully changed on <strong>{{ .ChangedAt }}</strong>.</p>
+
+<div class="alert-box alert-warning">
+ <strong>Wasn't you?</strong> If you did not make this change, please secure your account immediately by resetting your password and reviewing your active sessions.
+</div>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 24px 0;">
+ <a href="{{ .AppURL }}/profile" class="btn">Review Account</a>
+</p>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/role_changed.tmpl b/internal/services/notification/templates/role_changed.tmpl
new file mode 100644
index 0000000..96eb3fc
--- /dev/null
+++ b/internal/services/notification/templates/role_changed.tmpl
@@ -0,0 +1,15 @@
+{{ define "content" }}
+<h2>Workspace Role Updated</h2>
+<p>Hi {{ .UserName }},</p>
+<p>Your role in the workspace <strong>"{{ .WorkspaceName }}"</strong> has been changed from <strong>{{ .OldRole }}</strong> to <strong>{{ .NewRole }}</strong> by {{ .ChangedBy }}.</p>
+
+<div class="alert-box alert-info">
+ Your new permissions as <strong>{{ .NewRole }}</strong> are now active.
+</div>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 24px 0;">
+ <a href="{{ .AppURL }}/workspaces" class="btn">View Workspaces</a>
+</p>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/welcome.tmpl b/internal/services/notification/templates/welcome.tmpl
new file mode 100644
index 0000000..a0d3891
--- /dev/null
+++ b/internal/services/notification/templates/welcome.tmpl
@@ -0,0 +1,13 @@
+{{ define "content" }}
+<h2>Welcome to {{ .AppName }}!</h2>
+<p>Hi {{ .UserName }},</p>
+<p>Your account has been created successfully. You can now start sending emails, managing templates, and configuring your workspace.</p>
+
+{{ if .AppURL }}
+<p style="text-align: center; margin: 32px 0;">
+ <a href="{{ .AppURL }}" class="btn">Go to Dashboard</a>
+</p>
+{{ end }}
+
+<p class="muted">If you didn't create this account, please ignore this email.</p>
+{{ end }}
diff --git a/internal/services/notification/templates/workspace_invitation.tmpl b/internal/services/notification/templates/workspace_invitation.tmpl
new file mode 100644
index 0000000..239dcff
--- /dev/null
+++ b/internal/services/notification/templates/workspace_invitation.tmpl
@@ -0,0 +1,12 @@
+{{ define "content" }}
+<h2>You've been invited to a workspace</h2>
+<p><strong>{{ .InviterName }}</strong> has invited you to join the workspace <strong>"{{ .WorkspaceName }}"</strong> as {{ .RoleArticle }} <strong>{{ .Role }}</strong>.</p>
+
+{{ if .AcceptURL }}
+<p style="text-align: center; margin: 32px 0;">
+ <a href="{{ .AcceptURL }}" class="btn">Accept Invitation</a>
+</p>
+{{ end }}
+
+<p class="muted">This invitation expires on {{ .ExpiresAt }}. If you don't have an account, you'll need to register first.</p>
+{{ end }}
diff --git a/internal/storage/repositories/bounce_repo.go b/internal/storage/repositories/bounce_repo.go
index 0fe60dd..14753f8 100644
--- a/internal/storage/repositories/bounce_repo.go
+++ b/internal/storage/repositories/bounce_repo.go
@@ -18,6 +18,8 @@
package repositories
import (
+ "time"
+
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
)
@@ -94,3 +96,12 @@ func (r *BounceRepository) CountHardBouncesByRecipient(userID uint, recipient st
Count(&count).Error
return count, err
}
+
+// CountByUserAndDateRange counts bounces for a user within a date range.
+func (r *BounceRepository) CountByUserAndDateRange(userID uint, from, to time.Time) (int64, error) {
+ var count int64
+ err := r.db.Model(&models.Bounce{}).
+ Where("user_id = ? AND created_at >= ? AND created_at <= ?", userID, from, to).
+ Count(&count).Error
+ return count, err
+}
diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.go
index 5337879..591877d 100644
--- a/internal/storage/repositories/user_repo.go
+++ b/internal/storage/repositories/user_repo.go
@@ -77,20 +77,44 @@ func (r *UserRepository) Delete(id uint) error {
// DeleteAllUserData removes all data owned by a user
func (r *UserRepository) DeleteAllUserData(userID uint) error {
return r.db.Transaction(func(tx *gorm.DB) error {
+ // Delete tracking_events via campaign_messages -> campaigns
+ if err := tx.Exec("DELETE FROM tracking_events WHERE campaign_message_id IN (SELECT id FROM campaign_messages WHERE campaign_id IN (SELECT id FROM campaigns WHERE user_id = ?))", userID).Error; err != nil {
+ return err
+ }
+ // Delete tracked_links via campaigns
+ if err := tx.Exec("DELETE FROM tracked_links WHERE campaign_id IN (SELECT id FROM campaigns WHERE user_id = ?)", userID).Error; err != nil {
+ return err
+ }
+ // Delete campaign_messages via campaigns
+ if err := tx.Exec("DELETE FROM campaign_messages WHERE campaign_id IN (SELECT id FROM campaigns WHERE user_id = ?)", userID).Error; err != nil {
+ return err
+ }
+ // Delete subscriber_list_members via subscriber_lists
+ if err := tx.Exec("DELETE FROM subscriber_list_members WHERE list_id IN (SELECT id FROM subscriber_lists WHERE user_id = ?)", userID).Error; err != nil {
+ return err
+ }
+ // Clear active_version_id FK on templates before deleting versions
+ if err := tx.Exec("UPDATE templates SET active_version_id = NULL WHERE user_id = ?", userID).Error; err != nil {
+ return err
+ }
+ // Delete template_localizations via template_versions -> templates
+ if err := tx.Exec("DELETE FROM template_localizations WHERE version_id IN (SELECT id FROM template_versions WHERE template_id IN (SELECT id FROM templates WHERE user_id = ?))", userID).Error; err != nil {
+ return err
+ }
+ // Delete template_versions via templates
+ if err := tx.Exec("DELETE FROM template_versions WHERE template_id IN (SELECT id FROM templates WHERE user_id = ?)", userID).Error; err != nil {
+ return err
+ }
+
+ // Tables with a direct user_id column
tables := []string{
"sessions",
"webhook_deliveries",
"bounces",
"suppressions",
- "tracking_events",
- "tracked_links",
- "campaign_messages",
"campaigns",
- "subscriber_list_members",
"subscriber_lists",
"subscribers",
- "template_localizations",
- "template_versions",
"templates",
"style_sheets",
"languages",
@@ -100,9 +124,13 @@ func (r *UserRepository) DeleteAllUserData(userID uint) error {
"webhooks",
"domains",
"smtp_servers",
- "events",
"user_settings",
- "oauth_accounts",
+ "o_auth_accounts",
+ }
+
+ // Delete events
+ if err := tx.Exec("DELETE FROM events WHERE actor_id = ?", userID).Error; err != nil {
+ return err
}
var contactListIDs []uint
@@ -123,12 +151,12 @@ func (r *UserRepository) DeleteAllUserData(userID uint) error {
}
}
- // Remove workspace memberships (but not workspaces they don't own)
+ // Remove workspace memberships
if err := tx.Exec("DELETE FROM workspace_members WHERE user_id = ?", userID).Error; err != nil {
return err
}
- // Delete workspaces owned by this user (and their members/invitations)
+ // Delete workspaces owned
var ownedWSIDs []uint
if err := tx.Raw("SELECT id FROM workspaces WHERE owner_id = ?", userID).Scan(&ownedWSIDs).Error; err != nil {
return err
diff --git a/internal/worker/daily_report_handler.go b/internal/worker/daily_report_handler.go
new file mode 100644
index 0000000..0b4b6f7
--- /dev/null
+++ b/internal/worker/daily_report_handler.go
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package worker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/goposta/posta/internal/cron/jobs"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+)
+
+// DailyReportHandler processes daily report tasks from the Asynq queue.
+type DailyReportHandler struct {
+ notifier *notification.Service
+ analyticsRepo *repositories.AnalyticsRepository
+ bounceRepo *repositories.BounceRepository
+}
+
+// NewDailyReportHandler creates a new daily report task handler.
+func NewDailyReportHandler(
+ notifier *notification.Service,
+ analyticsRepo *repositories.AnalyticsRepository,
+ bounceRepo *repositories.BounceRepository,
+) *DailyReportHandler {
+ return &DailyReportHandler{
+ notifier: notifier,
+ analyticsRepo: analyticsRepo,
+ bounceRepo: bounceRepo,
+ }
+}
+
+// ProcessTask handles a daily report task for a single user.
+func (h *DailyReportHandler) ProcessTask(_ context.Context, t *asynq.Task) error {
+ var payload jobs.DailyReportPayload
+ if err := json.Unmarshal(t.Payload(), &payload); err != nil {
+ return fmt.Errorf("daily report: invalid payload: %w", err)
+ }
+
+ userID := payload.UserID
+ logger.Info("daily report: processing", "user_id", userID)
+
+ // Yesterday's date range
+ now := time.Now().UTC()
+ yesterday := now.AddDate(0, 0, -1)
+ from := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.UTC)
+ to := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, time.UTC)
+
+ // Gather stats
+ breakdown, err := h.analyticsRepo.StatusBreakdown(userID, from, to)
+ if err != nil {
+ logger.Error("daily report: failed to get stats", "user_id", userID, "error", err)
+ return err
+ }
+
+ var sent, failed, suppressed, total int64
+ for _, s := range breakdown {
+ total += s.Count
+ switch s.Status {
+ case "sent":
+ sent = s.Count
+ case "failed":
+ failed = s.Count
+ case "suppressed":
+ suppressed = s.Count
+ }
+ }
+
+ // Count bounces for the period
+ var bounced int64
+ if h.bounceRepo != nil {
+ bounced, _ = h.bounceRepo.CountByUserAndDateRange(userID, from, to)
+ }
+
+ var deliveryRate float64
+ if total > 0 {
+ deliveryRate = float64(sent) / float64(total) * 100
+ }
+
+ data := map[string]any{
+ "ReportDate": yesterday.Format("January 2, 2006"),
+ "TotalEmails": total,
+ "SentEmails": sent,
+ "FailedEmails": failed,
+ "BouncedEmails": bounced,
+ "SuppressedEmails": suppressed,
+ "DeliveryRate": fmt.Sprintf("%.1f", deliveryRate),
+ }
+
+ subject := fmt.Sprintf("Daily Email Report — %s", yesterday.Format("Jan 2, 2006"))
+ if err := h.notifier.SendToUser(userID, subject, notification.TemplateDailyReport, data); err != nil {
+ logger.Error("daily report: failed to send", "user_id", userID, "error", err)
+ return err
+ }
+
+ logger.Info("daily report: sent", "user_id", userID)
+ return nil
+}
diff --git a/web/src/api/admin.ts b/web/src/api/admin.ts
index 893abeb..0de427b 100644
--- a/web/src/api/admin.ts
+++ b/web/src/api/admin.ts
@@ -14,6 +14,9 @@ export const adminApi = {
deleteUser(id: number) {
return api.delete(`/admin/users/${id}`)
},
+ forceDeleteUser(id: number) {
+ return api.delete(`/admin/users/${id}/force`)
+ },
cancelUserDeletion(id: number) {
return api.post<ApiResponse<{ message: string }>>(`/admin/users/${id}/cancel-deletion`)
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 4c1fbfc..94de1b0 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -760,6 +760,7 @@ export interface TransferResponse {
// OAuth
export interface OAuthProviderInfo {
+ id: number
slug: string
name: string
type: 'google' | 'oidc'
diff --git a/web/src/views/about/About.vue b/web/src/views/about/About.vue
index 5cfd6b8..adc4f35 100644
--- a/web/src/views/about/About.vue
+++ b/web/src/views/about/About.vue
@@ -5,86 +5,6 @@ import { infoApi, type AppInfo } from '../../api/info'
const loading = ref(true)
const appInfo = ref<AppInfo | null>(null)
-const features = [
- {
- title: 'Email Delivery',
- icon: 'mail',
- items: [
- 'REST API for transactional, batch, and templated emails',
- 'Attachments, custom headers, and unsubscribe support',
- 'Scheduled sending and preview mode',
- 'Async processing with Redis and Asynq',
- 'Automatic retries and priority queues',
- ],
- },
- {
- title: 'Templates',
- icon: 'file-text',
- items: [
- 'Versioned and multi-language templates',
- 'Variable substitution and stylesheet inlining',
- 'Import/export and preview support',
- ],
- },
- {
- title: 'SMTP & Domains',
- icon: 'server',
- items: [
- 'Multiple SMTP providers with TLS support',
- 'Shared SMTP pools for teams',
- 'Domain verification (SPF, DKIM, DMARC)',
- 'Verified sender enforcement',
- ],
- },
- {
- title: 'Security',
- icon: 'key',
- items: [
- 'API keys with expiration, hashing, and IP allowlisting',
- 'JWT authentication and RBAC',
- 'Two-factor authentication (TOTP)',
- 'OAuth / SSO login (Google, Keycloak, authentik, and more)',
- 'Rate limiting and session management',
- ],
- },
- {
- title: 'Contacts & Suppression',
- icon: 'users',
- items: [
- 'Contact tracking and segmentation',
- 'Bounce and complaint handling',
- 'Automatic suppression lists',
- ],
- },
- {
- title: 'Workspaces',
- icon: 'briefcase',
- items: [
- 'Multi-tenant architecture with isolated workspaces',
- 'Role-based access control',
- 'Shared resources and scoped API keys',
- ],
- },
- {
- title: 'Webhooks & Events',
- icon: 'link',
- items: [
- 'Event-driven architecture with webhook delivery',
- 'Retry strategies and delivery tracking',
- 'Audit logs and real-time event streaming',
- ],
- },
- {
- title: 'Analytics & Monitoring',
- icon: 'bar-chart',
- items: [
- 'Email delivery metrics and trends',
- 'Prometheus integration',
- 'Health endpoints and daily reports',
- ],
- },
-]
-
const links = [
{ title: 'Website', url: 'https://goposta.dev/', icon: 'globe' },
{ title: 'Documentation', url: 'https://docs.goposta.dev/', icon: 'book-open' },
@@ -141,21 +61,6 @@ onMounted(async () => {
</div>
</div>
- <!-- Features -->
- <div class="about-section">
- <h2 class="section-title">Core Features</h2>
- <div class="features-grid">
- <div v-for="feature in features" :key="feature.title" class="card feature-card">
- <div class="card-body">
- <h3 class="feature-title">{{ feature.title }}</h3>
- <ul class="feature-list">
- <li v-for="item in feature.items" :key="item">{{ item }}</li>
- </ul>
- </div>
- </div>
- </div>
- </div>
-
<!-- Links -->
<div class="about-section">
<h2 class="section-title">Resources & SDKs</h2>
diff --git a/web/src/views/admin/OAuthProviders.vue b/web/src/views/admin/OAuthProviders.vue
index ac5a512..b6c1667 100644
--- a/web/src/views/admin/OAuthProviders.vue
+++ b/web/src/views/admin/OAuthProviders.vue
@@ -21,6 +21,16 @@ const form = ref({
auto_register: true, allowed_domains: '',
})
+// Edit modal
+const showEditModal = ref(false)
+const editing = ref(false)
+const editingProvider = ref<OAuthProviderAdmin | null>(null)
+const editForm = ref({
+ name: '', client_id: '', client_secret: '', issuer: '',
+ auth_url: '', token_url: '', userinfo_url: '',
+ scopes: '', auto_register: true, allowed_domains: '',
+})
+
async function fetchProviders() {
loading.value = true
try {
@@ -53,6 +63,46 @@ async function createProvider() {
}
}
+function openEdit(p: OAuthProviderAdmin) {
+ editingProvider.value = p
+ editForm.value = {
+ name: p.name,
+ client_id: '',
+ client_secret: '',
+ issuer: p.issuer || '',
+ auth_url: '',
+ token_url: '',
+ userinfo_url: '',
+ scopes: p.scopes || '',
+ auto_register: p.auto_register,
+ allowed_domains: p.allowed_domains || '',
+ }
+ showEditModal.value = true
+}
+
+async function updateProvider() {
+ if (!editingProvider.value) return
+ editing.value = true
+ try {
+ const data: Record<string, any> = {}
+ if (editForm.value.name) data.name = editForm.value.name
+ if (editForm.value.client_id) data.client_id = editForm.value.client_id
+ if (editForm.value.client_secret) data.client_secret = editForm.value.client_secret
+ if (editForm.value.issuer) data.issuer = editForm.value.issuer
+ if (editForm.value.scopes) data.scopes = editForm.value.scopes
+ data.auto_register = editForm.value.auto_register
+ data.allowed_domains = editForm.value.allowed_domains
+ await oauthApi.adminUpdate(editingProvider.value.id, data)
+ notify.success('Provider updated')
+ showEditModal.value = false
+ await fetchProviders()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to update provider')
+ } finally {
+ editing.value = false
+ }
+}
+
async function toggleEnabled(p: OAuthProviderAdmin) {
try {
await oauthApi.adminUpdate(p.id, { enabled: !p.enabled })
@@ -119,6 +169,7 @@ onMounted(fetchProviders)
<td>{{ formatDate(p.created_at) }}</td>
<td>
<div style="display: flex; gap: 6px;">
+ <button class="btn btn-secondary btn-sm" @click="openEdit(p)">Edit</button>
<button class="btn btn-secondary btn-sm" @click="toggleEnabled(p)">
{{ p.enabled ? 'Disable' : 'Enable' }}
</button>
@@ -192,5 +243,53 @@ onMounted(fetchProviders)
</form>
</div>
</div>
+
+ <!-- Edit Modal -->
+ <div v-if="showEditModal && editingProvider" class="modal-overlay" @click.self="showEditModal = false">
+ <div class="modal" style="max-width: 560px;">
+ <div class="modal-header"><h3>Edit {{ editingProvider.name }}</h3></div>
+ <form @submit.prevent="updateProvider">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="editForm.name" class="form-input" required />
+ </div>
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
+ <div class="form-group">
+ <label class="form-label">Client ID</label>
+ <input v-model="editForm.client_id" class="form-input" placeholder="Leave empty to keep current" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Client Secret</label>
+ <input v-model="editForm.client_secret" class="form-input" type="password" placeholder="Leave empty to keep current" />
+ </div>
+ </div>
+ <div v-if="editingProvider.type === 'oidc'" class="form-group">
+ <label class="form-label">Issuer URL</label>
+ <input v-model="editForm.issuer" class="form-input" placeholder="https://accounts.google.com" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Scopes</label>
+ <input v-model="editForm.scopes" class="form-input" placeholder="openid email profile" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed Domains</label>
+ <input v-model="editForm.allowed_domains" class="form-input" placeholder="example.com, company.org" />
+ <small style="font-size: 12px; color: var(--text-muted); display: block; margin-top: 4px;">Comma-separated. Leave empty to allow all.</small>
+ </div>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px;">
+ <input type="checkbox" v-model="editForm.auto_register" />
+ Auto-register new users on first login
+ </label>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showEditModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="editing">{{ editing ? 'Saving...' : 'Save' }}</button>
+ </div>
+ </form>
+ </div>
+ </div>
</div>
</template>
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
index 4649fff..eeb7154 100644
--- a/web/src/views/admin/UserDetail.vue
+++ b/web/src/views/admin/UserDetail.vue
@@ -16,6 +16,7 @@ const metrics = ref<UserDetailMetrics | null>(null)
const disabling2FA = ref(false)
const revokingSessions = ref(false)
const deleting = ref(false)
+const forceDeleting = ref(false)
const cancellingDeletion = ref(false)
const workspaces = ref<AdminWorkspace[]>([])
const plans = ref<Plan[]>([])
@@ -104,6 +105,28 @@ async function handleDeleteUser() {
}
}
+async function handleForceDeleteUser() {
+ if (!metrics.value) return
+ const confirmed = await confirm({
+ title: 'Force Delete User',
+ message: `Are you sure you want to permanently delete "${metrics.value.user.email}"? This will immediately remove the user and all their data. This action cannot be undone.`,
+ confirmText: 'Force Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ forceDeleting.value = true
+ try {
+ await adminApi.forceDeleteUser(metrics.value.user.id)
+ notification.success('User permanently deleted.')
+ router.push('/admin/users')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to force delete user'
+ notification.error(message)
+ } finally {
+ forceDeleting.value = false
+ }
+}
+
async function handleCancelDeletion() {
if (!metrics.value) return
cancellingDeletion.value = true
@@ -275,8 +298,16 @@ function formatDate(date: string) {
>
{{ deleting ? 'Deleting...' : 'Delete User' }}
</button>
+ <button
+ v-if="!metrics.user.active"
+ class="btn btn-danger"
+ :disabled="forceDeleting"
+ @click="handleForceDeleteUser"
+ >
+ {{ forceDeleting ? 'Deleting...' : 'Force Delete' }}
+ </button>
<span style="color: var(--color-text-muted); font-size: 0.875rem;">
- The account will be disabled and permanently deleted after 7 days.
+ {{ metrics.user.active ? 'The account will be disabled and permanently deleted after 7 days.' : 'Force delete will permanently remove the user and all their data immediately.' }}
</span>
</div>
</div>
diff --git a/web/src/views/admin/Users.vue b/web/src/views/admin/Users.vue
index 37b74f3..1c19c2b 100644
--- a/web/src/views/admin/Users.vue
+++ b/web/src/views/admin/Users.vue
@@ -138,6 +138,24 @@ async function deleteUser(user: User) {
notify.error(message)
}
}
+async function forceDeleteUser(user: User) {
+ const confirmed = await confirm({
+ title: 'Force Delete User',
+ message: `Are you sure you want to permanently delete "${user.email}"? This will immediately remove the user and all their data. This action cannot be undone.`,
+ confirmText: 'Force Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await adminApi.forceDeleteUser(user.id)
+ notify.success('User permanently deleted.')
+ await loadUsers()
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to force delete user'
+ notify.error(message)
+ }
+}
+
const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
cancelEdit()
});
@@ -229,6 +247,7 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
{{ user.active ? 'Disable' : 'Enable' }}
</button>
<button class="btn btn-sm btn-danger" @click="deleteUser(user)">Delete</button>
+ <button v-if="!user.active" class="btn btn-sm btn-danger" @click="forceDeleteUser(user)">Force Delete</button>
</td>
</tr>
</tbody>
diff --git a/web/src/views/auth/Profile.vue b/web/src/views/auth/Profile.vue
index 0a9d6a3..d07d44c 100644
--- a/web/src/views/auth/Profile.vue
+++ b/web/src/views/auth/Profile.vue
@@ -1,12 +1,13 @@
<script setup lang="ts">
-import { ref, onMounted } from 'vue'
+import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { authApi } from '../../api/auth'
+import { oauthApi } from '../../api/oauth'
import { sessionsApi, type Session } from '../../api/sessions'
import { useAuthStore } from '../../stores/auth'
import { useNotificationStore } from '../../stores/notification'
import { useConfirm } from '../../composables/useConfirm'
-import type { Plan } from '../../api/types'
+import type { Plan, OAuthLinkedAccount, OAuthProviderInfo } from '../../api/types'
const auth = useAuthStore()
const notify = useNotificationStore()
const { confirm } = useConfirm()
@@ -24,6 +25,17 @@ const deletionLoading = ref(false)
const userPlan = ref<Plan | null>(null)
const planLoading = ref(false)
+// Linked OAuth Accounts
+const linkedAccounts = ref<OAuthLinkedAccount[]>([])
+const oauthProviders = ref<OAuthProviderInfo[]>([])
+const oauthLoading = ref(false)
+const unlinkingAccount = ref<number | null>(null)
+
+const availableProviders = computed(() => {
+ const linkedNames = new Set(linkedAccounts.value.map(a => a.provider_name))
+ return oauthProviders.value.filter(p => !linkedNames.has(p.name))
+})
+
function formatLimit(val: number): string {
return val === 0 ? 'Unlimited' : String(val)
}
@@ -45,6 +57,18 @@ onMounted(async () => {
userPlan.value = res.data.data
} catch { /* ignore */ }
finally { planLoading.value = false }
+
+ // Fetch linked OAuth accounts and available providers
+ oauthLoading.value = true
+ try {
+ const [accountsRes, providersRes] = await Promise.all([
+ oauthApi.linkedAccounts(),
+ oauthApi.providers(),
+ ])
+ linkedAccounts.value = accountsRes.data.data || []
+ oauthProviders.value = providersRes.data.data?.providers || []
+ } catch { /* ignore */ }
+ finally { oauthLoading.value = false }
})
async function handleProfileUpdate() {
@@ -67,6 +91,33 @@ async function handleProfileUpdate() {
}
}
+// OAuth account management
+async function unlinkOAuthAccount(account: OAuthLinkedAccount) {
+ const confirmed = await confirm({
+ title: 'Unlink Account',
+ message: `Unlink your ${account.provider_name} account (${account.email})?`,
+ confirmText: 'Unlink',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+
+ unlinkingAccount.value = account.id
+ try {
+ await oauthApi.unlink(account.provider_id)
+ linkedAccounts.value = linkedAccounts.value.filter(a => a.id !== account.id)
+ notify.success(`${account.provider_name} account unlinked`)
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to unlink account'
+ notify.error(message)
+ } finally {
+ unlinkingAccount.value = null
+ }
+}
+
+function linkOAuthProvider(slug: string) {
+ window.location.href = `/api/v1/auth/oauth/${slug}/authorize`
+}
+
// Password
const currentPassword = ref('')
const newPassword = ref('')
@@ -461,6 +512,51 @@ onMounted(() => { loadSessions() })
</div>
</div>
+ <!-- Linked OAuth Accounts -->
+ <div class="card" v-if="oauthProviders.length > 0 || linkedAccounts.length > 0">
+ <div class="card-header"><h2>Linked Accounts</h2></div>
+ <div class="card-body">
+ <div v-if="oauthLoading" style="text-align: center; padding: 20px 0"><div class="spinner"></div></div>
+ <template v-else>
+ <div v-if="linkedAccounts.length > 0" class="session-list" style="margin-bottom: 16px">
+ <div v-for="account in linkedAccounts" :key="account.id" class="session-item">
+ <div class="session-info">
+ <div class="session-browser">
+ {{ account.provider_name }}
+ <span class="badge badge-neutral" style="margin-left: 6px">{{ account.provider_type }}</span>
+ </div>
+ <div class="session-meta">{{ account.email }}</div>
+ </div>
+ <button
+ class="btn btn-danger btn-sm"
+ :disabled="unlinkingAccount === account.id"
+ @click="unlinkOAuthAccount(account)"
+ >
+ {{ unlinkingAccount === account.id ? 'Unlinking...' : 'Unlink' }}
+ </button>
+ </div>
+ </div>
+ <div v-else class="text-muted" style="font-size: 13px; margin-bottom: 16px">
+ No linked accounts.
+ </div>
+
+ <div v-if="availableProviders.length > 0">
+ <p class="tfa-description">Link an additional login method to your account:</p>
+ <div style="display: flex; gap: 8px; flex-wrap: wrap">
+ <button
+ v-for="provider in availableProviders"
+ :key="provider.slug"
+ class="btn btn-secondary"
+ @click="linkOAuthProvider(provider.slug)"
+ >
+ Link {{ provider.name }}
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+ </div>
+
<!-- Active Sessions -->
<div class="card">
<div class="card-header">
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index 5de1ed1..bee6b93 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -2,7 +2,8 @@
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { workspaceApi } from '../../api/workspaces'
-import type { Workspace, WorkspaceMember, WorkspaceInvitation, WorkspaceRole, TransferResult, Plan } from '../../api/types'
+import { oauthApi } from '../../api/oauth'
+import type { Workspace, WorkspaceMember, WorkspaceInvitation, WorkspaceRole, TransferResult, Plan, OAuthProviderInfo, WorkspaceSSOConfig } from '../../api/types'
import { useNotificationStore } from '../../stores/notification'
import { useWorkspaceStore } from '../../stores/workspace'
import { useConfirm } from '../../composables/useConfirm'
@@ -18,7 +19,7 @@ const ws = ref<Workspace | null>(null)
const loading = ref(true)
// Tabs
-const activeTab = ref<'members' | 'invitations' | 'plan' | 'transfer' | 'settings'>('members')
+const activeTab = ref<'members' | 'invitations' | 'plan' | 'sso' | 'transfer' | 'settings'>('members')
// Members
const members = ref<WorkspaceMember[]>([])
@@ -33,6 +34,13 @@ const currentPlan = ref<Plan | null>(null)
const planLoading = ref(false)
const planSource = ref<string | null>(null)
+// SSO
+const ssoConfig = ref<WorkspaceSSOConfig | null>(null)
+const ssoProviders = ref<OAuthProviderInfo[]>([])
+const ssoLoading = ref(false)
+const ssoSaving = ref(false)
+const ssoForm = ref({ provider_id: 0, enforce_sso: false, auto_provision: true, allowed_domains: '' })
+
// Invite modal
const showInviteModal = ref(false)
const inviteEmail = ref('')
@@ -153,6 +161,69 @@ async function fetchPlan() {
}
}
+async function fetchSSO() {
+ const prevWs = wsStore.currentWorkspaceId
+ wsStore.setWorkspace(wsId)
+ ssoLoading.value = true
+ try {
+ const [ssoRes, providersRes] = await Promise.all([
+ oauthApi.getSSO(),
+ oauthApi.providers(),
+ ])
+ ssoConfig.value = ssoRes.data.data
+ ssoProviders.value = providersRes.data.data?.providers || []
+ if (ssoConfig.value) {
+ ssoForm.value = {
+ provider_id: ssoConfig.value.provider_id,
+ enforce_sso: ssoConfig.value.enforce_sso,
+ auto_provision: ssoConfig.value.auto_provision,
+ allowed_domains: ssoConfig.value.allowed_domains || '',
+ }
+ }
+ } catch { /* ignore */ }
+ finally {
+ ssoLoading.value = false
+ wsStore.setWorkspace(prevWs)
+ }
+}
+
+async function saveSSO() {
+ if (!ssoForm.value.provider_id) {
+ notify.error('Please select a provider')
+ return
+ }
+ const prevWs = wsStore.currentWorkspaceId
+ wsStore.setWorkspace(wsId)
+ ssoSaving.value = true
+ try {
+ await oauthApi.setSSO(ssoForm.value)
+ notify.success('SSO configuration saved')
+ await fetchSSO()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to save SSO config')
+ } finally {
+ ssoSaving.value = false
+ wsStore.setWorkspace(prevWs)
+ }
+}
+
+async function removeSSO() {
+ const ok = await confirm({ title: 'Remove SSO', message: 'Remove SSO configuration from this workspace? Members will no longer be required to use SSO.', confirmText: 'Remove SSO', variant: 'danger' })
+ if (!ok) return
+ const prevWs = wsStore.currentWorkspaceId
+ wsStore.setWorkspace(wsId)
+ try {
+ await oauthApi.deleteSSO()
+ ssoConfig.value = null
+ ssoForm.value = { provider_id: 0, enforce_sso: false, auto_provision: true, allowed_domains: '' }
+ notify.success('SSO configuration removed')
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to remove SSO config')
+ } finally {
+ wsStore.setWorkspace(prevWs)
+ }
+}
+
function formatLimit(value: number): string {
return value === 0 ? 'Unlimited' : value.toLocaleString()
}
@@ -402,6 +473,9 @@ onMounted(async () => {
<button :class="['tab', { active: activeTab === 'plan' }]" @click="activeTab = 'plan'">
Plan
</button>
+ <button v-if="isOwner" :class="['tab', { active: activeTab === 'sso' }]" @click="activeTab = 'sso'; fetchSSO()">
+ SSO
+ </button>
<button v-if="isAdminOrOwner" :class="['tab', { active: activeTab === 'transfer' }]" @click="activeTab = 'transfer'">
Data Transfer
</button>
@@ -596,6 +670,65 @@ onMounted(async () => {
</div>
</div>
+ <!-- SSO Tab -->
+ <div v-if="activeTab === 'sso' && isOwner">
+ <div v-if="ssoLoading" class="loading-page"><div class="spinner"></div></div>
+ <template v-else>
+ <div class="card">
+ <div class="card-header">
+ <h3 style="margin: 0">Single Sign-On (SSO)</h3>
+ <button v-if="ssoConfig" class="btn btn-danger btn-sm" @click="removeSSO">Remove SSO</button>
+ </div>
+ <div class="card-body">
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 16px;">
+ Configure SSO to allow workspace members to authenticate using an OAuth provider.
+ </p>
+
+ <div v-if="ssoProviders.length === 0" class="empty-state" style="padding: 24px 0">
+ <h3>No OAuth providers available</h3>
+ <p>An administrator must configure OAuth providers before SSO can be enabled.</p>
+ </div>
+
+ <form v-else @submit.prevent="saveSSO" style="display: grid; gap: 16px; max-width: 480px;">
+ <div class="form-group">
+ <label class="form-label">OAuth Provider</label>
+ <select v-model.number="ssoForm.provider_id" class="form-select" required>
+ <option :value="0" disabled>Select a provider</option>
+ <option v-for="p in ssoProviders" :key="p.slug" :value="p.id">{{ p.name }} ({{ p.type }})</option>
+ </select>
+ </div>
+
+ <div class="form-group">
+ <label class="form-label">Allowed Domains</label>
+ <input v-model="ssoForm.allowed_domains" type="text" class="form-input" placeholder="example.com, company.org" />
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">Comma-separated email domains. Leave empty to allow all domains.</small>
+ </div>
+
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
+ <input type="checkbox" v-model="ssoForm.enforce_sso" />
+ <span>Enforce SSO</span>
+ </label>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">Require all workspace members to authenticate via SSO.</small>
+ </div>
+
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
+ <input type="checkbox" v-model="ssoForm.auto_provision" />
+ <span>Auto-provision users</span>
+ </label>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">Automatically create accounts for new users who authenticate via SSO.</small>
+ </div>
+
+ <button type="submit" class="btn btn-primary" :disabled="ssoSaving" style="justify-self: start;">
+ {{ ssoSaving ? 'Saving...' : (ssoConfig ? 'Update SSO' : 'Enable SSO') }}
+ </button>
+ </form>
+ </div>
+ </div>
+ </template>
+ </div>
+
<!-- Data Transfer Tab -->
<div v-if="activeTab === 'transfer' && isAdminOrOwner" class="card">
<div class="card-header"><span>Transfer Personal Data to Workspace</span></div>