mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 16:06:08 +00:00
2226 lines
84 KiB
Go
2226 lines
84 KiB
Go
package organization
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/mail"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/warmbly/warmbly/internal/app/dailythrottle"
|
|
"github.com/warmbly/warmbly/internal/app/feature"
|
|
"github.com/warmbly/warmbly/internal/app/tz"
|
|
"github.com/warmbly/warmbly/internal/config"
|
|
"github.com/warmbly/warmbly/internal/errx"
|
|
"github.com/warmbly/warmbly/internal/models"
|
|
"github.com/warmbly/warmbly/internal/observability/errs"
|
|
"github.com/warmbly/warmbly/internal/pkg/crypt"
|
|
"github.com/warmbly/warmbly/internal/pkg/displayname"
|
|
"github.com/warmbly/warmbly/internal/repository"
|
|
)
|
|
|
|
const (
|
|
// InvitationTTL is the invitation expiration used when no instance
|
|
// settings service is wired; the operator's value overrides it.
|
|
InvitationTTL = 48 * time.Hour
|
|
|
|
// InvitationTokenLength is the length of invitation tokens
|
|
InvitationTokenLength = 32
|
|
)
|
|
|
|
// InstanceSettings is the operator-editable half of the invite flow. Satisfied
|
|
// by instancesettings.Service; injected post-construction so this package needs
|
|
// no import of it (no cycle).
|
|
type InstanceSettings interface {
|
|
InvitationTTL(ctx context.Context) time.Duration
|
|
InviteLinksEnabled(ctx context.Context) bool
|
|
}
|
|
|
|
// OperatorNotifier is the instance-wide operator alert surface, injected
|
|
// post-construction so this package needs no import of it. Nil disables every
|
|
// alert below; a deployment with no channels configured is the normal case.
|
|
type OperatorNotifier interface {
|
|
NotifyOperator(key, title, summary string, fields map[string]string)
|
|
}
|
|
|
|
// OrganizationService defines the interface for organization management
|
|
type OrganizationService interface {
|
|
CreateTesterWorkspace(ctx context.Context, userID, adminID uuid.UUID, name, reason string, until time.Time) (*models.Organization, *errx.Error)
|
|
SeedTesterWorkspace(ctx context.Context, orgID, adminID uuid.UUID, ip, userAgent string) (*models.TesterSampleData, *errx.Error)
|
|
// WireAuthPolicy attaches the deployment auth policy after construction.
|
|
WireAuthPolicy(p *config.AuthPolicy)
|
|
|
|
// WireOperatorNotifier attaches the operator alert channel.
|
|
WireOperatorNotifier(n OperatorNotifier)
|
|
|
|
// WireInstanceSettings attaches the database-backed instance settings
|
|
// (post-construction; nil keeps the compiled defaults).
|
|
WireInstanceSettings(s InstanceSettings)
|
|
|
|
// WireWorkspaceSeeder attaches a hook that runs once for every new
|
|
// workspace, so premade rows (inbox labels) exist before the first mail.
|
|
WireWorkspaceSeeder(fn func(ctx context.Context, orgID uuid.UUID))
|
|
// WireMemberRemoval attaches a hook that ends a removed member's access, run after every removal.
|
|
WireMemberRemoval(fn func(ctx context.Context, orgID, userID uuid.UUID) error)
|
|
|
|
// CRUD
|
|
Create(ctx context.Context, userID uuid.UUID, name, timezone string) (*models.Organization, *errx.Error)
|
|
CreateAgencyClient(ctx context.Context, userID uuid.UUID, name, timezone string) (*models.Organization, *errx.Error)
|
|
Get(ctx context.Context, orgID uuid.UUID) (*models.Organization, *errx.Error)
|
|
GetBySlug(ctx context.Context, slug string) (*models.Organization, *errx.Error)
|
|
Update(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrganizationRequest) (*models.Organization, *errx.Error)
|
|
Delete(ctx context.Context, orgID uuid.UUID) *errx.Error
|
|
|
|
// User's organizations
|
|
GetUserOrganizations(ctx context.Context, userID uuid.UUID) ([]models.OrganizationMember, *errx.Error)
|
|
GetUserDefaultOrganization(ctx context.Context, userID uuid.UUID) (*models.Organization, *errx.Error)
|
|
|
|
// Member management
|
|
GetMembers(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationMember, *errx.Error)
|
|
GetMembership(ctx context.Context, orgID, userID uuid.UUID) (*models.OrganizationMember, *errx.Error)
|
|
InviteMember(ctx context.Context, orgID uuid.UUID, inviterID uuid.UUID, req *models.InviteMemberRequest) (*models.OrganizationInvitation, *errx.Error)
|
|
// AttachTester joins a tester account to an existing workspace without an
|
|
// invitation. Operator-only: the admin is not a member, so there is no
|
|
// actor permission to check against, and the authority is the
|
|
// manage_testers bit plus the admin audit row the caller writes.
|
|
AttachTester(ctx context.Context, orgID, userID, adminID, roleID uuid.UUID) (*models.OrganizationMember, *errx.Error)
|
|
AcceptInvitation(ctx context.Context, token string, userID uuid.UUID, email string) (*models.OrganizationMember, *errx.Error)
|
|
CreateInvitedUser(ctx context.Context, token string, email *mail.Address, passwordHash string) (*models.User, *models.OrganizationMember, *errx.Error)
|
|
AcceptInvitationByID(ctx context.Context, invitationID, userID uuid.UUID, email string) (*models.OrganizationMember, *errx.Error)
|
|
PreviewInvitation(ctx context.Context, token string) (*models.InvitationPreview, *errx.Error)
|
|
// InvitationOrganization is the workspace an invitation, by token or id, is for; nil when there is none.
|
|
InvitationOrganization(ctx context.Context, token string, invitationID *uuid.UUID) (*uuid.UUID, *errx.Error)
|
|
GetInvitationToken(ctx context.Context, orgID, invitationID uuid.UUID) (string, *errx.Error)
|
|
|
|
// Custom roles
|
|
ListRoles(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationRole, *errx.Error)
|
|
CreateRole(ctx context.Context, orgID, actorID uuid.UUID, req *models.CreateOrganizationRoleRequest) (*models.OrganizationRole, *errx.Error)
|
|
UpdateRole(ctx context.Context, orgID, actorID, roleID uuid.UUID, req *models.UpdateOrganizationRoleRequest) (*models.OrganizationRole, *errx.Error)
|
|
DeleteRole(ctx context.Context, orgID, actorID, roleID uuid.UUID) *errx.Error
|
|
UpdateMemberRole(ctx context.Context, orgID, actorID, memberUserID uuid.UUID, req *models.UpdateMemberRequest) (*models.OrganizationMember, *errx.Error)
|
|
// Resource scope: a restricted member's role applies only to the campaigns, folders and mailboxes granted to them.
|
|
GetMemberAccess(ctx context.Context, orgID, userID uuid.UUID) (*models.MemberAccess, *errx.Error)
|
|
SetMemberAccess(ctx context.Context, orgID, actorID, memberUserID uuid.UUID, access *models.MemberAccess) (*models.OrganizationMember, *errx.Error)
|
|
ResolveMemberScope(ctx context.Context, orgID, userID uuid.UUID) (*models.ResourceScope, *errx.Error)
|
|
SuggestCampaignSenders(ctx context.Context, orgID uuid.UUID, campaignIDs, folderIDs []uuid.UUID) ([]models.SuggestedSender, *errx.Error)
|
|
RemoveMember(ctx context.Context, orgID, actorID, memberUserID uuid.UUID) *errx.Error
|
|
|
|
// Invitations
|
|
GetPendingInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, *errx.Error)
|
|
GetExpiredInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, *errx.Error)
|
|
GetUserPendingInvitations(ctx context.Context, email string) ([]models.OrganizationInvitation, *errx.Error)
|
|
CancelInvitation(ctx context.Context, orgID, invitationID uuid.UUID) *errx.Error
|
|
|
|
// Ownership transfer
|
|
TransferOwnership(ctx context.Context, orgID, actorUserID, newOwnerUserID uuid.UUID) *errx.Error
|
|
|
|
// Permission checks
|
|
HasPermission(ctx context.Context, orgID, userID uuid.UUID, perm models.OrganizationPermission) (bool, *errx.Error)
|
|
RequirePermission(ctx context.Context, orgID, userID uuid.UUID, perm models.OrganizationPermission) *errx.Error
|
|
|
|
// Limit checks
|
|
CanAddMember(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error)
|
|
CanAddCampaign(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error)
|
|
// MailboxAllowance resolves how many mailboxes the workspace may hold and
|
|
// why; every connect path checks it and GET /emails/allowance returns it.
|
|
MailboxAllowance(ctx context.Context, orgID uuid.UUID) (*models.MailboxAllowance, *errx.Error)
|
|
|
|
// GrantManagedPlan / RevokeManagedPlan are the operator-granted plan: paid
|
|
// entitlements without Stripe, for internal workspaces, design partners
|
|
// and support gestures.
|
|
GrantManagedPlan(ctx context.Context, orgID, planID, adminID uuid.UUID, reason string, until *time.Time) (*models.ManagedPlan, *errx.Error)
|
|
RevokeManagedPlan(ctx context.Context, orgID uuid.UUID) (*models.ManagedPlan, *errx.Error)
|
|
GetManagedPlan(ctx context.Context, orgID uuid.UUID) (*models.ManagedPlan, *errx.Error)
|
|
GetCampaignCounts(ctx context.Context, orgID uuid.UUID) (total int, active int, err *errx.Error)
|
|
GetOrganizationLimits(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimits, *errx.Error)
|
|
GetOrganizationCounts(ctx context.Context, orgID uuid.UUID) (*models.OrganizationCounts, *errx.Error)
|
|
GetScopedOrganizationCounts(ctx context.Context, orgID uuid.UUID, scope *models.ResourceScope) (*models.OrganizationCounts, *errx.Error)
|
|
|
|
// Enterprise inquiries
|
|
CreateEnterpriseInquiry(ctx context.Context, inquiry *models.EnterpriseInquiry) (*models.EnterpriseInquiry, *errx.Error)
|
|
|
|
// Admin permissions (for admin middleware)
|
|
GetUserAdminPermissions(ctx context.Context, userID uuid.UUID) (uint32, error)
|
|
|
|
// Admin: read-only org listing for the admin panel. Detail composes
|
|
// the list-shape row with counts, plan defaults, the override row,
|
|
// and the effective limits the runtime actually enforces.
|
|
SearchOrganizationsForAdmin(ctx context.Context, search *models.AdminOrgSearch) (*models.AdminOrgsResult, *errx.Error)
|
|
GetOrganizationAdminDetail(ctx context.Context, orgID uuid.UUID) (*models.AdminOrgDetail, *errx.Error)
|
|
GetOrganizationMembersForAdmin(ctx context.Context, orgID uuid.UUID) ([]models.AdminOrgMember, *errx.Error)
|
|
|
|
// Admin: per-org limit overrides. Read returns nil if the org has
|
|
// never been touched. Set is an upsert that stamps granted_by /
|
|
// granted_at on every write.
|
|
GetLimitOverrides(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimitOverrides, *errx.Error)
|
|
SetLimitOverrides(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrgOverridesRequest, grantedBy uuid.UUID) (*models.OrganizationLimitOverrides, *errx.Error)
|
|
|
|
// Effective limits: plan defaults overlaid with overrides. This is
|
|
// what the in-app limit checks (CanAddMember / Campaign / EmailAccount)
|
|
// compare counts against.
|
|
GetEffectiveLimits(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimits, *errx.Error)
|
|
|
|
// WebhookDispatchLimit returns the org's per-minute cap on webhook +
|
|
// integration fan-out, derived from the org's effective plan limits. Used by
|
|
// the webhook dispatch throttle. Never errors — falls back to the generous
|
|
// base cap so dispatch is never blocked by a limits-lookup failure.
|
|
WebhookDispatchLimit(ctx context.Context, orgID uuid.UUID) int
|
|
|
|
// Limit-increase request workflow. Users self-serve via
|
|
// SubmitLimitIncreaseRequest from the dashboard; admins drain the
|
|
// queue with the AdminListLimitRequests / ApproveLimitRequest /
|
|
// RejectLimitRequest path. Approving rewrites the override row via
|
|
// SetLimitOverrides so the audit story stays unified.
|
|
SubmitLimitIncreaseRequest(ctx context.Context, orgID, submitterID uuid.UUID, req *models.CreateLimitIncreaseRequest) (*models.LimitIncreaseRequest, *errx.Error)
|
|
ListLimitRequestsForOrg(ctx context.Context, orgID, requesterID uuid.UUID) ([]models.LimitIncreaseRequest, *errx.Error)
|
|
CancelLimitRequest(ctx context.Context, id, userID uuid.UUID) *errx.Error
|
|
AdminListLimitRequests(ctx context.Context, search *models.AdminLimitRequestSearch) (*models.AdminLimitRequestsResult, *errx.Error)
|
|
ApproveLimitRequest(ctx context.Context, id, reviewerID uuid.UUID, notes string) (*models.LimitIncreaseRequest, *errx.Error)
|
|
RejectLimitRequest(ctx context.Context, id, reviewerID uuid.UUID, notes string) (*models.LimitIncreaseRequest, *errx.Error)
|
|
}
|
|
|
|
type organizationService struct {
|
|
orgRepo repository.OrganizationRepository
|
|
subRepo repository.SubscriptionRepository
|
|
userRepo repository.UserRepository
|
|
// planRepo validates a granted plan id before it is written, so a typo is
|
|
// a 400 naming the problem rather than a foreign-key violation.
|
|
planRepo repository.PlanRepository
|
|
throttle dailythrottle.Service
|
|
// gate is the sender's own entitlement check, so reported limits match what is enforced.
|
|
gate feature.FeatureGateService
|
|
// authPolicy is wired after construction, because the policy is loaded
|
|
// alongside the mail transport and not available at this call site.
|
|
authPolicy *config.AuthPolicy
|
|
// settings is the operator-editable invite configuration, wired after
|
|
// construction because it needs the database pool.
|
|
settings InstanceSettings
|
|
// opsNotify raises instance-wide operator alerts. Nil is the default.
|
|
opsNotify OperatorNotifier
|
|
// seeders run after a workspace is created, best-effort.
|
|
seeders []func(ctx context.Context, orgID uuid.UUID)
|
|
// removals end a removed member's sessions and grants; the auth middleware backs them up.
|
|
removals []func(ctx context.Context, orgID, userID uuid.UUID) error
|
|
}
|
|
|
|
func (s *organizationService) WireWorkspaceSeeder(fn func(ctx context.Context, orgID uuid.UUID)) {
|
|
if fn != nil {
|
|
s.seeders = append(s.seeders, fn)
|
|
}
|
|
}
|
|
|
|
func (s *organizationService) WireMemberRemoval(fn func(ctx context.Context, orgID, userID uuid.UUID) error) {
|
|
if fn != nil {
|
|
s.removals = append(s.removals, fn)
|
|
}
|
|
}
|
|
|
|
// WireOperatorNotifier attaches the operator alert channel.
|
|
func (s *organizationService) WireOperatorNotifier(n OperatorNotifier) {
|
|
s.opsNotify = n
|
|
}
|
|
|
|
// notifyOperator is the nil-safe emit helper.
|
|
func (s *organizationService) notifyOperator(key, title, summary string, fields map[string]string) {
|
|
if s.opsNotify == nil {
|
|
return
|
|
}
|
|
s.opsNotify.NotifyOperator(key, title, summary, fields)
|
|
}
|
|
|
|
// WireAgencyPool lets the limits this service reports follow an agency's shared pool.
|
|
func (s *organizationService) WireAgencyPool(p feature.AgencyPool) {
|
|
if g, ok := s.gate.(interface{ WireAgencyPool(feature.AgencyPool) }); ok {
|
|
g.WireAgencyPool(p)
|
|
}
|
|
}
|
|
|
|
// WireAuthPolicy attaches the deployment auth policy, so invitations answer to
|
|
// DISABLE_REGISTRATION the same way the signup form does.
|
|
func (s *organizationService) WireAuthPolicy(p *config.AuthPolicy) {
|
|
s.authPolicy = p
|
|
}
|
|
|
|
// WireInstanceSettings attaches the instance settings document, so the invite
|
|
// TTL and the invite-link switch answer to the admin page.
|
|
func (s *organizationService) WireInstanceSettings(set InstanceSettings) {
|
|
s.settings = set
|
|
}
|
|
|
|
// invitationTTL is the operator's invitation lifetime, falling back to the
|
|
// compiled default when nothing is wired.
|
|
func (s *organizationService) invitationTTL(ctx context.Context) time.Duration {
|
|
if s.settings == nil {
|
|
return InvitationTTL
|
|
}
|
|
if ttl := s.settings.InvitationTTL(ctx); ttl > 0 {
|
|
return ttl
|
|
}
|
|
return InvitationTTL
|
|
}
|
|
|
|
// inviteLinksEnabled reports whether the copyable invite link is exposed. It
|
|
// defaults to on, so an unwired service keeps the historic behavior.
|
|
func (s *organizationService) inviteLinksEnabled(ctx context.Context) bool {
|
|
if s.settings == nil {
|
|
return true
|
|
}
|
|
return s.settings.InviteLinksEnabled(ctx)
|
|
}
|
|
|
|
// NewService creates a new organization service
|
|
func NewService(
|
|
orgRepo repository.OrganizationRepository,
|
|
subRepo repository.SubscriptionRepository,
|
|
userRepo repository.UserRepository,
|
|
planRepo repository.PlanRepository,
|
|
throttle dailythrottle.Service,
|
|
) OrganizationService {
|
|
gate := feature.NewService(subRepo, planRepo)
|
|
if g, ok := gate.(interface {
|
|
WireLimitOverrides(feature.LimitOverrideReader)
|
|
}); ok {
|
|
g.WireLimitOverrides(orgRepo)
|
|
}
|
|
return &organizationService{
|
|
orgRepo: orgRepo,
|
|
subRepo: subRepo,
|
|
planRepo: planRepo,
|
|
userRepo: userRepo,
|
|
throttle: throttle,
|
|
gate: gate,
|
|
}
|
|
}
|
|
|
|
// Create creates a new organization and adds the user as owner
|
|
func (s *organizationService) Create(ctx context.Context, userID uuid.UUID, name, timezone string) (*models.Organization, *errx.Error) {
|
|
return s.create(ctx, userID, name, timezone, true)
|
|
}
|
|
|
|
// CreateAgencyClient is Create for a workspace an agency runs: the daily
|
|
// creation throttle applies, the owned-workspace cap does not.
|
|
func (s *organizationService) CreateAgencyClient(ctx context.Context, userID uuid.UUID, name, timezone string) (*models.Organization, *errx.Error) {
|
|
return s.create(ctx, userID, name, timezone, false)
|
|
}
|
|
|
|
func (s *organizationService) create(ctx context.Context, userID uuid.UUID, name, timezone string, ownedCap bool) (*models.Organization, *errx.Error) {
|
|
name, nerr := displayname.Validate("Workspace name", name, displayname.Workspace, false)
|
|
if nerr != nil {
|
|
return nil, nerr
|
|
}
|
|
timezone = strings.TrimSpace(timezone)
|
|
if timezone != "" && !tz.Valid(timezone) {
|
|
return nil, errx.ErrTimezone
|
|
}
|
|
if xerr := s.requireWorkspaceCreation(ctx, userID); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
// Ban-scope enforcement (migration 000045). Block new workspace
|
|
// creation when the admin's set the BanScopeOrgCreate bit, even
|
|
// if the user can otherwise log in.
|
|
scope, scopeErr := s.userRepo.GetBanState(ctx, userID)
|
|
if scopeErr != nil {
|
|
errs.CaptureException(scopeErr)
|
|
return nil, errx.InternalError()
|
|
}
|
|
if models.BanScope(scope).Has(models.BanScopeOrgCreate) {
|
|
return nil, errx.ErrAccountWorkspaceCreateSuspended
|
|
}
|
|
|
|
// Daily creation throttle — caps "new workspaces per owner per
|
|
// day" so a script can't spawn 100 orgs from one user account.
|
|
// Scope is the owner uuid (not the org, which doesn't exist yet).
|
|
if !config.SelfHosted() && s.throttle != nil {
|
|
if xerr := s.throttle.CheckAndIncrement(ctx, userID, dailythrottle.ResourceOrg, config.DailyThrottleNewOrgs); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
}
|
|
|
|
// Check organization limit
|
|
user, userErr := s.userRepo.GetUser(ctx, userID)
|
|
if userErr != nil {
|
|
errs.CaptureException(userErr)
|
|
return nil, errx.New(errx.Internal, "failed to get user")
|
|
}
|
|
if user == nil {
|
|
return nil, errx.New(errx.NotFound, "user not found")
|
|
}
|
|
|
|
if ownedCap && !config.SelfHosted() {
|
|
ownedCount, countErr := s.orgRepo.GetUserOwnedOrganizationCount(ctx, userID)
|
|
if countErr != nil {
|
|
errs.CaptureException(countErr)
|
|
return nil, errx.New(errx.Internal, "failed to get organization count")
|
|
}
|
|
if ownedCount >= user.MaxOrganizations {
|
|
return nil, errx.New(errx.Forbidden, "maximum organization limit reached")
|
|
}
|
|
}
|
|
|
|
org := &models.Organization{
|
|
Category: models.OrganizationCategoryStandard,
|
|
ID: uuid.New(),
|
|
Name: name,
|
|
OwnerUserID: userID,
|
|
Timezone: timezone,
|
|
CreatedAt: time.Now(),
|
|
UpdatedAt: time.Now(),
|
|
}
|
|
|
|
// Generate slug from name
|
|
slug := generateSlug(name)
|
|
org.Slug = &slug
|
|
|
|
if err := s.orgRepo.Create(ctx, org); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to create organization")
|
|
}
|
|
|
|
// Add creator as owner member
|
|
now := time.Now()
|
|
member := &models.OrganizationMember{
|
|
ID: uuid.New(),
|
|
OrganizationID: org.ID,
|
|
UserID: userID,
|
|
Role: string(models.RoleOwner),
|
|
Permissions: models.RolePermissions[models.RoleOwner],
|
|
InvitedAt: now,
|
|
AcceptedAt: &now,
|
|
}
|
|
|
|
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
|
errs.CaptureException(err)
|
|
// Rollback org creation
|
|
_ = s.orgRepo.Delete(ctx, org.ID)
|
|
return nil, errx.New(errx.Internal, "failed to add owner member")
|
|
}
|
|
|
|
// Seed the default roles (Admin/Manager/Viewer). Ordinary rows from here
|
|
// on: the owner can rename, reshape, or delete them. Best-effort — a
|
|
// failure leaves a usable org where roles can be created manually.
|
|
for _, seed := range models.DefaultSeedRoles() {
|
|
if err := s.orgRepo.CreateRole(ctx, &models.OrganizationRole{
|
|
ID: uuid.New(),
|
|
OrganizationID: org.ID,
|
|
Name: seed.Name,
|
|
Description: seed.Description,
|
|
Color: seed.Color,
|
|
Permissions: seed.Permissions,
|
|
}); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
}
|
|
|
|
for _, seed := range s.seeders {
|
|
seed(ctx, org.ID)
|
|
}
|
|
|
|
s.notifyOperator(
|
|
"organization.created",
|
|
"New workspace: "+org.Name,
|
|
"A new organization was created on this instance.",
|
|
map[string]string{
|
|
"Workspace": org.Name,
|
|
"Owner": user.Email,
|
|
},
|
|
)
|
|
|
|
return org, nil
|
|
}
|
|
|
|
func (s *organizationService) CreateTesterWorkspace(ctx context.Context, userID, adminID uuid.UUID, name, reason string, until time.Time) (*models.Organization, *errx.Error) {
|
|
if !until.After(time.Now()) || strings.TrimSpace(reason) == "" {
|
|
return nil, errx.New(errx.BadRequest, "test access needs a reason and a future expiry")
|
|
}
|
|
org, xerr := s.Create(ctx, userID, name, "")
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if err := s.orgRepo.ProvisionTesterWorkspace(ctx, org.ID, userID, adminID, reason, until); err != nil {
|
|
errs.CaptureException(err)
|
|
if derr := s.orgRepo.Delete(ctx, org.ID); derr != nil {
|
|
errs.CaptureException(derr)
|
|
return nil, errx.New(errx.Internal, "could not provision or remove the test workspace; review it in the admin panel")
|
|
}
|
|
return nil, errx.New(errx.Internal, "could not provision the test workspace")
|
|
}
|
|
org.Category = models.OrganizationCategoryTest
|
|
return org, nil
|
|
}
|
|
|
|
func (s *organizationService) SeedTesterWorkspace(ctx context.Context, orgID, adminID uuid.UUID, ip, userAgent string) (*models.TesterSampleData, *errx.Error) {
|
|
result, err := s.orgRepo.SeedTesterWorkspace(ctx, orgID, adminID, ip, userAgent)
|
|
if errors.Is(err, repository.ErrTesterWorkspaceInactive) {
|
|
return nil, errx.New(errx.BadRequest, "sample data requires an active dedicated Test workspace")
|
|
}
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "could not add sample data; retrying is safe")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// Get retrieves an organization by ID
|
|
func (s *organizationService) Get(ctx context.Context, orgID uuid.UUID) (*models.Organization, *errx.Error) {
|
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get organization")
|
|
}
|
|
if org == nil {
|
|
return nil, errx.ErrNotFound
|
|
}
|
|
return org, nil
|
|
}
|
|
|
|
// GetBySlug retrieves an organization by slug
|
|
func (s *organizationService) GetBySlug(ctx context.Context, slug string) (*models.Organization, *errx.Error) {
|
|
org, err := s.orgRepo.GetBySlug(ctx, slug)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get organization")
|
|
}
|
|
if org == nil {
|
|
return nil, errx.ErrNotFound
|
|
}
|
|
return org, nil
|
|
}
|
|
|
|
// Update updates an organization
|
|
func (s *organizationService) Update(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrganizationRequest) (*models.Organization, *errx.Error) {
|
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get organization")
|
|
}
|
|
if org == nil {
|
|
return nil, errx.ErrNotFound
|
|
}
|
|
|
|
if req.Name != nil {
|
|
name, nerr := displayname.Validate("Workspace name", *req.Name, displayname.Workspace, false)
|
|
if nerr != nil {
|
|
return nil, nerr
|
|
}
|
|
org.Name = name
|
|
}
|
|
if req.Slug != nil {
|
|
if !slugPattern.MatchString(*req.Slug) {
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, "invalid_slug", "Slug must be 2 to 80 lowercase letters, numbers or dashes, starting and ending with a letter or number.")
|
|
}
|
|
// Validate slug uniqueness
|
|
existing, _ := s.orgRepo.GetBySlug(ctx, *req.Slug)
|
|
if existing != nil && existing.ID != orgID {
|
|
return nil, errx.New(errx.Conflict, "slug already in use")
|
|
}
|
|
org.Slug = req.Slug
|
|
}
|
|
if req.PresenceShowOnline != nil {
|
|
org.PresenceShowOnline = *req.PresenceShowOnline
|
|
}
|
|
if req.PresenceShowActivity != nil {
|
|
org.PresenceShowActivity = *req.PresenceShowActivity
|
|
}
|
|
if req.ProductDescription != nil {
|
|
org.ProductDescription = strings.TrimSpace(*req.ProductDescription)
|
|
}
|
|
if req.ICPNotes != nil {
|
|
org.ICPNotes = strings.TrimSpace(*req.ICPNotes)
|
|
}
|
|
if req.VoiceProfile != nil {
|
|
org.VoiceProfile = strings.TrimSpace(*req.VoiceProfile)
|
|
}
|
|
if req.InboxAgentEnabled != nil {
|
|
org.InboxAgentEnabled = *req.InboxAgentEnabled
|
|
}
|
|
if req.AssistantSharedHistory != nil {
|
|
org.AssistantSharedHistory = *req.AssistantSharedHistory
|
|
}
|
|
if req.Timezone != nil {
|
|
zone := strings.TrimSpace(*req.Timezone)
|
|
if zone != "" && !tz.Valid(zone) {
|
|
return nil, errx.ErrTimezone
|
|
}
|
|
org.Timezone = zone
|
|
}
|
|
|
|
org.UpdatedAt = time.Now()
|
|
|
|
if err := s.orgRepo.Update(ctx, org); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to update organization")
|
|
}
|
|
|
|
return org, nil
|
|
}
|
|
|
|
// Delete deletes an organization
|
|
func (s *organizationService) Delete(ctx context.Context, orgID uuid.UUID) *errx.Error {
|
|
if err := s.orgRepo.Delete(ctx, orgID); err != nil {
|
|
if errors.Is(err, repository.ErrOrganizationCloudLinked) {
|
|
return errx.NewWithIdentifier(errx.Conflict, "organization_cloud_connected", "Disconnect this workspace from Warmbly Cloud before deleting it.")
|
|
}
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to delete organization")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetUserOrganizations retrieves all organizations a user is a member of
|
|
func (s *organizationService) GetUserOrganizations(ctx context.Context, userID uuid.UUID) ([]models.OrganizationMember, *errx.Error) {
|
|
members, err := s.orgRepo.GetUserOrganizations(ctx, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get user organizations")
|
|
}
|
|
return members, nil
|
|
}
|
|
|
|
// GetUserDefaultOrganization retrieves the user's default (first owned) organization
|
|
func (s *organizationService) GetUserDefaultOrganization(ctx context.Context, userID uuid.UUID) (*models.Organization, *errx.Error) {
|
|
org, err := s.orgRepo.GetUserDefaultOrganization(ctx, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get default organization")
|
|
}
|
|
return org, nil
|
|
}
|
|
|
|
// AttachTester joins a user to an existing workspace directly, bypassing the
|
|
// invitation round trip. It exists for one case: a reviewer who has to see a
|
|
// real workspace and cannot read this instance's mail, so neither the invite
|
|
// email nor the accept-as-the-invited-address check can be satisfied.
|
|
//
|
|
// It deliberately does NOT take the escalation check InviteMember applies. That
|
|
// check asks whether the actor holds every permission they are handing out, and
|
|
// an operator is not a member of the workspace at all, so there is nothing to
|
|
// compare against. What stands in for it is the manage_testers permission bit
|
|
// on the route and the admin audit row the handler writes.
|
|
//
|
|
// Idempotent: an existing membership is returned untouched rather than
|
|
// re-roled, so a repeated call cannot quietly widen what a tester can reach.
|
|
func (s *organizationService) AttachTester(ctx context.Context, orgID, userID, adminID, roleID uuid.UUID) (*models.OrganizationMember, *errx.Error) {
|
|
if _, xerr := s.Get(ctx, orgID); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
// Before the seat check, so a repeat call cannot be refused for a seat it
|
|
// already holds.
|
|
if existing, err := s.orgRepo.GetMember(ctx, orgID, userID); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to read the membership")
|
|
} else if existing != nil {
|
|
return existing, nil
|
|
}
|
|
|
|
role, err := s.orgRepo.GetRoleByID(ctx, orgID, roleID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load the role")
|
|
}
|
|
if role == nil {
|
|
return nil, errx.New(errx.BadRequest, "that role does not exist in this workspace")
|
|
}
|
|
|
|
// Last gate before the write, and the workspace's own: a tester occupies a
|
|
// seat like anyone else, so exceeding it silently would bill wrong and read
|
|
// as a bug later.
|
|
canAdd, xerr := s.CanAddMember(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if !canAdd {
|
|
return nil, errx.New(errx.Forbidden, "that workspace is at its team member limit")
|
|
}
|
|
|
|
now := time.Now()
|
|
member := &models.OrganizationMember{
|
|
ID: uuid.New(),
|
|
OrganizationID: orgID,
|
|
UserID: userID,
|
|
Role: role.Name,
|
|
RoleID: &role.ID,
|
|
Permissions: role.Permissions,
|
|
// Recorded as invited by the operator who made the tester, so the
|
|
// members list names somebody rather than showing a member nobody added.
|
|
InvitedBy: &adminID,
|
|
InvitedAt: now,
|
|
AcceptedAt: &now,
|
|
}
|
|
if err := s.orgRepo.AddMemberWithRoles(ctx, member, []uuid.UUID{role.ID}); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to add the tester to the workspace")
|
|
}
|
|
|
|
if updated, _ := s.orgRepo.GetMember(ctx, orgID, userID); updated != nil {
|
|
return updated, nil
|
|
}
|
|
return member, nil
|
|
}
|
|
|
|
// GetMembers retrieves all members of an organization
|
|
func (s *organizationService) GetMembers(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationMember, *errx.Error) {
|
|
members, err := s.orgRepo.GetMembers(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get members")
|
|
}
|
|
if err := s.orgRepo.HydrateMemberRoles(ctx, orgID, members); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
s.attachMemberAccess(ctx, orgID, members)
|
|
return members, nil
|
|
}
|
|
|
|
// GetMembership retrieves a user's membership in an organization
|
|
func (s *organizationService) GetMembership(ctx context.Context, orgID, userID uuid.UUID) (*models.OrganizationMember, *errx.Error) {
|
|
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get membership")
|
|
}
|
|
return member, nil
|
|
}
|
|
|
|
// requireWorkspaceMember authorizes workspace-wide operations against the target membership.
|
|
func (s *organizationService) requireWorkspaceMember(ctx context.Context, orgID, userID uuid.UUID) *errx.Error {
|
|
member, xerr := s.GetMembership(ctx, orgID, userID)
|
|
if xerr != nil {
|
|
return xerr
|
|
}
|
|
if member == nil {
|
|
return errx.New(errx.Forbidden, "not a member of this organization")
|
|
}
|
|
if member.IsRestricted() {
|
|
return errx.NewWithIdentifier(errx.Forbidden, "member_access_restricted", "Your access to this workspace is limited to selected campaigns and mailboxes, and this is outside it.")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// requireWorkspaceCreation checks account memberships independently of the selected workspace or credential.
|
|
func (s *organizationService) requireWorkspaceCreation(ctx context.Context, userID uuid.UUID) *errx.Error {
|
|
members, err := s.orgRepo.GetUserOrganizations(ctx, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to load workspace memberships")
|
|
}
|
|
if len(members) == 0 {
|
|
return nil
|
|
}
|
|
for i := range members {
|
|
if !members[i].IsRestricted() {
|
|
return nil
|
|
}
|
|
}
|
|
permissions, err := s.orgRepo.GetUserAdminPermissions(ctx, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to load administrator permissions")
|
|
}
|
|
if models.AdminPermission(permissions).IsAdmin() {
|
|
return nil
|
|
}
|
|
return errx.NewWithIdentifier(errx.Forbidden, "member_access_restricted", "Accounts with only restricted workspace memberships cannot create workspaces.")
|
|
}
|
|
|
|
// InviteMember invites a new member to the organization
|
|
func (s *organizationService) InviteMember(ctx context.Context, orgID uuid.UUID, inviterID uuid.UUID, req *models.InviteMemberRequest) (*models.OrganizationInvitation, *errx.Error) {
|
|
// Refuse to mint an invitation the recipient could never redeem. With
|
|
// signups fully closed the invite link 403s, so issuing one only wastes
|
|
// the inviter's time.
|
|
if s.authPolicy != nil && !s.authPolicy.InvitesAllowed() {
|
|
return nil, errx.ErrRegistrationClosed
|
|
}
|
|
|
|
// Check member limit
|
|
canAdd, err := s.CanAddMember(ctx, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !canAdd {
|
|
return nil, errx.New(errx.Forbidden, "team member limit reached")
|
|
}
|
|
|
|
// Check if user is already a member
|
|
// First, we need to check if there's already a user with this email
|
|
// For now, we'll just create the invitation
|
|
|
|
// Roles are data rows: every invite lands in one or more, snapshotting
|
|
// the effective (OR) permissions + primary name onto the invitation.
|
|
roleIDs, roles, permissions, xerr := s.resolveRoleSet(ctx, orgID, req.Resolved())
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
// Assignment is an escalation surface: the inviter must hold every
|
|
// permission the role set grants (the owner's full mask passes trivially).
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, inviterID, permissions); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
access := req.Access
|
|
if access == nil {
|
|
access = models.WorkspaceAccess()
|
|
}
|
|
if xerr := s.validateAccess(ctx, orgID, access); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
role := roles[0].Name
|
|
roleID := &roles[0].ID
|
|
|
|
// Generate invitation token
|
|
token, tokErr := generateInvitationToken()
|
|
if tokErr != nil {
|
|
errs.CaptureException(tokErr)
|
|
return nil, errx.New(errx.Internal, "failed to generate invitation token")
|
|
}
|
|
|
|
inv := &models.OrganizationInvitation{
|
|
ID: uuid.New(),
|
|
OrganizationID: orgID,
|
|
Email: strings.ToLower(req.Email),
|
|
Role: role,
|
|
RoleID: roleID,
|
|
Permissions: permissions,
|
|
InvitedBy: inviterID,
|
|
Token: crypt.SHA256(token),
|
|
ExpiresAt: time.Now().Add(s.invitationTTL(ctx)),
|
|
CreatedAt: time.Now(),
|
|
Access: access,
|
|
}
|
|
|
|
if err := s.orgRepo.CreateInvitation(ctx, inv); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to create invitation")
|
|
}
|
|
if err := s.orgRepo.SetInvitationRoles(ctx, inv.ID, roleIDs); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to attach roles")
|
|
}
|
|
inv.Roles = toMemberRoles(roles)
|
|
// The caller mails the plaintext; only its digest is stored.
|
|
inv.Token = token
|
|
|
|
return inv, nil
|
|
}
|
|
|
|
// resolveRoleSet loads + validates a set of org role ids, returning the
|
|
// deduped ids, the role rows, and the effective (OR) permission mask. At
|
|
// least one valid role is required.
|
|
func (s *organizationService) resolveRoleSet(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) ([]uuid.UUID, []models.OrganizationRole, models.OrganizationPermission, *errx.Error) {
|
|
if len(ids) == 0 {
|
|
return nil, nil, 0, errx.New(errx.BadRequest, "at least one role is required")
|
|
}
|
|
var roles []models.OrganizationRole
|
|
var perms models.OrganizationPermission
|
|
for _, id := range ids {
|
|
role, err := s.orgRepo.GetRoleByID(ctx, orgID, id)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, nil, 0, errx.New(errx.Internal, "failed to load role")
|
|
}
|
|
if role == nil {
|
|
return nil, nil, 0, errx.New(errx.BadRequest, "role not found")
|
|
}
|
|
roles = append(roles, *role)
|
|
perms |= role.Permissions
|
|
}
|
|
return ids, roles, perms, nil
|
|
}
|
|
|
|
func toMemberRoles(roles []models.OrganizationRole) []models.MemberRole {
|
|
out := make([]models.MemberRole, 0, len(roles))
|
|
for _, r := range roles {
|
|
out = append(out, models.MemberRole{ID: r.ID, Name: r.Name, Color: r.Color})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// CreateInvitedUser provisions a new account and its invitation membership atomically.
|
|
func (s *organizationService) CreateInvitedUser(ctx context.Context, token string, email *mail.Address, passwordHash string) (*models.User, *models.OrganizationMember, *errx.Error) {
|
|
u, member, err := s.orgRepo.CreateInvitedUser(ctx, crypt.SHA256(token), email, passwordHash)
|
|
if errors.Is(err, repository.ErrInvitationInvalid) {
|
|
return nil, nil, errx.ErrInvitationInvalid
|
|
}
|
|
if errors.Is(err, repository.ErrUserEmailTaken) {
|
|
return nil, nil, errx.ErrAccountExists
|
|
}
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, nil, errx.InternalError()
|
|
}
|
|
return u, member, nil
|
|
}
|
|
|
|
// AcceptInvitation accepts an invitation and adds the user as a member.
|
|
func (s *organizationService) AcceptInvitation(ctx context.Context, token string, userID uuid.UUID, email string) (*models.OrganizationMember, *errx.Error) {
|
|
inv, err := s.orgRepo.GetInvitationByToken(ctx, crypt.SHA256(token))
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitation")
|
|
}
|
|
if inv == nil {
|
|
return nil, errx.New(errx.NotFound, "invitation not found")
|
|
}
|
|
return s.acceptResolved(ctx, inv, userID, email)
|
|
}
|
|
|
|
// AcceptInvitationByID accepts an invitation the logged-in user found in their
|
|
// own pending list (no token needed; the email-match check still gates it).
|
|
func (s *organizationService) AcceptInvitationByID(ctx context.Context, invitationID, userID uuid.UUID, email string) (*models.OrganizationMember, *errx.Error) {
|
|
inv, err := s.orgRepo.GetInvitationByID(ctx, invitationID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitation")
|
|
}
|
|
if inv == nil {
|
|
return nil, errx.New(errx.NotFound, "invitation not found")
|
|
}
|
|
return s.acceptResolved(ctx, inv, userID, email)
|
|
}
|
|
|
|
func (s *organizationService) InvitationOrganization(ctx context.Context, token string, invitationID *uuid.UUID) (*uuid.UUID, *errx.Error) {
|
|
var inv *models.OrganizationInvitation
|
|
var err error
|
|
switch {
|
|
case token != "":
|
|
inv, err = s.orgRepo.GetInvitationByToken(ctx, crypt.SHA256(token))
|
|
case invitationID != nil:
|
|
inv, err = s.orgRepo.GetInvitationByID(ctx, *invitationID)
|
|
}
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.InternalError()
|
|
}
|
|
if inv == nil {
|
|
return nil, nil
|
|
}
|
|
id := inv.OrganizationID
|
|
return &id, nil
|
|
}
|
|
|
|
// PreviewInvitation returns the safe public view for the /invite landing page.
|
|
func (s *organizationService) PreviewInvitation(ctx context.Context, token string) (*models.InvitationPreview, *errx.Error) {
|
|
inv, err := s.orgRepo.GetInvitationByToken(ctx, crypt.SHA256(token))
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitation")
|
|
}
|
|
if inv == nil {
|
|
return nil, errx.New(errx.NotFound, "invitation not found")
|
|
}
|
|
// An expired invitation is answered with the fact that it expired and
|
|
// nothing else. The token is unguessable, but it can outlive its usefulness
|
|
// in an inbox or a log, and there is no reason for a stale one to keep
|
|
// handing out the invitee's address and the workspace's name.
|
|
if inv.IsExpired() {
|
|
return &models.InvitationPreview{Expired: true}, nil
|
|
}
|
|
|
|
preview := &models.InvitationPreview{
|
|
Email: inv.Email,
|
|
Expired: false,
|
|
}
|
|
if inv.Organization != nil {
|
|
// Shown to someone outside the workspace, with the invitation email's fallbacks.
|
|
preview.OrganizationName = displayname.DisplayableOr(inv.Organization.Name, "your organization")
|
|
if inv.Organization.AvatarURL != nil {
|
|
preview.OrganizationAvatar = *inv.Organization.AvatarURL
|
|
}
|
|
}
|
|
if inviter, _ := s.userRepo.GetUser(ctx, inv.InvitedBy); inviter != nil {
|
|
preview.InviterName = displayname.FullName(inviter.FirstName, inviter.LastName)
|
|
if preview.InviterName == "" {
|
|
preview.InviterName = "A team member"
|
|
}
|
|
}
|
|
list := []models.OrganizationInvitation{*inv}
|
|
if err := s.orgRepo.HydrateInvitationRoles(ctx, list); err == nil {
|
|
preview.Roles = list[0].Roles
|
|
}
|
|
return preview, nil
|
|
}
|
|
|
|
// GetInvitationToken mints a shareable /invite link token for one of the org's
|
|
// pending invitations; the emailed link keeps working alongside it.
|
|
func (s *organizationService) GetInvitationToken(ctx context.Context, orgID, invitationID uuid.UUID) (string, *errx.Error) {
|
|
// The link is a bearer credential, so an operator can switch it off and
|
|
// require the invitation to arrive by email.
|
|
if !s.inviteLinksEnabled(ctx) {
|
|
return "", errx.New(errx.NotFound, "invite links are turned off on this instance; the invitation has to be delivered by email")
|
|
}
|
|
|
|
inv, err := s.orgRepo.GetInvitationByID(ctx, invitationID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return "", errx.New(errx.Internal, "failed to get invitation")
|
|
}
|
|
if inv == nil || inv.OrganizationID != orgID {
|
|
return "", errx.New(errx.NotFound, "invitation not found")
|
|
}
|
|
// Only digests are stored, so each copy mints the link's own token and replaces the last copied one.
|
|
token, err := generateInvitationToken()
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return "", errx.New(errx.Internal, "failed to generate invitation token")
|
|
}
|
|
ok, err := s.orgRepo.SetInvitationLinkToken(ctx, orgID, invitationID, crypt.SHA256(token))
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return "", errx.New(errx.Internal, "failed to store invitation link")
|
|
}
|
|
if !ok {
|
|
return "", errx.New(errx.NotFound, "invitation not found")
|
|
}
|
|
return token, nil
|
|
}
|
|
|
|
// acceptResolved performs the actual join given an already-loaded invitation.
|
|
func (s *organizationService) acceptResolved(ctx context.Context, inv *models.OrganizationInvitation, userID uuid.UUID, email string) (*models.OrganizationMember, *errx.Error) {
|
|
|
|
// Verify email matches. Name both addresses: the usual cause is a browser
|
|
// already signed in as someone else, and a bare "does not match" hides it.
|
|
if !strings.EqualFold(email, inv.Email) {
|
|
return nil, errx.New(errx.Forbidden, "this invitation is for "+inv.Email+", but you are signed in as "+email+"; sign out and use the invited address")
|
|
}
|
|
|
|
// An expired invitation stays listed so the team page can send it again.
|
|
if inv.IsExpired() {
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, "invitation_expired", "This invitation has expired. Invitations last 48 hours; ask the person who invited you to send it again from the Team page.")
|
|
}
|
|
|
|
// Check if already a member
|
|
existing, _ := s.orgRepo.GetMember(ctx, inv.OrganizationID, userID)
|
|
if existing != nil {
|
|
if err := s.orgRepo.DeleteInvitation(ctx, inv.ID); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.InternalError()
|
|
}
|
|
return existing, nil
|
|
}
|
|
|
|
// Re-resolve the invitation's role set at accept time: snapshots may be
|
|
// stale (edited) or dangling (deleted) since the invite was sent. Roles
|
|
// deleted in the meantime are dropped; at least one must survive.
|
|
invRoleIDs, ierr := s.orgRepo.GetInvitationRoles(ctx, inv.ID)
|
|
if ierr != nil {
|
|
errs.CaptureException(ierr)
|
|
return nil, errx.New(errx.Internal, "failed to load invitation roles")
|
|
}
|
|
var liveRoleIDs []uuid.UUID
|
|
var primary *models.OrganizationRole
|
|
for _, id := range invRoleIDs {
|
|
role, rerr := s.orgRepo.GetRoleByID(ctx, inv.OrganizationID, id)
|
|
if rerr != nil {
|
|
errs.CaptureException(rerr)
|
|
return nil, errx.New(errx.Internal, "failed to load role")
|
|
}
|
|
if role == nil {
|
|
continue
|
|
}
|
|
if primary == nil {
|
|
primary = role
|
|
}
|
|
liveRoleIDs = append(liveRoleIDs, id)
|
|
}
|
|
if len(liveRoleIDs) == 0 {
|
|
if err := s.orgRepo.DeleteInvitation(ctx, inv.ID); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, "invitation_roles_removed", "The roles this invitation granted no longer exist. Ask the person who invited you to send a new invitation.")
|
|
}
|
|
|
|
// Add the membership row, then assign the full role set (which recomputes
|
|
// the effective permission snapshot).
|
|
now := time.Now()
|
|
member := &models.OrganizationMember{
|
|
ID: uuid.New(),
|
|
OrganizationID: inv.OrganizationID,
|
|
UserID: userID,
|
|
Role: primary.Name,
|
|
RoleID: &primary.ID,
|
|
Permissions: primary.Permissions,
|
|
InvitedBy: repository.InviterOf(inv.InvitedBy),
|
|
InvitedAt: inv.CreatedAt,
|
|
AcceptedAt: &now,
|
|
// Grants on resources deleted since the invite are dropped by the insert.
|
|
Access: inv.Access,
|
|
}
|
|
if err := s.orgRepo.AcceptInvitation(ctx, inv.ID, member, liveRoleIDs); err != nil {
|
|
if errors.Is(err, repository.ErrInvitationInvalid) {
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, "invitation_used_or_expired", "This invitation has already been used or has expired. Ask the person who invited you to send it again from the Team page.")
|
|
}
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to add member")
|
|
}
|
|
|
|
if updated, _ := s.orgRepo.GetMember(ctx, inv.OrganizationID, userID); updated != nil {
|
|
member = updated
|
|
}
|
|
return member, nil
|
|
}
|
|
|
|
// UpdateMemberRole updates a member's role and permissions
|
|
func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID, actorID, memberUserID uuid.UUID, req *models.UpdateMemberRequest) (*models.OrganizationMember, *errx.Error) {
|
|
member, err := s.orgRepo.GetMember(ctx, orgID, memberUserID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get member")
|
|
}
|
|
if member == nil {
|
|
return nil, errx.New(errx.NotFound, "member not found")
|
|
}
|
|
|
|
// Cannot change owner's role
|
|
if member.Role == string(models.RoleOwner) {
|
|
return nil, errx.New(errx.Forbidden, "cannot modify owner role")
|
|
}
|
|
|
|
roleIDs, _, permissions, xerr := s.resolveRoleSet(ctx, orgID, req.Resolved())
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
// Assignment is an escalation surface: the actor must hold every
|
|
// permission the member has now and every one the new role set grants,
|
|
// and may not re-role themselves.
|
|
if actorID == memberUserID {
|
|
return nil, errx.New(errx.Forbidden, "you cannot change your own roles")
|
|
}
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, actorID, permissions|member.Permissions); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
if err := s.orgRepo.SetMemberRoles(ctx, orgID, memberUserID, roleIDs); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to update roles")
|
|
}
|
|
|
|
updated, gerr := s.orgRepo.GetMember(ctx, orgID, memberUserID)
|
|
if gerr != nil {
|
|
errs.CaptureException(gerr)
|
|
return nil, errx.New(errx.Internal, "failed to load member")
|
|
}
|
|
if updated != nil {
|
|
updated.Roles, _ = s.orgRepo.GetMemberRoles(ctx, orgID, memberUserID)
|
|
}
|
|
return updated, nil
|
|
}
|
|
|
|
// RemoveMember removes a member from the organization. The actor must hold
|
|
// every permission the member holds.
|
|
func (s *organizationService) RemoveMember(ctx context.Context, orgID, actorID, memberUserID uuid.UUID) *errx.Error {
|
|
member, err := s.orgRepo.GetMember(ctx, orgID, memberUserID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to get member")
|
|
}
|
|
if member == nil {
|
|
return errx.New(errx.NotFound, "member not found")
|
|
}
|
|
|
|
// Cannot remove owner
|
|
if member.Role == string(models.RoleOwner) {
|
|
return errx.New(errx.Forbidden, "cannot remove organization owner")
|
|
}
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, actorID, member.Permissions); xerr != nil {
|
|
return xerr
|
|
}
|
|
|
|
if err := s.orgRepo.RemoveMember(ctx, orgID, memberUserID); err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to remove member")
|
|
}
|
|
|
|
// Detached from the caller, so a dropped request cannot leave the removed member's access in place.
|
|
hookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
|
defer cancel()
|
|
for _, fn := range s.removals {
|
|
if err := fn(hookCtx, orgID, memberUserID); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetPendingInvitations retrieves all pending invitations for an organization
|
|
func (s *organizationService) GetPendingInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, *errx.Error) {
|
|
invitations, err := s.orgRepo.GetPendingInvitations(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitations")
|
|
}
|
|
if err := s.orgRepo.HydrateInvitationRoles(ctx, invitations); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
return invitations, nil
|
|
}
|
|
|
|
// expiredInvitationsListed bounds the expired invitations offered for sending again.
|
|
const expiredInvitationsListed = 50
|
|
|
|
// GetExpiredInvitations returns an organization's recently expired invitations, marked expired.
|
|
func (s *organizationService) GetExpiredInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, *errx.Error) {
|
|
invitations, err := s.orgRepo.GetExpiredInvitations(ctx, orgID, expiredInvitationsListed)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitations")
|
|
}
|
|
for i := range invitations {
|
|
invitations[i].Expired = true
|
|
}
|
|
if err := s.orgRepo.HydrateInvitationRoles(ctx, invitations); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
return invitations, nil
|
|
}
|
|
|
|
// GetUserPendingInvitations retrieves all pending invitations for a user
|
|
func (s *organizationService) GetUserPendingInvitations(ctx context.Context, email string) ([]models.OrganizationInvitation, *errx.Error) {
|
|
invitations, err := s.orgRepo.GetUserPendingInvitations(ctx, email)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get invitations")
|
|
}
|
|
return invitations, nil
|
|
}
|
|
|
|
// CancelInvitation cancels a pending invitation. The org id comes from the
|
|
// caller's session, never from the request, so the invitation id alone cannot
|
|
// address a row outside the caller's workspace.
|
|
func (s *organizationService) CancelInvitation(ctx context.Context, orgID, invitationID uuid.UUID) *errx.Error {
|
|
inv, err := s.orgRepo.GetInvitationByID(ctx, invitationID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to load invitation")
|
|
}
|
|
if inv == nil || inv.OrganizationID != orgID {
|
|
return errx.ErrNotFound
|
|
}
|
|
|
|
if err := s.orgRepo.DeleteInvitation(ctx, invitationID); err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to cancel invitation")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// TransferOwnership transfers organization ownership
|
|
func (s *organizationService) TransferOwnership(ctx context.Context, orgID, actorUserID, newOwnerUserID uuid.UUID) *errx.Error {
|
|
// Only the current owner may hand the workspace over. The route is gated
|
|
// on PermTransferOwnership, but that permission can sit in a custom role,
|
|
// and a delegate transferring ownership to themselves is an escalation.
|
|
org, oerr := s.orgRepo.GetByID(ctx, orgID)
|
|
if oerr != nil {
|
|
errs.CaptureException(oerr)
|
|
return errx.New(errx.Internal, "failed to load organization")
|
|
}
|
|
if org == nil {
|
|
return errx.ErrNotFound
|
|
}
|
|
if org.OwnerUserID != actorUserID {
|
|
return errx.New(errx.Forbidden, "only the workspace owner can transfer ownership")
|
|
}
|
|
|
|
if newOwnerUserID == actorUserID {
|
|
return errx.New(errx.BadRequest, "you already own this workspace")
|
|
}
|
|
|
|
// The repository decides again against the locked row, so two requests cannot both move it.
|
|
switch err := s.orgRepo.TransferOwnership(ctx, orgID, actorUserID, newOwnerUserID); {
|
|
case err == nil:
|
|
return nil
|
|
case errors.Is(err, repository.ErrOwnershipNotHeld):
|
|
return errx.New(errx.Forbidden, "only the workspace owner can transfer ownership")
|
|
case errors.Is(err, repository.ErrNewOwnerNotMember):
|
|
return errx.New(errx.BadRequest, "new owner must be a member of the organization")
|
|
case errors.Is(err, repository.ErrNewOwnerUnavailable):
|
|
return errx.New(errx.Conflict, "that member's account cannot take ownership right now")
|
|
default:
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to transfer ownership")
|
|
}
|
|
}
|
|
|
|
// HasPermission checks if a user has a specific permission
|
|
func (s *organizationService) HasPermission(ctx context.Context, orgID, userID uuid.UUID, perm models.OrganizationPermission) (bool, *errx.Error) {
|
|
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return false, errx.New(errx.Internal, "failed to check permission")
|
|
}
|
|
if member == nil {
|
|
return false, nil
|
|
}
|
|
return member.HasPermission(perm), nil
|
|
}
|
|
|
|
// RequirePermission checks permission and returns error if not granted
|
|
func (s *organizationService) RequirePermission(ctx context.Context, orgID, userID uuid.UUID, perm models.OrganizationPermission) *errx.Error {
|
|
has, err := s.HasPermission(ctx, orgID, userID, perm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !has {
|
|
return errx.ErrForbidden
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CanAddMember checks if the organization can add more members based on plan limits
|
|
func (s *organizationService) CanAddMember(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) {
|
|
limits, err := s.GetEffectiveLimits(ctx, orgID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
// No limit set = unlimited
|
|
if limits == nil || limits.MaxTeamMembers == nil {
|
|
return true, nil
|
|
}
|
|
|
|
count, xerr := s.orgRepo.GetMemberCount(ctx, orgID)
|
|
if xerr != nil {
|
|
errs.CaptureException(xerr)
|
|
return false, errx.New(errx.Internal, "failed to get member count")
|
|
}
|
|
|
|
return count < *limits.MaxTeamMembers, nil
|
|
}
|
|
|
|
// CanAddCampaign checks if the organization can add more campaigns based on plan limits
|
|
func (s *organizationService) CanAddCampaign(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) {
|
|
limits, err := s.GetEffectiveLimits(ctx, orgID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
total, active, xerr := s.GetCampaignCounts(ctx, orgID)
|
|
if xerr != nil {
|
|
return false, xerr
|
|
}
|
|
|
|
// Check total campaign limit
|
|
if limits != nil && limits.MaxCampaigns != nil && total >= *limits.MaxCampaigns {
|
|
return false, nil
|
|
}
|
|
|
|
// Check active campaign limit
|
|
if limits != nil && limits.MaxActiveCampaigns != nil && active >= *limits.MaxActiveCampaigns {
|
|
return false, nil
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// MailboxAllowance resolves the workspace's mailbox allowance. Resolution:
|
|
//
|
|
// 1. no billing provider: unlimited
|
|
// 2. an operator override: the override
|
|
// 3. no paid subscription: Subscription.FreeMailboxLimit (none for new workspaces)
|
|
// 4. the plan's explicit mailbox column, when it carries one
|
|
// 5. the plan's daily sends divided by FairUseSendsPerMailbox
|
|
// 6. a plan with no daily send cap: unlimited
|
|
//
|
|
// The count includes every connected mailbox, so a workspace that dropped to
|
|
// a smaller plan simply cannot add until it is back under; nothing is removed.
|
|
func (s *organizationService) MailboxAllowance(ctx context.Context, orgID uuid.UUID) (*models.MailboxAllowance, *errx.Error) {
|
|
count, err := s.orgRepo.GetEmailAccountCount(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get email account count")
|
|
}
|
|
a := &models.MailboxAllowance{Used: count, SendsPerMailbox: config.FairUseSendsPerMailbox}
|
|
|
|
if config.BillingProvider() == "none" {
|
|
a.Basis = models.MailboxAllowanceUnlimited
|
|
a.Paid = true
|
|
return a, nil
|
|
}
|
|
|
|
sub, serr := s.subRepo.GetByOrganizationID(ctx, orgID)
|
|
if serr != nil {
|
|
errs.CaptureException(serr)
|
|
return nil, errx.New(errx.Internal, "failed to get subscription")
|
|
}
|
|
a.Paid = sub != nil && sub.HasPaidSubscription()
|
|
if sub != nil && sub.Plan != nil {
|
|
if sub.Plan.Name != nil {
|
|
a.PlanName = *sub.Plan.Name
|
|
}
|
|
if sub.Plan.DailyCampaignLimit != nil && *sub.Plan.DailyCampaignLimit > 0 {
|
|
v := *sub.Plan.DailyCampaignLimit
|
|
a.PlanDailySends = &v
|
|
}
|
|
}
|
|
|
|
override, xerr := s.GetLimitOverrides(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
set := func(v int, basis models.MailboxAllowanceBasis) {
|
|
a.Allowance = &v
|
|
rem := v - count
|
|
if rem < 0 {
|
|
rem = 0
|
|
}
|
|
a.Remaining = &rem
|
|
a.Basis = basis
|
|
}
|
|
|
|
switch {
|
|
case override != nil && override.MaxEmailAccounts > 0:
|
|
set(override.MaxEmailAccounts, models.MailboxAllowanceOverride)
|
|
case !a.Paid:
|
|
set(sub.FreeMailboxLimit(), models.MailboxAllowanceFree)
|
|
case sub.Plan != nil && sub.Plan.MaxEmailAccounts != nil && *sub.Plan.MaxEmailAccounts > 0:
|
|
set(*sub.Plan.MaxEmailAccounts, models.MailboxAllowancePlan)
|
|
case a.PlanDailySends != nil:
|
|
set((*a.PlanDailySends+config.FairUseSendsPerMailbox-1)/config.FairUseSendsPerMailbox, models.MailboxAllowanceFairUse)
|
|
default:
|
|
a.Basis = models.MailboxAllowanceUnlimited
|
|
}
|
|
|
|
// The open request, so the dashboard can show "asked for 5,000, pending"
|
|
// instead of offering a form that would be refused as a duplicate.
|
|
if a.Allowance != nil {
|
|
rows, rerr := s.orgRepo.ListLimitRequestsForOrg(ctx, orgID)
|
|
if rerr != nil {
|
|
errs.CaptureException(rerr)
|
|
}
|
|
for i := range rows {
|
|
if rows[i].Field == "max_email_accounts" && rows[i].Status == models.LimitRequestStatusPending {
|
|
a.PendingRequest = &rows[i]
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
// GetCampaignCounts returns total and active campaign counts
|
|
func (s *organizationService) GetCampaignCounts(ctx context.Context, orgID uuid.UUID) (total int, active int, err *errx.Error) {
|
|
t, a, xerr := s.orgRepo.GetCampaignCounts(ctx, orgID)
|
|
if xerr != nil {
|
|
errs.CaptureException(xerr)
|
|
return 0, 0, errx.New(errx.Internal, "failed to get campaign counts")
|
|
}
|
|
return t, a, nil
|
|
}
|
|
|
|
// GetOrganizationLimits retrieves the organization's plan limits
|
|
func (s *organizationService) GetOrganizationLimits(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimits, *errx.Error) {
|
|
sub, err := s.subRepo.GetByOrganizationID(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get subscription")
|
|
}
|
|
if sub == nil || sub.Plan == nil {
|
|
return nil, nil
|
|
}
|
|
|
|
return &models.OrganizationLimits{
|
|
MaxCampaigns: sub.Plan.MaxCampaigns,
|
|
MaxActiveCampaigns: sub.Plan.MaxActiveCampaigns,
|
|
MaxTeamMembers: sub.Plan.MaxTeamMembers,
|
|
MaxEmailAccounts: sub.Plan.MaxEmailAccounts,
|
|
DailyCampaignLimit: sub.Plan.DailyCampaignLimit,
|
|
}, nil
|
|
}
|
|
|
|
// GetOrganizationCounts retrieves the organization's resource counts
|
|
func (s *organizationService) GetOrganizationCounts(ctx context.Context, orgID uuid.UUID) (*models.OrganizationCounts, *errx.Error) {
|
|
total, active, err := s.orgRepo.GetCampaignCounts(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get campaign counts")
|
|
}
|
|
|
|
members, err := s.orgRepo.GetMemberCount(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get member count")
|
|
}
|
|
|
|
emails, err := s.orgRepo.GetEmailAccountCount(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get email account count")
|
|
}
|
|
|
|
contacts, err := s.orgRepo.GetContactCount(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to get contact count")
|
|
}
|
|
|
|
sentToday, _ := s.orgRepo.GetEmailsSentTodayCount(ctx, orgID)
|
|
|
|
return &models.OrganizationCounts{
|
|
TotalCampaigns: total,
|
|
ActiveCampaigns: active,
|
|
TotalMembers: members,
|
|
EmailAccounts: emails,
|
|
TotalContacts: contacts,
|
|
EmailsSentToday: sentToday,
|
|
}, nil
|
|
}
|
|
|
|
// GetScopedOrganizationCounts reports only granted campaigns, their contacts and granted mailbox sends.
|
|
func (s *organizationService) GetScopedOrganizationCounts(ctx context.Context, orgID uuid.UUID, scope *models.ResourceScope) (*models.OrganizationCounts, *errx.Error) {
|
|
if scope == nil {
|
|
return nil, errx.New(errx.Internal, "member access was not resolved")
|
|
}
|
|
counts, err := s.orgRepo.GetScopedOrganizationCounts(ctx, orgID, scope)
|
|
if err != nil || counts == nil {
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
return nil, errx.New(errx.Internal, "failed to get scoped organization counts")
|
|
}
|
|
return counts, nil
|
|
}
|
|
|
|
// CreateEnterpriseInquiry creates an enterprise inquiry
|
|
func (s *organizationService) CreateEnterpriseInquiry(ctx context.Context, inquiry *models.EnterpriseInquiry) (*models.EnterpriseInquiry, *errx.Error) {
|
|
inquiry.ID = uuid.New()
|
|
inquiry.Status = string(models.EnterpriseInquiryStatusPending)
|
|
inquiry.CreatedAt = time.Now()
|
|
|
|
if err := s.orgRepo.CreateEnterpriseInquiry(ctx, inquiry); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to create enterprise inquiry")
|
|
}
|
|
|
|
s.notifyOperator(
|
|
"enterprise_inquiry.created",
|
|
"Enterprise inquiry from "+inquiry.CompanyName,
|
|
"Someone asked for enterprise pricing.",
|
|
map[string]string{
|
|
"Company": inquiry.CompanyName,
|
|
"Contact": inquiry.ContactName,
|
|
"Email": inquiry.ContactEmail,
|
|
"Notes": inquiry.Notes,
|
|
},
|
|
)
|
|
|
|
return inquiry, nil
|
|
}
|
|
|
|
// Helper functions
|
|
|
|
var slugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$`)
|
|
|
|
func generateSlug(name string) string {
|
|
// Simple slug generation - lowercase, replace spaces with dashes
|
|
slug := strings.ToLower(name)
|
|
slug = strings.ReplaceAll(slug, " ", "-")
|
|
// Remove non-alphanumeric characters except dashes
|
|
var result strings.Builder
|
|
for _, r := range slug {
|
|
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' {
|
|
result.WriteRune(r)
|
|
}
|
|
}
|
|
// Add random suffix to ensure uniqueness
|
|
suffix := make([]byte, 4)
|
|
rand.Read(suffix)
|
|
return result.String() + "-" + hex.EncodeToString(suffix)
|
|
}
|
|
|
|
func generateInvitationToken() (string, error) {
|
|
bytes := make([]byte, InvitationTokenLength)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(bytes), nil
|
|
}
|
|
|
|
// GetUserAdminPermissions retrieves the admin permissions for a user
|
|
func (s *organizationService) GetUserAdminPermissions(ctx context.Context, userID uuid.UUID) (uint32, error) {
|
|
return s.orgRepo.GetUserAdminPermissions(ctx, userID)
|
|
}
|
|
|
|
// SearchOrganizationsForAdmin returns the paginated admin org listing.
|
|
func (s *organizationService) SearchOrganizationsForAdmin(ctx context.Context, search *models.AdminOrgSearch) (*models.AdminOrgsResult, *errx.Error) {
|
|
result, err := s.orgRepo.SearchOrganizationsForAdmin(ctx, search)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to search organizations")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// GetOrganizationAdminDetail returns the per-org admin payload — the
|
|
// list-shape row plus a counts snapshot and plan/subscription state.
|
|
// Limits come from the org's plan via GetOrganizationLimits so admin
|
|
// callers see the same numbers the in-app limit checks enforce.
|
|
func (s *organizationService) GetOrganizationAdminDetail(ctx context.Context, orgID uuid.UUID) (*models.AdminOrgDetail, *errx.Error) {
|
|
detail, err := s.orgRepo.GetOrganizationAdminDetail(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load organization")
|
|
}
|
|
if detail == nil {
|
|
return nil, errx.New(errx.NotFound, "organization not found")
|
|
}
|
|
|
|
if limits, xerr := s.GetOrganizationLimits(ctx, orgID); xerr == nil {
|
|
detail.Limits = limits
|
|
}
|
|
if overrides, xerr := s.GetLimitOverrides(ctx, orgID); xerr == nil {
|
|
detail.Overrides = overrides
|
|
}
|
|
if effective, xerr := s.GetEffectiveLimits(ctx, orgID); xerr == nil {
|
|
detail.EffectiveLimits = effective
|
|
}
|
|
if counts, xerr := s.GetOrganizationCounts(ctx, orgID); xerr == nil {
|
|
detail.Counts = counts
|
|
}
|
|
|
|
return detail, nil
|
|
}
|
|
|
|
// GetOrganizationMembersForAdmin returns the members of an org with
|
|
// joined user info for the admin panel.
|
|
func (s *organizationService) GetOrganizationMembersForAdmin(ctx context.Context, orgID uuid.UUID) ([]models.AdminOrgMember, *errx.Error) {
|
|
members, err := s.orgRepo.GetOrganizationMembersForAdmin(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load members")
|
|
}
|
|
return members, nil
|
|
}
|
|
|
|
// GetLimitOverrides returns the override row for an org, or nil if no
|
|
// admin has touched it yet.
|
|
func (s *organizationService) GetLimitOverrides(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimitOverrides, *errx.Error) {
|
|
o, err := s.orgRepo.GetOrganizationLimitOverrides(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load limit overrides")
|
|
}
|
|
return o, nil
|
|
}
|
|
|
|
// SetLimitOverrides applies a partial update to the override row. The
|
|
// caller is responsible for the audit log write — the service stays
|
|
// audit-agnostic so it can be reused outside admin handlers later
|
|
// (e.g. limit-request approval in slice 3).
|
|
func (s *organizationService) SetLimitOverrides(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrgOverridesRequest, grantedBy uuid.UUID) (*models.OrganizationLimitOverrides, *errx.Error) {
|
|
o, err := s.orgRepo.UpsertOrganizationLimitOverrides(ctx, orgID, req, grantedBy)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to write limit overrides")
|
|
}
|
|
return o, nil
|
|
}
|
|
|
|
// GetEffectiveLimits returns the limits the runtime actually enforces.
|
|
// Resolution per field:
|
|
//
|
|
// 1. override > 0 → use override
|
|
// 2. plan != nil → use plan column
|
|
// 3. otherwise → fall back to the product-level hard cap
|
|
//
|
|
// Every field but mailboxes and daily sends is never nil: an "unlimited" plan
|
|
// is bounded by the product hard caps in config/constants.go. Mailboxes follow
|
|
// MailboxAllowance and daily sends follow the sender's gate, where nil really
|
|
// means unlimited. Admins can raise individual caps per-org by writing an override.
|
|
func (s *organizationService) GetEffectiveLimits(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimits, *errx.Error) {
|
|
plan, err := s.GetOrganizationLimits(ctx, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
override, err := s.GetLimitOverrides(ctx, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
mailboxes, err := s.MailboxAllowance(ctx, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
resolve := func(overrideVal int, planVal *int, hardCap int) *int {
|
|
if overrideVal > 0 {
|
|
v := overrideVal
|
|
return &v
|
|
}
|
|
if planVal != nil {
|
|
return planVal
|
|
}
|
|
v := hardCap
|
|
return &v
|
|
}
|
|
|
|
var ovMaxCampaigns, ovMaxActive, ovMaxMembers, ovMaxContacts int
|
|
if override != nil {
|
|
ovMaxCampaigns = override.MaxCampaigns
|
|
ovMaxActive = override.MaxActiveCampaigns
|
|
ovMaxMembers = override.MaxTeamMembers
|
|
ovMaxContacts = override.MaxContacts
|
|
}
|
|
|
|
var planLimits models.OrganizationLimits
|
|
if plan != nil {
|
|
planLimits = *plan
|
|
}
|
|
|
|
daily, err := s.dailySendLimit(ctx, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &models.OrganizationLimits{
|
|
MaxCampaigns: resolve(ovMaxCampaigns, planLimits.MaxCampaigns, config.HardCapCampaignsTotal),
|
|
MaxActiveCampaigns: resolve(ovMaxActive, planLimits.MaxActiveCampaigns, config.HardCapCampaignsActive),
|
|
MaxTeamMembers: resolve(ovMaxMembers, planLimits.MaxTeamMembers, config.HardCapTeamMembers),
|
|
MaxEmailAccounts: mailboxes.Allowance,
|
|
MaxContacts: resolve(ovMaxContacts, planLimits.MaxContacts, config.HardCapContacts),
|
|
DailyCampaignLimit: daily,
|
|
}, nil
|
|
}
|
|
|
|
// dailySendLimit is the cap the sender enforces (feature.GetDailyEmailLimit), nil when it is unlimited.
|
|
func (s *organizationService) dailySendLimit(ctx context.Context, orgID uuid.UUID) (*int, *errx.Error) {
|
|
if s.gate == nil {
|
|
v := config.HardCapDailyCampaignSends
|
|
return &v, nil
|
|
}
|
|
n, xerr := s.gate.GetDailyEmailLimit(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if n < 0 {
|
|
return nil, nil
|
|
}
|
|
return &n, nil
|
|
}
|
|
|
|
// WebhookDispatchLimit derives the org's per-minute webhook/integration fan-out
|
|
// cap from its effective plan limits. Plan-based: it scales with the org's
|
|
// resolved mailbox allowance (since webhook volume tracks sending activity),
|
|
// floored at a generous baseline so even free/no-plan orgs never trip the
|
|
// throttle under normal use, and ceilinged so an "unlimited" plan stays bounded.
|
|
// Fail-open generous: any error yields the base cap rather than blocking.
|
|
func (s *organizationService) WebhookDispatchLimit(ctx context.Context, orgID uuid.UUID) int {
|
|
limit := config.WebhookDispatchBasePerMinute
|
|
|
|
eff, err := s.GetEffectiveLimits(ctx, orgID)
|
|
if err != nil || eff == nil {
|
|
return limit
|
|
}
|
|
if eff.MaxEmailAccounts == nil {
|
|
// Unlimited mailboxes: the ceiling is the only bound left.
|
|
return config.WebhookDispatchMaxPerMinute
|
|
}
|
|
if scaled := *eff.MaxEmailAccounts * config.WebhookDispatchPerMailboxPerMinute; scaled > limit {
|
|
limit = scaled
|
|
}
|
|
if limit > config.WebhookDispatchMaxPerMinute {
|
|
limit = config.WebhookDispatchMaxPerMinute
|
|
}
|
|
return limit
|
|
}
|
|
|
|
// limitFieldUpdater maps a request's `field` string onto the override
|
|
// column it should write. Keeping this map adjacent to the request flow
|
|
// makes it obvious what's user-requestable; adding a new field is two
|
|
// lines here plus the override model.
|
|
var limitFieldUpdater = map[string]func(req *models.UpdateOrgOverridesRequest, v int){
|
|
"max_campaigns": func(r *models.UpdateOrgOverridesRequest, v int) { r.MaxCampaigns = &v },
|
|
"max_active_campaigns": func(r *models.UpdateOrgOverridesRequest, v int) { r.MaxActiveCampaigns = &v },
|
|
"max_team_members": func(r *models.UpdateOrgOverridesRequest, v int) { r.MaxTeamMembers = &v },
|
|
"max_email_accounts": func(r *models.UpdateOrgOverridesRequest, v int) { r.MaxEmailAccounts = &v },
|
|
"max_contacts": func(r *models.UpdateOrgOverridesRequest, v int) { r.MaxContacts = &v },
|
|
"daily_campaign_limit": func(r *models.UpdateOrgOverridesRequest, v int) { r.DailyCampaignLimit = &v },
|
|
}
|
|
|
|
// limitFieldEffective extracts the currently-enforced value for a field
|
|
// off the effective-limits resolver result. Used at submission time so
|
|
// the stored row records what the user was looking at when they asked.
|
|
func limitFieldEffective(field string, eff *models.OrganizationLimits) int {
|
|
if eff == nil {
|
|
return 0
|
|
}
|
|
get := func(p *int) int {
|
|
if p == nil {
|
|
return 0
|
|
}
|
|
return *p
|
|
}
|
|
switch field {
|
|
case "max_campaigns":
|
|
return get(eff.MaxCampaigns)
|
|
case "max_active_campaigns":
|
|
return get(eff.MaxActiveCampaigns)
|
|
case "max_team_members":
|
|
return get(eff.MaxTeamMembers)
|
|
case "max_email_accounts":
|
|
return get(eff.MaxEmailAccounts)
|
|
case "max_contacts":
|
|
return get(eff.MaxContacts)
|
|
case "daily_campaign_limit":
|
|
return get(eff.DailyCampaignLimit)
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func (s *organizationService) SubmitLimitIncreaseRequest(ctx context.Context, orgID, submitterID uuid.UUID, req *models.CreateLimitIncreaseRequest) (*models.LimitIncreaseRequest, *errx.Error) {
|
|
if _, ok := limitFieldUpdater[req.Field]; !ok {
|
|
return nil, errx.New(errx.BadRequest, "unknown field")
|
|
}
|
|
if req.Requested <= 0 {
|
|
return nil, errx.New(errx.BadRequest, "requested value must be positive")
|
|
}
|
|
|
|
// Limit requests require workspace-wide access to the target organization.
|
|
if xerr := s.requireWorkspaceMember(ctx, orgID, submitterID); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
effective, xerr := s.GetEffectiveLimits(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if req.Field == "max_email_accounts" && effective.MaxEmailAccounts == nil {
|
|
return nil, errx.New(errx.BadRequest, "this workspace already holds unlimited mailboxes")
|
|
}
|
|
// An override on an uncapped limit would impose a cap, not raise one.
|
|
if req.Field == "daily_campaign_limit" && effective.DailyCampaignLimit == nil {
|
|
return nil, errx.New(errx.BadRequest, "this workspace's daily sends are already unlimited")
|
|
}
|
|
// Only the mailbox allowance applies to a workspace that does not send.
|
|
if req.Field != "max_email_accounts" && s.gate != nil {
|
|
if sends, xerr := s.gate.IsPaidOrganization(ctx, orgID); xerr != nil {
|
|
return nil, xerr
|
|
} else if !sends {
|
|
return nil, errx.New(errx.BadRequest, "this workspace's plan does not include sending; choose a plan that does to raise this limit")
|
|
}
|
|
}
|
|
current := limitFieldEffective(req.Field, effective)
|
|
if req.Requested <= current {
|
|
return nil, errx.New(errx.BadRequest, "requested value must exceed current effective limit")
|
|
}
|
|
|
|
lr := &models.LimitIncreaseRequest{
|
|
ID: uuid.New(),
|
|
OrganizationID: orgID,
|
|
Field: req.Field,
|
|
CurrentEffective: current,
|
|
Requested: req.Requested,
|
|
Reason: req.Reason,
|
|
Status: models.LimitRequestStatusPending,
|
|
SubmittedBy: submitterID,
|
|
}
|
|
|
|
if err := s.orgRepo.CreateLimitRequest(ctx, lr); err != nil {
|
|
// The (org, field) WHERE status='pending' unique index trips
|
|
// when the same workspace already has an open request for the
|
|
// same resource. Surface as 409 so the dashboard can render
|
|
// "you already have a pending request" instead of a generic
|
|
// 500.
|
|
if strings.Contains(err.Error(), "uq_limit_requests_one_pending_per_field") {
|
|
return nil, errx.New(errx.Conflict, "a pending request already exists for this field")
|
|
}
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to submit request")
|
|
}
|
|
|
|
s.notifyOperator(
|
|
"limit_request.created",
|
|
"Limit increase requested",
|
|
"A workspace asked for more capacity than its plan allows.",
|
|
map[string]string{
|
|
"Workspace": orgID.String(),
|
|
"Field": req.Field,
|
|
"Current": strconv.Itoa(current),
|
|
"Requested": strconv.Itoa(req.Requested),
|
|
"Reason": req.Reason,
|
|
},
|
|
)
|
|
|
|
return lr, nil
|
|
}
|
|
|
|
func (s *organizationService) ListLimitRequestsForOrg(ctx context.Context, orgID, requesterID uuid.UUID) ([]models.LimitIncreaseRequest, *errx.Error) {
|
|
if xerr := s.requireWorkspaceMember(ctx, orgID, requesterID); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
rows, err := s.orgRepo.ListLimitRequestsForOrg(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load requests")
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
// CancelLimitRequest lets the original submitter walk back a pending
|
|
// request. Approved / rejected rows are immutable — they survive as
|
|
// the audit record of what was decided and when.
|
|
func (s *organizationService) CancelLimitRequest(ctx context.Context, id, userID uuid.UUID) *errx.Error {
|
|
lr, err := s.orgRepo.GetLimitRequest(ctx, id)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to load request")
|
|
}
|
|
if lr == nil {
|
|
return errx.New(errx.NotFound, "request not found")
|
|
}
|
|
if lr.SubmittedBy != userID {
|
|
return errx.ErrForbidden
|
|
}
|
|
if xerr := s.requireWorkspaceMember(ctx, lr.OrganizationID, userID); xerr != nil {
|
|
return xerr
|
|
}
|
|
if lr.Status != models.LimitRequestStatusPending {
|
|
return errx.New(errx.BadRequest, "only pending requests can be cancelled")
|
|
}
|
|
if err := s.orgRepo.UpdateLimitRequestStatus(ctx, id, models.LimitRequestStatusCancelled, userID, ""); err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to cancel request")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *organizationService) AdminListLimitRequests(ctx context.Context, search *models.AdminLimitRequestSearch) (*models.AdminLimitRequestsResult, *errx.Error) {
|
|
// field/status are free-form strings on the wire (field has no DB enum), so
|
|
// validate them here rather than relying on query binding.
|
|
if search.Field != "" {
|
|
if _, ok := limitFieldUpdater[search.Field]; !ok {
|
|
return nil, errx.New(errx.BadRequest, "invalid field filter")
|
|
}
|
|
}
|
|
switch search.Status {
|
|
case "", "all",
|
|
string(models.LimitRequestStatusPending),
|
|
string(models.LimitRequestStatusApproved),
|
|
string(models.LimitRequestStatusRejected),
|
|
string(models.LimitRequestStatusCancelled):
|
|
default:
|
|
return nil, errx.New(errx.BadRequest, "invalid status filter")
|
|
}
|
|
|
|
result, err := s.orgRepo.ListLimitRequestsForAdmin(ctx, search)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load limit requests")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// ApproveLimitRequest stamps the row and writes the corresponding
|
|
// override column via SetLimitOverrides — same write path the admin
|
|
// uses for direct overrides, so the granted_by audit trail is unified.
|
|
func (s *organizationService) ApproveLimitRequest(ctx context.Context, id, reviewerID uuid.UUID, notes string) (*models.LimitIncreaseRequest, *errx.Error) {
|
|
lr, err := s.orgRepo.GetLimitRequest(ctx, id)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load request")
|
|
}
|
|
if lr == nil {
|
|
return nil, errx.New(errx.NotFound, "request not found")
|
|
}
|
|
if lr.Status != models.LimitRequestStatusPending {
|
|
return nil, errx.New(errx.BadRequest, "only pending requests can be approved")
|
|
}
|
|
|
|
updater, ok := limitFieldUpdater[lr.Field]
|
|
if !ok {
|
|
return nil, errx.New(errx.Internal, "request references an unknown field")
|
|
}
|
|
|
|
override := &models.UpdateOrgOverridesRequest{}
|
|
updater(override, lr.Requested)
|
|
if notes != "" {
|
|
notesCopy := "approved request " + lr.ID.String() + ": " + notes
|
|
override.Notes = ¬esCopy
|
|
}
|
|
if _, xerr := s.SetLimitOverrides(ctx, lr.OrganizationID, override, reviewerID); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
if err := s.orgRepo.UpdateLimitRequestStatus(ctx, id, models.LimitRequestStatusApproved, reviewerID, notes); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to mark request approved")
|
|
}
|
|
lr.Status = models.LimitRequestStatusApproved
|
|
lr.ReviewedBy = &reviewerID
|
|
lr.ReviewNotes = notes
|
|
return lr, nil
|
|
}
|
|
|
|
func (s *organizationService) RejectLimitRequest(ctx context.Context, id, reviewerID uuid.UUID, notes string) (*models.LimitIncreaseRequest, *errx.Error) {
|
|
lr, err := s.orgRepo.GetLimitRequest(ctx, id)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load request")
|
|
}
|
|
if lr == nil {
|
|
return nil, errx.New(errx.NotFound, "request not found")
|
|
}
|
|
if lr.Status != models.LimitRequestStatusPending {
|
|
return nil, errx.New(errx.BadRequest, "only pending requests can be rejected")
|
|
}
|
|
if err := s.orgRepo.UpdateLimitRequestStatus(ctx, id, models.LimitRequestStatusRejected, reviewerID, notes); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to mark request rejected")
|
|
}
|
|
lr.Status = models.LimitRequestStatusRejected
|
|
lr.ReviewedBy = &reviewerID
|
|
lr.ReviewNotes = notes
|
|
return lr, nil
|
|
}
|
|
|
|
// MaxCustomRolesPerOrg caps role sprawl per workspace.
|
|
const MaxCustomRolesPerOrg = 25
|
|
|
|
// validateRolePermissions enforces the two safety rules for custom roles:
|
|
// transfer-ownership can never be delegated through a role, and an actor can
|
|
// only put permissions into a role that they hold themselves (no privilege
|
|
// escalation by minting a stronger role and self-assigning a teammate).
|
|
func (s *organizationService) validateRolePermissions(ctx context.Context, orgID, actorID uuid.UUID, perms models.OrganizationPermission) *errx.Error {
|
|
if perms&models.PermTransferOwnership != 0 {
|
|
return errx.New(errx.BadRequest, "custom roles cannot include ownership transfer")
|
|
}
|
|
return s.validateActorHoldsPermissions(ctx, orgID, actorID, perms)
|
|
}
|
|
|
|
// validateActorHoldsPermissions rejects granting (via role create/edit OR
|
|
// assignment) any permission the actor does not hold themselves.
|
|
func (s *organizationService) validateActorHoldsPermissions(ctx context.Context, orgID, actorID uuid.UUID, perms models.OrganizationPermission) *errx.Error {
|
|
actor, err := s.orgRepo.GetMember(ctx, orgID, actorID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to load member")
|
|
}
|
|
if actor == nil {
|
|
return errx.New(errx.Forbidden, "not a member")
|
|
}
|
|
// The owner holds every permission, including bits added after its row was written.
|
|
if actor.Role == string(models.RoleOwner) {
|
|
return nil
|
|
}
|
|
if perms&^actor.Permissions != 0 {
|
|
return errx.New(errx.Forbidden, "you cannot grant permissions you do not hold")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateRoleName(name string) (string, *errx.Error) {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" || len(name) > 50 {
|
|
return "", errx.New(errx.BadRequest, "role name must be 1-50 characters")
|
|
}
|
|
if models.IsReservedRoleName(name) {
|
|
return "", errx.New(errx.BadRequest, "that name is reserved for a built-in role")
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
func (s *organizationService) ListRoles(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationRole, *errx.Error) {
|
|
roles, err := s.orgRepo.ListRoles(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to list roles")
|
|
}
|
|
if roles == nil {
|
|
roles = []models.OrganizationRole{}
|
|
}
|
|
return roles, nil
|
|
}
|
|
|
|
func (s *organizationService) CreateRole(ctx context.Context, orgID, actorID uuid.UUID, req *models.CreateOrganizationRoleRequest) (*models.OrganizationRole, *errx.Error) {
|
|
name, xerr := validateRoleName(req.Name)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
perms := models.OrganizationPermission(req.Permissions)
|
|
if xerr := s.validateRolePermissions(ctx, orgID, actorID, perms); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
|
|
count, err := s.orgRepo.CountRoles(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to count roles")
|
|
}
|
|
if count >= MaxCustomRolesPerOrg {
|
|
return nil, errx.New(errx.Forbidden, "custom role limit reached")
|
|
}
|
|
|
|
color := strings.TrimSpace(req.Color)
|
|
if color != "" && !crypt.IsValidHexColor(color) {
|
|
return nil, errx.New(errx.BadRequest, "color must be a hex value like #0ea5e9")
|
|
}
|
|
|
|
role := &models.OrganizationRole{
|
|
ID: uuid.New(),
|
|
OrganizationID: orgID,
|
|
Name: name,
|
|
Description: strings.TrimSpace(req.Description),
|
|
Color: color,
|
|
Permissions: perms,
|
|
ActsInScope: req.ActsInScope,
|
|
}
|
|
if err := s.orgRepo.CreateRole(ctx, role); err != nil {
|
|
// Unique (org, name) violation is the only expected failure here.
|
|
return nil, errx.New(errx.BadRequest, "a role with that name already exists")
|
|
}
|
|
return role, nil
|
|
}
|
|
|
|
func (s *organizationService) UpdateRole(ctx context.Context, orgID, actorID, roleID uuid.UUID, req *models.UpdateOrganizationRoleRequest) (*models.OrganizationRole, *errx.Error) {
|
|
role, err := s.orgRepo.GetRoleByID(ctx, orgID, roleID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to load role")
|
|
}
|
|
if role == nil {
|
|
return nil, errx.New(errx.NotFound, "role not found")
|
|
}
|
|
|
|
if req.Name != nil {
|
|
name, xerr := validateRoleName(*req.Name)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
role.Name = name
|
|
}
|
|
if req.Description != nil {
|
|
role.Description = strings.TrimSpace(*req.Description)
|
|
}
|
|
if req.Color != nil {
|
|
color := strings.TrimSpace(*req.Color)
|
|
if color != "" && !crypt.IsValidHexColor(color) {
|
|
return nil, errx.New(errx.BadRequest, "color must be a hex value like #0ea5e9")
|
|
}
|
|
role.Color = color
|
|
}
|
|
if req.Permissions != nil {
|
|
perms := models.OrganizationPermission(*req.Permissions)
|
|
if xerr := s.validateRolePermissions(ctx, orgID, actorID, perms); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
// Editing takes the old permissions away from everyone holding the
|
|
// role, so the actor must hold those too, as for DeleteRole.
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, actorID, role.Permissions); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
role.Permissions = perms
|
|
}
|
|
// Whether restricted members act with the role changes what it does for them, so the actor must hold it.
|
|
if req.ActsInScope != nil && *req.ActsInScope != role.ActsInScope {
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, actorID, role.Permissions); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
role.ActsInScope = *req.ActsInScope
|
|
}
|
|
|
|
// Write-through: assigned members pick up the new name + permissions
|
|
// atomically (their effective access changes live via the audit spine).
|
|
if err := s.orgRepo.UpdateRole(ctx, role); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to update role")
|
|
}
|
|
return role, nil
|
|
}
|
|
|
|
func (s *organizationService) DeleteRole(ctx context.Context, orgID, actorID, roleID uuid.UUID) *errx.Error {
|
|
// Deleting a role strips its permissions from everyone holding it, so the
|
|
// actor must hold those permissions themselves (symmetry with the grant
|
|
// paths — otherwise a team-manager could de-privilege admins by deleting
|
|
// the Admin role).
|
|
role, rerr := s.orgRepo.GetRoleByID(ctx, orgID, roleID)
|
|
if rerr != nil {
|
|
errs.CaptureException(rerr)
|
|
return errx.New(errx.Internal, "failed to load role")
|
|
}
|
|
if role == nil {
|
|
return nil // already gone — idempotent
|
|
}
|
|
if xerr := s.validateActorHoldsPermissions(ctx, orgID, actorID, role.Permissions); xerr != nil {
|
|
return xerr
|
|
}
|
|
if err := s.orgRepo.DeleteRole(ctx, orgID, roleID); err != nil {
|
|
errs.CaptureException(err)
|
|
return errx.New(errx.Internal, "failed to delete role")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetManagedPlan reports the grant on a workspace, if any.
|
|
func (s *organizationService) GetManagedPlan(ctx context.Context, orgID uuid.UUID) (*models.ManagedPlan, *errx.Error) {
|
|
sub, err := s.subRepo.GetByOrganizationID(ctx, orgID)
|
|
if err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to read the subscription")
|
|
}
|
|
if sub == nil {
|
|
return nil, errx.New(errx.NotFound, "that workspace has no subscription")
|
|
}
|
|
return managedPlanOf(sub), nil
|
|
}
|
|
|
|
// GrantManagedPlan puts a workspace on a plan without Stripe.
|
|
func (s *organizationService) GrantManagedPlan(ctx context.Context, orgID, planID, adminID uuid.UUID, reason string, until *time.Time) (*models.ManagedPlan, *errx.Error) {
|
|
// A grant into the past is almost certainly a timezone or unit mistake,
|
|
// and it would read as "granted" in the audit trail while entitling
|
|
// nothing at all.
|
|
if until != nil && !until.After(time.Now()) {
|
|
return nil, errx.New(errx.BadRequest, "the grant would already have expired; leave it open-ended or pick a future date")
|
|
}
|
|
if s.planRepo != nil {
|
|
plan, perr := s.planRepo.GetByID(ctx, planID)
|
|
if perr != nil {
|
|
errs.CaptureException(perr)
|
|
return nil, errx.New(errx.Internal, "failed to look up the plan")
|
|
}
|
|
if plan == nil {
|
|
return nil, errx.New(errx.BadRequest, "that plan does not exist")
|
|
}
|
|
// An agency plan sends from the agency's pool, which one workspace on its own does not have.
|
|
if plan.IsAgencyPlan() {
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, "agency_plan_needs_agency",
|
|
"Agency plans are given to an agency, not to one workspace. Open the agency under Agencies and give it the plan there; its client workspaces receive it.")
|
|
}
|
|
}
|
|
if err := s.subRepo.SetManagedPlan(ctx, orgID, planID, adminID, reason, until); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to grant the plan")
|
|
}
|
|
if err := s.subRepo.ResumeTrialWarmup(ctx, orgID); err != nil {
|
|
errs.CaptureException(err)
|
|
}
|
|
return s.GetManagedPlan(ctx, orgID)
|
|
}
|
|
|
|
// RevokeManagedPlan ends a grant. The workspace keeps the plan row it was on
|
|
// and stops counting as paid, which is where an expired grant leaves it too.
|
|
func (s *organizationService) RevokeManagedPlan(ctx context.Context, orgID uuid.UUID) (*models.ManagedPlan, *errx.Error) {
|
|
if err := s.subRepo.ClearManagedPlan(ctx, orgID); err != nil {
|
|
errs.CaptureException(err)
|
|
return nil, errx.New(errx.Internal, "failed to revoke the plan")
|
|
}
|
|
return s.GetManagedPlan(ctx, orgID)
|
|
}
|
|
|
|
func managedPlanOf(sub *models.Subscription) *models.ManagedPlan {
|
|
out := &models.ManagedPlan{
|
|
Managed: sub.IsManaged(),
|
|
Expired: sub.ManagedExpired(),
|
|
GrantedAt: sub.ManagedAt,
|
|
GrantedBy: sub.ManagedBy,
|
|
Reason: sub.ManagedReason,
|
|
Until: sub.ManagedUntil,
|
|
PlanID: sub.EffectivePlanID(),
|
|
}
|
|
return out
|
|
}
|