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 user account Plan

Jonas Kaninda38d078e9869e
diff --git a/internal/handlers/plan_handler.go b/internal/handlers/plan_handler.go
index 65a8a34..1528784 100644
--- a/internal/handlers/plan_handler.go
+++ b/internal/handlers/plan_handler.go
@@ -34,6 +34,7 @@ import (
type PlanHandler struct {
planRepo *repositories.PlanRepository
workspaceRepo *repositories.WorkspaceRepository
+ userRepo *repositories.UserRepository
planService *planpkg.Service
audit *audit.Logger
}
@@ -41,12 +42,14 @@ type PlanHandler struct {
func NewPlanHandler(
planRepo *repositories.PlanRepository,
workspaceRepo *repositories.WorkspaceRepository,
+ userRepo *repositories.UserRepository,
planService *planpkg.Service,
audit *audit.Logger,
) *PlanHandler {
return &PlanHandler{
planRepo: planRepo,
workspaceRepo: workspaceRepo,
+ userRepo: userRepo,
planService: planService,
audit: audit,
}
@@ -240,22 +243,34 @@ func (h *PlanHandler) Delete(c *okapi.Context, req *DeletePlanRequest) error {
return c.AbortNotFound("plan not found")
}
- count, err := h.planRepo.CountWorkspaces(plan.ID)
+ wsCount, err := h.planRepo.CountWorkspaces(plan.ID)
if err != nil {
return c.AbortInternalServerError("failed to check plan usage", err)
}
- if count > 0 && !req.Force {
+ userCount, err := h.planRepo.CountUsers(plan.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to check plan usage", err)
+ }
+
+ totalCount := wsCount + userCount
+ if totalCount > 0 && !req.Force {
return c.AbortWithError(http.StatusConflict,
- fmt.Errorf("plan is assigned to %d workspace(s); use ?force=true to delete", count))
+ fmt.Errorf("plan is assigned to %d workspace(s) and %d user(s); use ?force=true to delete", wsCount, userCount))
}
- if count > 0 {
+ if wsCount > 0 {
if err := h.planRepo.UnassignAllFromPlan(plan.ID); err != nil {
return c.AbortInternalServerError("failed to unassign workspaces from plan", err)
}
}
+ if userCount > 0 {
+ if err := h.planRepo.UnassignAllUsersFromPlan(plan.ID); err != nil {
+ return c.AbortInternalServerError("failed to unassign users from plan", err)
+ }
+ }
+
if err := h.planRepo.Delete(plan.ID); err != nil {
return c.AbortInternalServerError("failed to delete plan", err)
}
@@ -335,3 +350,71 @@ func (h *PlanHandler) GetWorkspacePlan(c *okapi.Context, req *WorkspacePlanReque
return ok(c, plan)
}
+
+// AssignUserPlanRequest is the request type for assigning a plan to a user.
+type AssignUserPlanRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ PlanID uint `json:"plan_id" required:"true"`
+ } `json:"body"`
+}
+
+// UserPlanRequest is the request type for getting a user's plan.
+type UserPlanRequest struct {
+ ID int `param:"id"`
+}
+
+// AssignToUser assigns a plan to a user.
+func (h *PlanHandler) AssignToUser(c *okapi.Context, req *AssignUserPlanRequest) error {
+ adminID := uint(c.GetInt("user_id"))
+
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ plan, err := h.planRepo.FindByID(req.Body.PlanID)
+ if err != nil {
+ return c.AbortNotFound("plan not found")
+ }
+
+ if !plan.IsActive {
+ return c.AbortWithError(http.StatusBadRequest, fmt.Errorf("cannot assign inactive plan"))
+ }
+
+ if err := h.planRepo.AssignToUser(user.ID, plan.ID); err != nil {
+ return c.AbortInternalServerError("failed to assign plan to user", err)
+ }
+
+ h.audit.Log(adminID, c.GetString("email"), c.RealIP(), "plan.user_assigned",
+ fmt.Sprintf("Plan '%s' assigned to user '%s'", plan.Name, user.Email), nil)
+
+ return ok(c, dto.MessageData{Message: fmt.Sprintf("plan '%s' assigned to user '%s'", plan.Name, user.Email)})
+}
+
+// GetUserPlan returns the effective plan for a user (admin view).
+func (h *PlanHandler) GetUserPlan(c *okapi.Context, req *UserPlanRequest) error {
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ plan := h.planService.EffectiveUserPlan(user.ID)
+ if plan == nil {
+ return ok(c, okapi.M{"plan": nil, "source": "global_settings"})
+ }
+
+ return ok(c, plan)
+}
+
+// GetMyPlan returns the effective plan for the authenticated user.
+func (h *PlanHandler) GetMyPlan(c *okapi.Context) error {
+ userID := uint(c.GetInt("user_id"))
+
+ plan := h.planService.EffectiveUserPlan(userID)
+ if plan == nil {
+ return ok(c, okapi.M{"plan": nil, "source": "global_settings"})
+ }
+
+ return ok(c, plan)
+}
diff --git a/internal/models/user.go b/internal/models/user.go
index dad0b31..14cfe54 100644
--- a/internal/models/user.go
+++ b/internal/models/user.go
@@ -38,9 +38,12 @@ type User struct {
RequireVerifiedDomain bool `json:"require_verified_domain" gorm:"default:false"`
AuthMethod string `json:"auth_method" gorm:"default:'password';not null"`
AvatarURL string `json:"avatar_url"`
+ PlanID *uint `json:"plan_id" gorm:"index"`
ScheduledDeletionAt *time.Time `json:"scheduled_deletion_at"`
CreatedAt time.Time `json:"created_at"`
LastLoginAt *time.Time `json:"last_login_at"`
+
+ Plan Plan `json:"-" gorm:"foreignKey:PlanID"`
}
func (u *User) IsAdmin() bool {
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 6d601e3..0f18be1 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -150,6 +150,35 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
},
},
+ // ==================== User Plans ====================
+ {
+ Method: http.MethodPost,
+ Path: "/users/{id:int}/plan",
+ Handler: okapi.H(r.h.plan.AssignToUser),
+ Group: adminGroup,
+ Summary: "Assign plan to user",
+ Description: "Assign a usage plan to a user account",
+ Request: &handlers.AssignUserPlanRequest{},
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/users/{id:int}/plan",
+ Handler: okapi.H(r.h.plan.GetUserPlan),
+ Group: adminGroup,
+ Summary: "Get user plan",
+ Description: "Get the effective plan for a user",
+ Response: &dto.Response[models.Plan]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
// ==================== Events ====================
{
Method: http.MethodGet,
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 7474bbb..8337c35 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -239,7 +239,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.admin.SetSessionRepo(sessionRepo, sessionStore)
// Plans
- r.h.plan = handlers.NewPlanHandler(planRepo, workspaceRepo, planService, auditLogger)
+ r.h.plan = handlers.NewPlanHandler(planRepo, workspaceRepo, userRepo, planService, auditLogger)
r.h.admin.SetWorkspaceRepo(workspaceRepo, planRepo)
r.h.workspace.SetPlanService(planService)
r.h.apiKey.SetQuota(planService, db)
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index 28c23d8..2471c36 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -63,6 +63,17 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Response: &dto.Response[dto.MessageData]{},
},
+ // ==================== Plan ====================
+ {
+ Method: http.MethodGet,
+ Path: "/plan",
+ Handler: r.h.plan.GetMyPlan,
+ Group: userGroup,
+ Summary: "Get my plan",
+ Description: "Get the effective plan for the authenticated user",
+ Response: &dto.Response[models.Plan]{},
+ },
+
// ==================== 2FA ====================
{
Method: http.MethodPost,
diff --git a/internal/services/plan/service.go b/internal/services/plan/service.go
index 10ec704..3b63690 100644
--- a/internal/services/plan/service.go
+++ b/internal/services/plan/service.go
@@ -99,6 +99,38 @@ func (s *Service) EffectivePlan(workspaceID *uint) *models.Plan {
return nil
}
+// EffectiveUserPlan returns the plan assigned to the user, the default plan,
+// or nil if no plan applies.
+func (s *Service) EffectiveUserPlan(userID uint) *models.Plan {
+ plan, err := s.planRepo.FindByUserID(userID)
+ if err == nil && plan.IsActive {
+ return plan
+ }
+ plan, err = s.planRepo.FindDefault()
+ if err == nil {
+ return plan
+ }
+ return nil
+}
+
+// EffectiveLimitsForUser resolves the limits for a given user.
+// Priority: user plan -> default plan -> global settings.
+func (s *Service) EffectiveLimitsForUser(userID uint) *Limits {
+ plan, err := s.planRepo.FindByUserID(userID)
+ if err == nil && plan.IsActive {
+ return limitsFromPlan(plan)
+ }
+
+ // Try the default plan.
+ plan, err = s.planRepo.FindDefault()
+ if err == nil {
+ return limitsFromPlan(plan)
+ }
+
+ // Fallback to global settings.
+ return s.limitsFromSettings()
+}
+
// CheckQuota verifies that creating one more resource of the given type
// would not exceed the plan limit. Returns nil if within limit.
func (s *Service) CheckQuota(db *gorm.DB, userID uint, workspaceID *uint, resource string) error {
@@ -143,20 +175,9 @@ func (s *Service) CheckQuota(db *gorm.DB, userID uint, workspaceID *uint, resour
}
// CheckWorkspaceQuota verifies that the user has not exceeded their max_workspaces limit.
-// This counts all workspaces owned by the user.
+// This counts all workspaces owned by the user and checks against the user's plan.
func (s *Service) CheckWorkspaceQuota(db *gorm.DB, userID uint) error {
- // For workspace quota, we use the default plan since the user may not
- // have a workspace yet. If they have one, use that workspace's plan.
- var limits *Limits
-
- // Check if user owns any workspace with a plan.
- var ws models.Workspace
- err := db.Where("owner_id = ? AND plan_id IS NOT NULL", userID).First(&ws).Error
- if err == nil {
- limits = s.EffectiveLimits(ws.PlanID)
- } else {
- limits = s.EffectiveLimits(nil)
- }
+ limits := s.EffectiveLimitsForUser(userID)
if limits.MaxWorkspaces == 0 {
return nil // unlimited
diff --git a/internal/storage/repositories/plan_repo.go b/internal/storage/repositories/plan_repo.go
index 3a4ccde..9f59f61 100644
--- a/internal/storage/repositories/plan_repo.go
+++ b/internal/storage/repositories/plan_repo.go
@@ -124,6 +124,46 @@ func (r *PlanRepository) UnassignAllFromPlan(planID uint) error {
return r.db.Model(&models.Workspace{}).Where("plan_id = ?", planID).Update("plan_id", nil).Error
}
+// FindByUserID returns the plan assigned to the given user.
+func (r *PlanRepository) FindByUserID(userID uint) (*models.Plan, error) {
+ var user models.User
+ if err := r.db.First(&user, userID).Error; err != nil {
+ return nil, err
+ }
+ if user.PlanID == nil {
+ return nil, gorm.ErrRecordNotFound
+ }
+ var plan models.Plan
+ if err := r.db.First(&plan, *user.PlanID).Error; err != nil {
+ return nil, err
+ }
+ return &plan, nil
+}
+
+// AssignToUser sets the plan_id on the given user.
+func (r *PlanRepository) AssignToUser(userID, planID uint) error {
+ return r.db.Model(&models.User{}).Where("id = ?", userID).Update("plan_id", planID).Error
+}
+
+// UnassignFromUser removes the plan assignment from the given user.
+func (r *PlanRepository) UnassignFromUser(userID uint) error {
+ return r.db.Model(&models.User{}).Where("id = ?", userID).Update("plan_id", nil).Error
+}
+
+// CountUsers returns the number of users assigned to the given plan.
+func (r *PlanRepository) CountUsers(planID uint) (int64, error) {
+ var count int64
+ if err := r.db.Model(&models.User{}).Where("plan_id = ?", planID).Count(&count).Error; err != nil {
+ return 0, err
+ }
+ return count, nil
+}
+
+// UnassignAllUsersFromPlan removes plan assignment from all users using the given plan.
+func (r *PlanRepository) UnassignAllUsersFromPlan(planID uint) error {
+ return r.db.Model(&models.User{}).Where("plan_id = ?", planID).Update("plan_id", nil).Error
+}
+
// DB returns the underlying database connection for use in transactions.
func (r *PlanRepository) DB() *gorm.DB {
return r.db
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
index 0e1907f..9ddb2a1 100644
--- a/web/src/api/auth.ts
+++ b/web/src/api/auth.ts
@@ -1,5 +1,5 @@
import api from './client'
-import type { ApiResponse, AuthResponse, UserProfile, Setup2FAResponse } from './types'
+import type { ApiResponse, AuthResponse, UserProfile, Setup2FAResponse, Plan } from './types'
export const authApi = {
login(email: string, password: string, twoFactorCode?: string) {
@@ -40,4 +40,7 @@ export const authApi = {
registrationStatus() {
return api.get<ApiResponse<{ registration_enabled: boolean }>>('/auth/registration-status')
},
+ getMyPlan() {
+ return api.get<ApiResponse<Plan | null>>('/users/me/plan')
+ },
}
diff --git a/web/src/api/plans.ts b/web/src/api/plans.ts
index 1c7c669..0f088d4 100644
--- a/web/src/api/plans.ts
+++ b/web/src/api/plans.ts
@@ -26,4 +26,10 @@ export const plansApi = {
getWorkspacePlan(workspaceId: number) {
return api.get<ApiResponse<Plan | null>>(`/admin/workspaces/${workspaceId}/plan`)
},
+ assignToUser(userId: number, planId: number) {
+ return api.post<ApiResponse<{ message: string }>>(`/admin/users/${userId}/plan`, { plan_id: planId })
+ },
+ getUserPlan(userId: number) {
+ return api.get<ApiResponse<Plan | null>>(`/admin/users/${userId}/plan`)
+ },
}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 774ba76..4c1fbfc 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -34,6 +34,7 @@ export interface User {
active: boolean
two_factor_enabled: boolean
auth_method: string
+ plan_id: number | null
scheduled_deletion_at: string | null
created_at: string
last_login_at: string | null
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
index 49be1e8..4649fff 100644
--- a/web/src/views/admin/UserDetail.vue
+++ b/web/src/views/admin/UserDetail.vue
@@ -20,6 +20,7 @@ const cancellingDeletion = ref(false)
const workspaces = ref<AdminWorkspace[]>([])
const plans = ref<Plan[]>([])
const changingPlan = ref<number | null>(null)
+const changingUserPlan = ref(false)
onMounted(async () => {
try {
@@ -119,6 +120,22 @@ async function handleCancelDeletion() {
}
}
+async function handleChangeUserPlan(planId: number | null) {
+ if (!metrics.value) return
+ changingUserPlan.value = true
+ try {
+ if (planId) {
+ await plansApi.assignToUser(metrics.value.user.id, planId)
+ metrics.value.user.plan_id = planId
+ notification.success('User plan updated.')
+ }
+ } catch {
+ notification.error('Failed to update user plan.')
+ } finally {
+ changingUserPlan.value = false
+ }
+}
+
async function handleChangePlan(workspace: AdminWorkspace, planId: number | null) {
changingPlan.value = workspace.id
try {
@@ -317,6 +334,33 @@ function formatDate(date: string) {
</div>
</div>
+ <!-- User Plan -->
+ <div class="card" style="margin-top: 24px;">
+ <div class="card-header">
+ <h2>Account Plan</h2>
+ </div>
+ <div class="card-body">
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
+ The account plan determines how many workspaces this user can create.
+ </p>
+ <div style="display: flex; align-items: center; gap: 12px;">
+ <label style="font-weight: 600; font-size: 14px;">Plan:</label>
+ <select
+ class="form-select"
+ style="max-width: 300px;"
+ :value="metrics.user.plan_id || ''"
+ :disabled="changingUserPlan"
+ @change="handleChangeUserPlan(Number($event.target.value) || null)"
+ >
+ <option value="">No plan (use default)</option>
+ <option v-for="plan in plans" :key="plan.id" :value="plan.id">
+ {{ plan.name }}{{ !plan.is_active ? ' (inactive)' : '' }}{{ plan.is_default ? ' (default)' : '' }}
+ </option>
+ </select>
+ </div>
+ </div>
+ </div>
+
<!-- Workspaces Section -->
<div class="card" style="margin-top: 24px;">
<div class="card-header">
diff --git a/web/src/views/auth/Profile.vue b/web/src/views/auth/Profile.vue
index cd25c2a..0a9d6a3 100644
--- a/web/src/views/auth/Profile.vue
+++ b/web/src/views/auth/Profile.vue
@@ -6,6 +6,7 @@ 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'
const auth = useAuthStore()
const notify = useNotificationStore()
const { confirm } = useConfirm()
@@ -19,6 +20,14 @@ const twoFactorEnabled = ref(false)
const scheduledDeletionAt = ref<string | null>(null)
const deletionLoading = ref(false)
+// Plan
+const userPlan = ref<Plan | null>(null)
+const planLoading = ref(false)
+
+function formatLimit(val: number): string {
+ return val === 0 ? 'Unlimited' : String(val)
+}
+
onMounted(async () => {
name.value = auth.user?.name || ''
email.value = auth.user?.email || ''
@@ -28,6 +37,14 @@ onMounted(async () => {
twoFactorEnabled.value = res.data.data.two_factor_enabled
scheduledDeletionAt.value = res.data.data.scheduled_deletion_at
} catch { /* ignore */ }
+
+ // Fetch user plan
+ planLoading.value = true
+ try {
+ const res = await authApi.getMyPlan()
+ userPlan.value = res.data.data
+ } catch { /* ignore */ }
+ finally { planLoading.value = false }
})
async function handleProfileUpdate() {
@@ -319,6 +336,45 @@ onMounted(() => { loadSessions() })
</div>
</div>
+ <!-- My Plan -->
+ <div class="card">
+ <div class="card-header"><h2>My Plan</h2></div>
+ <div class="card-body">
+ <div v-if="planLoading" style="text-align: center; padding: 20px 0"><div class="spinner"></div></div>
+ <template v-else-if="userPlan">
+ <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 16px">
+ <h3 style="margin: 0; font-size: 16px">{{ userPlan.name }}</h3>
+ <span class="badge badge-success" v-if="userPlan.is_active">Active</span>
+ <span class="badge badge-info" v-if="userPlan.is_default">Default</span>
+ </div>
+ <p v-if="userPlan.description" style="margin: 0 0 16px; font-size: 13px; color: var(--text-secondary)">{{ userPlan.description }}</p>
+ <div class="plan-limits-grid">
+ <div class="plan-limit-group">
+ <h4 class="plan-limit-title">Rate Limits</h4>
+ <div class="plan-limit-row"><span>Hourly</span><span>{{ formatLimit(userPlan.hourly_rate_limit) }}</span></div>
+ <div class="plan-limit-row"><span>Daily</span><span>{{ formatLimit(userPlan.daily_rate_limit) }}</span></div>
+ </div>
+ <div class="plan-limit-group">
+ <h4 class="plan-limit-title">Resource Limits</h4>
+ <div class="plan-limit-row"><span>Workspaces</span><span>{{ formatLimit(userPlan.max_workspaces) }}</span></div>
+ <div class="plan-limit-row"><span>API Keys</span><span>{{ formatLimit(userPlan.max_api_keys) }}</span></div>
+ <div class="plan-limit-row"><span>Domains</span><span>{{ formatLimit(userPlan.max_domains) }}</span></div>
+ <div class="plan-limit-row"><span>SMTP Servers</span><span>{{ formatLimit(userPlan.max_smtp_servers) }}</span></div>
+ </div>
+ <div class="plan-limit-group">
+ <h4 class="plan-limit-title">Email Constraints</h4>
+ <div class="plan-limit-row"><span>Attachment</span><span>{{ userPlan.max_attachment_size_mb === 0 ? 'Unlimited' : userPlan.max_attachment_size_mb + ' MB' }}</span></div>
+ <div class="plan-limit-row"><span>Batch Size</span><span>{{ formatLimit(userPlan.max_batch_size) }}</span></div>
+ <div class="plan-limit-row"><span>Log Retention</span><span>{{ userPlan.email_log_retention_days === 0 ? 'Default' : userPlan.email_log_retention_days + ' days' }}</span></div>
+ </div>
+ </div>
+ </template>
+ <div v-else class="text-muted" style="font-size: 13px">
+ No plan assigned. Your account is using the platform's global default settings.
+ </div>
+ </div>
+ </div>
+
<!-- Two-Factor Authentication -->
<div class="card">
<div class="card-header">
@@ -630,4 +686,38 @@ onMounted(() => { loadSessions() })
color: var(--danger-600, #dc2626);
margin: 0;
}
+
+.plan-limits-grid {
+ display: grid;
+ gap: 16px;
+}
+
+.plan-limit-group {
+ padding: 12px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+}
+
+.plan-limit-title {
+ margin: 0 0 8px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text-secondary);
+}
+
+.plan-limit-row {
+ display: flex;
+ justify-content: space-between;
+ padding: 4px 0;
+ font-size: 13px;
+}
+
+.plan-limit-row span:first-child {
+ color: var(--text-secondary);
+}
+
+.plan-limit-row span:last-child {
+ font-weight: 500;
+}
</style>