feat(invitations): implement pending invitations feature with polling and dialog

Added functionality for managing pending invitations, including a polling mechanism to update the invitation count in real-time. Introduced a new dialog component for users to view and respond to their invitations without navigating away from their current context. Updated API endpoints for fetching and managing invitations, and enhanced the user interface with relevant internationalization support.

Refs: #1303
This commit is contained in:
wizardchen
2026-05-17 21:19:59 +08:00
committed by lyingbug
parent 3bb0d6d763
commit 884ac44283
36 changed files with 4378 additions and 440 deletions
@@ -0,0 +1,257 @@
package repository
import (
"context"
"errors"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// ErrPendingInvitationExists is returned by Create when a pending
// invitation for (tenant_id, invitee_user_id) already exists. The
// service layer maps it to its own sentinel for the handler.
var ErrPendingInvitationExists = errors.New("repository: pending invitation already exists")
// tenantInvitationRepository implements interfaces.TenantInvitationRepository.
type tenantInvitationRepository struct {
db *gorm.DB
}
// NewTenantInvitationRepository constructs the repo against db. Wired
// up via the dig container alongside other repositories.
func NewTenantInvitationRepository(db *gorm.DB) interfaces.TenantInvitationRepository {
return &tenantInvitationRepository{db: db}
}
// Create inserts a new pending invitation row. The partial unique
// index on (tenant_id, invitee_user_id) WHERE status='pending' is the
// authoritative guard against duplicates, but we ALSO pre-check via
// GetPendingByPair inside a tiny transaction so the typical "click
// twice fast" case returns a clean sentinel instead of a raw 23505 /
// SQLITE_CONSTRAINT error string the handler would have to parse.
//
// The pre-check is best-effort: two concurrent inserts can still race
// past it, in which case the underlying database error surfaces. The
// service layer treats any insert error containing the index name
// (idx_tenant_invitations_unique_pending) as the conflict sentinel —
// see invitationService.Create.
func (r *tenantInvitationRepository) Create(
ctx context.Context,
inv *types.TenantInvitation,
) error {
if inv.Status == "" {
inv.Status = types.TenantInvitationStatusPending
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var probe types.TenantInvitation
err := tx.
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
First(&probe).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
// fallthrough — clean to insert.
case err != nil:
return err
default:
return ErrPendingInvitationExists
}
return tx.Create(inv).Error
})
}
// GetByID returns the invitation row (regardless of status) or
// (nil, nil) when missing. Used by Accept/Decline/Revoke flows that
// must inspect status before transitioning.
func (r *tenantInvitationRepository) GetByID(
ctx context.Context,
id uint64,
) (*types.TenantInvitation, error) {
var inv types.TenantInvitation
err := r.db.WithContext(ctx).Where("id = ?", id).First(&inv).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &inv, nil
}
// GetPendingByPair returns the in-flight pending invitation, if any.
func (r *tenantInvitationRepository) GetPendingByPair(
ctx context.Context,
tenantID uint64,
inviteeUserID string,
) (*types.TenantInvitation, error) {
var inv types.TenantInvitation
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
tenantID, inviteeUserID, types.TenantInvitationStatusPending).
First(&inv).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &inv, nil
}
// listQuery centralises the "newest-first" ordering and includeTerminal
// filter so ListByTenant / ListByInvitee stay short.
func (r *tenantInvitationRepository) listQuery(includeTerminal bool) *gorm.DB {
q := r.db.Order("id DESC")
if !includeTerminal {
q = q.Where("status = ?", types.TenantInvitationStatusPending)
}
return q
}
// tenantInvitationTenantScope applies tenant_id, optional pending-only
// filter, and id DESC ordering — shared by ListByTenant and paging helpers.
func (r *tenantInvitationRepository) tenantInvitationTenantScope(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
) *gorm.DB {
q := r.db.WithContext(ctx).
Model(&types.TenantInvitation{}).
Where("tenant_id = ?", tenantID).
Order("id DESC")
if !includeTerminal {
q = q.Where("status = ?", types.TenantInvitationStatusPending)
}
return q
}
// ListByTenant returns invitations for the tenant ordered by id DESC.
func (r *tenantInvitationRepository) ListByTenant(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
) ([]*types.TenantInvitation, error) {
var rows []*types.TenantInvitation
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).Find(&rows).Error
if err != nil {
return nil, err
}
return rows, nil
}
// CountByTenantList counts invitations matching ListByTenant filters.
func (r *tenantInvitationRepository) CountByTenantList(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
) (int64, error) {
var n int64
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
Count(&n).Error
return n, err
}
// ListByTenantPage returns a page of invitations (id DESC).
func (r *tenantInvitationRepository) ListByTenantPage(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
offset, limit int,
) ([]*types.TenantInvitation, error) {
var rows []*types.TenantInvitation
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
Offset(offset).
Limit(limit).
Find(&rows).Error
if err != nil {
return nil, err
}
return rows, nil
}
// ListByInvitee returns invitations addressed to the user across all
// tenants.
func (r *tenantInvitationRepository) ListByInvitee(
ctx context.Context,
inviteeUserID string,
includeTerminal bool,
) ([]*types.TenantInvitation, error) {
var rows []*types.TenantInvitation
err := r.listQuery(includeTerminal).
WithContext(ctx).
Where("invitee_user_id = ?", inviteeUserID).
Find(&rows).Error
if err != nil {
return nil, err
}
return rows, nil
}
// CountPendingByInvitee returns the pending invitation count for the user.
func (r *tenantInvitationRepository) CountPendingByInvitee(
ctx context.Context,
inviteeUserID string,
) (int64, error) {
var count int64
err := r.db.WithContext(ctx).
Model(&types.TenantInvitation{}).
Where("invitee_user_id = ? AND status = ?",
inviteeUserID, types.TenantInvitationStatusPending).
Count(&count).Error
return count, err
}
// MarkStatusIfPending atomically transitions a row from pending to
// the supplied terminal status. The WHERE filter on status='pending'
// is what makes this safe under concurrent accept/revoke clicks —
// only the first writer succeeds; the second sees RowsAffected=0 and
// receives gorm.ErrRecordNotFound (which the service maps to a
// "already finalised" sentinel).
func (r *tenantInvitationRepository) MarkStatusIfPending(
ctx context.Context,
id uint64,
status types.TenantInvitationStatus,
respondedAt time.Time,
) error {
res := r.db.WithContext(ctx).
Model(&types.TenantInvitation{}).
Where("id = ? AND status = ?", id, types.TenantInvitationStatusPending).
Updates(map[string]any{
"status": status,
"responded_at": respondedAt,
"updated_at": time.Now(),
})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
// SweepExpired transitions all overdue pending rows to expired in a
// single batch. We intentionally don't emit per-row audit events from
// here — the original rbac.invitation_sent already lives in the audit
// log, and a sweep can touch many rows on a sleepy weekend (an audit
// fanout would dwarf the original event volume).
func (r *tenantInvitationRepository) SweepExpired(
ctx context.Context,
now time.Time,
) (int64, error) {
res := r.db.WithContext(ctx).
Model(&types.TenantInvitation{}).
Where("status = ? AND expires_at < ?", types.TenantInvitationStatusPending, now).
Updates(map[string]any{
"status": types.TenantInvitationStatusExpired,
"responded_at": now,
"updated_at": time.Now(),
})
if res.Error != nil {
return 0, res.Error
}
return res.RowsAffected, nil
}
@@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -92,6 +93,56 @@ func (r *tenantMemberRepository) ListByTenant(ctx context.Context, tenantID uint
return members, nil
}
// CountFilteredByTenant counts active tenant membership rows, optionally
// restricted to users whose email or username matches search.
func (r *tenantMemberRepository) CountFilteredByTenant(
ctx context.Context, tenantID uint64, search string,
) (int64, error) {
search = strings.TrimSpace(search)
q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
Where("tenant_id = ?", tenantID)
var total int64
var err error
if search == "" {
err = q.Count(&total).Error
} else {
like := "%" + escapeLikePattern(search) + "%"
err = q.
Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
Count(&total).Error
}
return total, err
}
// ListPagedByTenant lists active memberships with stable sort.
func (r *tenantMemberRepository) ListPagedByTenant(
ctx context.Context, tenantID uint64, search string, offset, limit int,
) ([]*types.TenantMember, error) {
search = strings.TrimSpace(search)
var members []*types.TenantMember
q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
Where("tenant_id = ?", tenantID).
Order("tenant_members.joined_at ASC, tenant_members.id ASC").
Offset(offset).
Limit(limit)
var err error
if search == "" {
err = q.Find(&members).Error
} else {
like := "%" + escapeLikePattern(search) + "%"
err = q.
Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
Find(&members).Error
}
if err != nil {
return nil, err
}
return members, nil
}
// UpdateRole changes the role of an existing active membership.
func (r *tenantMemberRepository) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
res := r.db.WithContext(ctx).
@@ -0,0 +1,430 @@
package service
import (
"context"
"encoding/json"
"errors"
"os"
"strconv"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// Sentinel errors returned by tenantInvitationService. Callers compare
// with errors.Is to render the appropriate HTTP responses.
var (
// ErrInvitationNotFound is returned when no invitation row matches
// the supplied id.
ErrInvitationNotFound = errors.New("invitation not found")
// ErrPendingInvitationExists is returned by Create when a pending
// invitation for (tenant, invitee) is already in flight. The
// handler maps this to 409.
ErrPendingInvitationExists = errors.New("a pending invitation for this user already exists")
// ErrAlreadyMember is returned by Create when the invitee is
// already an active member of the tenant; sending an invite would
// be a no-op at best and a confusing UX at worst.
ErrAlreadyMember = errors.New("user is already an active member of the tenant")
// ErrInvitationNotPending is returned by Accept / Decline / Revoke
// when the row exists but has already been finalised. Maps to 409.
ErrInvitationNotPending = errors.New("invitation is no longer pending")
// ErrInvitationExpired is returned by Accept / Decline when the
// pending row has aged past its expires_at. Maps to 410.
ErrInvitationExpired = errors.New("invitation has expired")
// ErrInvitationForbidden is returned by Accept / Decline when the
// caller is not the invitee. Owner-driven Revoke is gated at the
// route layer so this error only surfaces on the /me/ paths.
ErrInvitationForbidden = errors.New("only the invitee can accept or decline this invitation")
)
// defaultInvitationTTL is the lifetime of a pending invitation before
// the lazy sweep transitions it to expired. Operator override is via
// the WEKNORA_INVITATION_TTL env var (Go duration: "168h", "7d-ish");
// keeping this out of TenantConfig avoids a yaml migration for a knob
// that almost nobody is going to tweak.
const defaultInvitationTTL = 7 * 24 * time.Hour
// invitationTTL resolves the effective TTL at call time so an operator
// can hot-reload the override without restarting. The env var is parsed
// once per call; cost is negligible and beats a goroutine watching the
// environment.
func invitationTTL() time.Duration {
raw := os.Getenv("WEKNORA_INVITATION_TTL")
if raw == "" {
return defaultInvitationTTL
}
if d, err := time.ParseDuration(raw); err == nil && d > 0 {
return d
}
// Allow "604800" seconds for callers that don't like Go duration
// syntax — same shape as the rest of our int env knobs.
if secs, err := strconv.ParseInt(raw, 10, 64); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
return defaultInvitationTTL
}
// tenantInvitationService implements interfaces.TenantInvitationService.
type tenantInvitationService struct {
repo interfaces.TenantInvitationRepository
memberSvc interfaces.TenantMemberService
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
now func() time.Time // injection seam for tests
}
// NewTenantInvitationService wires the dependencies. memberSvc is
// required (Accept must create the tenant_members row); audit is
// optional and matches the same nil-safe pattern tenantMemberService
// uses.
func NewTenantInvitationService(
repo interfaces.TenantInvitationRepository,
memberSvc interfaces.TenantMemberService,
audit interfaces.AuditLogService,
) interfaces.TenantInvitationService {
return &tenantInvitationService{
repo: repo,
memberSvc: memberSvc,
audit: audit,
now: time.Now,
}
}
// emitAudit is the best-effort audit hook; mirrors tenantMemberService.
func (s *tenantInvitationService) emitAudit(ctx context.Context, entry *types.AuditLog) {
if s.audit == nil {
return
}
_ = s.audit.Log(ctx, entry)
}
// detailsFor packs the role + invitation id into the audit Details so a
// reader can reconstruct "Alice invited Bob as Admin (inv #42)" without
// joining back to the invitations table.
func detailsFor(invID uint64, role types.TenantRole) types.JSON {
b, _ := json.Marshal(map[string]any{
"invitation_id": invID,
"role": string(role),
})
return types.JSON(b)
}
// sweep transitions overdue pending rows to expired before any List/
// Accept/Decline/Count read. Failures are logged and swallowed — a
// transient sweep error must not block a user from reading their
// inbox; the next call will sweep again.
func (s *tenantInvitationService) sweep(ctx context.Context) {
if _, err := s.repo.SweepExpired(ctx, s.now()); err != nil {
logger.Warnf(ctx, "tenant_invitation lazy sweep failed: %v", err)
}
}
// Create issues a new pending invitation. Returns the standard
// conflict sentinels for the duplicate-pending and already-member
// cases.
func (s *tenantInvitationService) Create(
ctx context.Context,
tenantID uint64,
inviteeUserID string,
role types.TenantRole,
invitedBy *string,
message string,
) (*types.TenantInvitation, error) {
if !role.IsValid() {
return nil, ErrInvalidTenantRole
}
// Reject early if the invitee is already an active member; the
// handler renders this as "they're already in" rather than the
// generic conflict.
existing, err := s.memberSvc.GetMembership(ctx, inviteeUserID, tenantID)
if err != nil {
return nil, err
}
if existing != nil && existing.Status == types.TenantMemberStatusActive {
return nil, ErrAlreadyMember
}
now := s.now()
inv := &types.TenantInvitation{
TenantID: tenantID,
InviteeUserID: inviteeUserID,
InvitedBy: invitedBy,
Role: role,
Status: types.TenantInvitationStatusPending,
Message: message,
ExpiresAt: now.Add(invitationTTL()),
}
if err := s.repo.Create(ctx, inv); err != nil {
if errors.Is(err, apprepo.ErrPendingInvitationExists) {
return nil, ErrPendingInvitationExists
}
return nil, err
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationSent,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
TargetUserID: inviteeUserID,
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, role),
})
return inv, nil
}
// Accept transitions a pending invitation into accepted AND creates
// the active tenant_members row in the same flow. We do NOT wrap both
// writes in a single DB transaction because TenantMemberService.AddMember
// owns its own write + audit emit and reaching across services here
// would force the audit-log writes to commit/rollback in lockstep.
// Instead, we order operations so the user-visible failure mode is
// "you couldn't accept the invitation"; if the membership insert fails
// AFTER the invitation transition committed (rare; collision on the
// tenant_members unique index would be the only realistic case), the
// row already in tenant_members wins and a subsequent Accept call sees
// ErrInvitationNotPending which the handler renders as 409.
func (s *tenantInvitationService) Accept(
ctx context.Context,
invID uint64,
callerUserID string,
) (*types.TenantMember, error) {
s.sweep(ctx)
inv, err := s.repo.GetByID(ctx, invID)
if err != nil {
return nil, err
}
if inv == nil {
return nil, ErrInvitationNotFound
}
if inv.InviteeUserID != callerUserID {
return nil, ErrInvitationForbidden
}
if inv.Status != types.TenantInvitationStatusPending {
return nil, ErrInvitationNotPending
}
if inv.IsExpired(s.now()) {
// The sweep above should have flipped it already, but a row
// can age past expires_at between the sweep and this read.
// Treat it as expired regardless.
return nil, ErrInvitationExpired
}
now := s.now()
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusAccepted, now); err != nil {
// Another goroutine (concurrent click) won the race. Honour
// the state machine.
return nil, ErrInvitationNotPending
}
// Create the actual tenant_members row. Cross-service hop: the
// member service handles its own audit (rbac.member_added) and
// also enforces the (user, tenant) uniqueness invariant via the
// repo. If it fails here the invitation is already accepted —
// see comment above for why we don't rollback the invitation.
member, err := s.memberSvc.AddMember(ctx, inv.InviteeUserID, inv.TenantID, inv.Role, inv.InvitedBy)
if err != nil {
// Special-case "already a member": that's the idempotent
// outcome we want. Return the existing membership instead of
// bubbling the error up to the invitee.
if errors.Is(err, ErrMembershipAlreadyExists) {
existing, getErr := s.memberSvc.GetMembership(ctx, inv.InviteeUserID, inv.TenantID)
if getErr == nil && existing != nil {
s.emitInvitationAccepted(ctx, inv)
return existing, nil
}
}
logger.Errorf(ctx,
"invitation %d accepted but tenant_members insert failed: %v",
invID, err)
return nil, err
}
s.emitInvitationAccepted(ctx, inv)
return member, nil
}
// emitInvitationAccepted writes the rbac.invitation_accepted audit row.
// Actor is the invitee (acting on their own inbox); target is the same
// user since the action is self-directed.
func (s *tenantInvitationService) emitInvitationAccepted(ctx context.Context, inv *types.TenantInvitation) {
s.emitAudit(ctx, &types.AuditLog{
TenantID: inv.TenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationAccepted,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
TargetUserID: inv.InviteeUserID,
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, inv.Role),
})
}
// Decline transitions the pending row into declined. Only the invitee
// themselves can call this.
func (s *tenantInvitationService) Decline(
ctx context.Context,
invID uint64,
callerUserID string,
) error {
s.sweep(ctx)
inv, err := s.repo.GetByID(ctx, invID)
if err != nil {
return err
}
if inv == nil {
return ErrInvitationNotFound
}
if inv.InviteeUserID != callerUserID {
return ErrInvitationForbidden
}
if inv.Status != types.TenantInvitationStatusPending {
return ErrInvitationNotPending
}
if inv.IsExpired(s.now()) {
return ErrInvitationExpired
}
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusDeclined, s.now()); err != nil {
return ErrInvitationNotPending
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: inv.TenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationDeclined,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
TargetUserID: inv.InviteeUserID,
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, inv.Role),
})
return nil
}
// Revoke transitions the pending row into revoked. Route-layer Owner
// gate guarantees the caller is allowed to act on this tenant; this
// method does not re-check role.
func (s *tenantInvitationService) Revoke(ctx context.Context, invID uint64) error {
s.sweep(ctx)
inv, err := s.repo.GetByID(ctx, invID)
if err != nil {
return err
}
if inv == nil {
return ErrInvitationNotFound
}
if inv.Status != types.TenantInvitationStatusPending {
return ErrInvitationNotPending
}
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusRevoked, s.now()); err != nil {
return ErrInvitationNotPending
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: inv.TenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationRevoked,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
TargetUserID: inv.InviteeUserID,
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, inv.Role),
})
return nil
}
// GetByID returns the row or (nil, nil) without sweeping. The handler
// uses this for narrow per-row checks where running a full sweep just
// to read one row would be wasted work; List* paths still sweep.
func (s *tenantInvitationService) GetByID(
ctx context.Context,
invID uint64,
) (*types.TenantInvitation, error) {
return s.repo.GetByID(ctx, invID)
}
// ListByTenant sweeps then returns. The tenant-side management UI
// expects expired rows to surface correctly; running the sweep here
// guarantees the page reflects reality even if no other code path has
// touched the table recently.
func (s *tenantInvitationService) ListByTenant(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
) ([]*types.TenantInvitation, error) {
s.sweep(ctx)
return s.repo.ListByTenant(ctx, tenantID, includeTerminal)
}
// ListTenantInvitationsPage sweeps then returns a page plus total rows
// matching the same filter as ListByTenant.
func (s *tenantInvitationService) ListTenantInvitationsPage(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
page, pageSize int,
) ([]*types.TenantInvitation, int64, error) {
const (
defSize = 20
maxSize = 100
)
s.sweep(ctx)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = defSize
}
if pageSize > maxSize {
pageSize = maxSize
}
total, err := s.repo.CountByTenantList(ctx, tenantID, includeTerminal)
if err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
rows, err := s.repo.ListByTenantPage(ctx, tenantID, includeTerminal, offset, pageSize)
if err != nil {
return nil, 0, err
}
return rows, total, nil
}
// ListByInvitee sweeps then returns. Same reasoning as ListByTenant.
func (s *tenantInvitationService) ListByInvitee(
ctx context.Context,
inviteeUserID string,
includeTerminal bool,
) ([]*types.TenantInvitation, error) {
s.sweep(ctx)
return s.repo.ListByInvitee(ctx, inviteeUserID, includeTerminal)
}
// CountPendingByInvitee sweeps then counts. The avatar-row badge polls
// this endpoint so a stale sweep would manifest as a phantom "1" on
// the bell icon for the full polling interval; sweeping inline is
// worth the extra UPDATE.
func (s *tenantInvitationService) CountPendingByInvitee(
ctx context.Context,
inviteeUserID string,
) (int64, error) {
s.sweep(ctx)
return s.repo.CountPendingByInvitee(ctx, inviteeUserID)
}
@@ -0,0 +1,397 @@
package service
import (
"context"
"errors"
"sort"
"testing"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// fakeInvitationRepo is an in-memory stand-in for
// interfaces.TenantInvitationRepository. The implementation is
// deliberately tiny — these tests focus on the service-layer state
// machine (Accept / Decline / Revoke / lazy sweep / duplicate guard)
// rather than the SQL surface. The production repo gets exercised via
// the real DB in repo tests if/when those are added.
type fakeInvitationRepo struct {
rows []*types.TenantInvitation
nextID uint64
}
func newFakeInvitationRepo() *fakeInvitationRepo { return &fakeInvitationRepo{} }
func (r *fakeInvitationRepo) Create(ctx context.Context, inv *types.TenantInvitation) error {
for _, e := range r.rows {
if e.TenantID == inv.TenantID &&
e.InviteeUserID == inv.InviteeUserID &&
e.Status == types.TenantInvitationStatusPending {
return apprepo.ErrPendingInvitationExists
}
}
r.nextID++
inv.ID = r.nextID
inv.CreatedAt = time.Now()
inv.UpdatedAt = inv.CreatedAt
cp := *inv
r.rows = append(r.rows, &cp)
return nil
}
func (r *fakeInvitationRepo) GetByID(ctx context.Context, id uint64) (*types.TenantInvitation, error) {
for _, e := range r.rows {
if e.ID == id {
cp := *e
return &cp, nil
}
}
return nil, nil
}
func (r *fakeInvitationRepo) GetPendingByPair(
ctx context.Context, tenantID uint64, inviteeUserID string,
) (*types.TenantInvitation, error) {
for _, e := range r.rows {
if e.TenantID == tenantID &&
e.InviteeUserID == inviteeUserID &&
e.Status == types.TenantInvitationStatusPending {
cp := *e
return &cp, nil
}
}
return nil, nil
}
func (r *fakeInvitationRepo) filteredTenantRows(
tenantID uint64, includeTerminal bool,
) []*types.TenantInvitation {
var out []*types.TenantInvitation
for _, e := range r.rows {
if e.TenantID != tenantID {
continue
}
if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
continue
}
cp := *e
out = append(out, &cp)
}
sort.SliceStable(out, func(i, j int) bool {
return out[i].ID > out[j].ID
})
return out
}
func (r *fakeInvitationRepo) ListByTenant(
ctx context.Context, tenantID uint64, includeTerminal bool,
) ([]*types.TenantInvitation, error) {
return r.filteredTenantRows(tenantID, includeTerminal), nil
}
func (r *fakeInvitationRepo) CountByTenantList(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
) (int64, error) {
return int64(len(r.filteredTenantRows(tenantID, includeTerminal))), nil
}
func (r *fakeInvitationRepo) ListByTenantPage(
ctx context.Context,
tenantID uint64,
includeTerminal bool,
offset, limit int,
) ([]*types.TenantInvitation, error) {
all := r.filteredTenantRows(tenantID, includeTerminal)
if offset >= len(all) {
return []*types.TenantInvitation{}, nil
}
end := offset + limit
if end > len(all) {
end = len(all)
}
return append([]*types.TenantInvitation(nil), all[offset:end]...), nil
}
func (r *fakeInvitationRepo) ListByInvitee(
ctx context.Context, inviteeUserID string, includeTerminal bool,
) ([]*types.TenantInvitation, error) {
var out []*types.TenantInvitation
for _, e := range r.rows {
if e.InviteeUserID != inviteeUserID {
continue
}
if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
continue
}
cp := *e
out = append(out, &cp)
}
return out, nil
}
func (r *fakeInvitationRepo) CountPendingByInvitee(
ctx context.Context, inviteeUserID string,
) (int64, error) {
var n int64
for _, e := range r.rows {
if e.InviteeUserID == inviteeUserID &&
e.Status == types.TenantInvitationStatusPending {
n++
}
}
return n, nil
}
func (r *fakeInvitationRepo) MarkStatusIfPending(
ctx context.Context,
id uint64,
status types.TenantInvitationStatus,
respondedAt time.Time,
) error {
for _, e := range r.rows {
if e.ID == id && e.Status == types.TenantInvitationStatusPending {
e.Status = status
e.RespondedAt = &respondedAt
e.UpdatedAt = time.Now()
return nil
}
}
return gormErrRecordNotFound
}
func (r *fakeInvitationRepo) SweepExpired(
ctx context.Context, now time.Time,
) (int64, error) {
var n int64
for _, e := range r.rows {
if e.Status == types.TenantInvitationStatusPending && e.ExpiresAt.Before(now) {
e.Status = types.TenantInvitationStatusExpired
e.RespondedAt = &now
e.UpdatedAt = time.Now()
n++
}
}
return n, nil
}
var _ interfaces.TenantInvitationRepository = (*fakeInvitationRepo)(nil)
// newInvitationSvc returns a service wired against in-memory fakes for
// both the invitation repo and the member service. Audit is nil so
// the lazy emitAudit short-circuit keeps the test surface focused.
func newInvitationSvc() (
interfaces.TenantInvitationService,
*fakeInvitationRepo,
interfaces.TenantMemberService,
) {
invRepo := newFakeInvitationRepo()
memberSvc, _ := newServiceWithRepo()
svc := NewTenantInvitationService(invRepo, memberSvc, nil)
return svc, invRepo, memberSvc
}
func TestInvitationService_Create_RejectsInvalidRole(t *testing.T) {
svc, _, _ := newInvitationSvc()
_, err := svc.Create(context.Background(), 1, "u-bob", types.TenantRole("magician"), nil, "")
if !errors.Is(err, ErrInvalidTenantRole) {
t.Fatalf("want ErrInvalidTenantRole, got %v", err)
}
}
func TestInvitationService_Create_RejectsAlreadyActiveMember(t *testing.T) {
svc, _, memberSvc := newInvitationSvc()
ctx := context.Background()
if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleContributor, nil); err != nil {
t.Fatalf("seed: %v", err)
}
_, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
if !errors.Is(err, ErrAlreadyMember) {
t.Fatalf("want ErrAlreadyMember, got %v", err)
}
}
func TestInvitationService_Create_DedupsPending(t *testing.T) {
svc, _, _ := newInvitationSvc()
ctx := context.Background()
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
t.Fatalf("first invite: %v", err)
}
_, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
if !errors.Is(err, ErrPendingInvitationExists) {
t.Fatalf("want ErrPendingInvitationExists, got %v", err)
}
}
func TestInvitationService_Accept_OnlyByInvitee(t *testing.T) {
svc, _, _ := newInvitationSvc()
ctx := context.Background()
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if _, err := svc.Accept(ctx, inv.ID, "u-eve"); !errors.Is(err, ErrInvitationForbidden) {
t.Fatalf("non-invitee must be forbidden, got %v", err)
}
}
func TestInvitationService_Accept_HappyPath_CreatesMembership(t *testing.T) {
svc, _, memberSvc := newInvitationSvc()
ctx := context.Background()
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
mb, err := svc.Accept(ctx, inv.ID, "u-bob")
if err != nil {
t.Fatalf("accept: %v", err)
}
if mb == nil || mb.UserID != "u-bob" || mb.Role != types.TenantRoleAdmin {
t.Fatalf("unexpected membership: %+v", mb)
}
// Re-acceptance must be a state-machine rejection, not silent
// success — otherwise a duplicate click double-creates audit rows.
if _, err := svc.Accept(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
t.Fatalf("re-accept must reject as ErrInvitationNotPending, got %v", err)
}
// And the membership service must see the row exactly once.
got, _ := memberSvc.GetMembership(ctx, "u-bob", 1)
if got == nil {
t.Fatalf("membership row missing after accept")
}
}
func TestInvitationService_Accept_IdempotentWhenAlreadyMember(t *testing.T) {
// If the invitee somehow became an active member between Create
// and Accept (e.g. a parallel direct-add via POST /members), the
// Accept call must not 500 — it should fold gracefully into "you
// are already in" and flip the invitation to accepted for audit.
svc, invRepo, memberSvc := newInvitationSvc()
ctx := context.Background()
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
// Side-effect: mint the membership directly.
if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleViewer, nil); err != nil {
t.Fatalf("side-effect AddMember: %v", err)
}
mb, err := svc.Accept(ctx, inv.ID, "u-bob")
if err != nil {
t.Fatalf("accept must be idempotent, got %v", err)
}
if mb == nil || mb.Role != types.TenantRoleViewer {
// Returns the pre-existing membership; the role on the
// invitation does NOT clobber a real membership row.
t.Fatalf("unexpected membership after idempotent accept: %+v", mb)
}
// Invitation row must reflect accepted state so the inbox no
// longer surfaces it as pending.
row, _ := invRepo.GetByID(ctx, inv.ID)
if row == nil || row.Status != types.TenantInvitationStatusAccepted {
t.Fatalf("invitation must be accepted after idempotent accept, got %+v", row)
}
}
func TestInvitationService_Decline_MarksDeclined(t *testing.T) {
svc, invRepo, _ := newInvitationSvc()
ctx := context.Background()
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if err := svc.Decline(ctx, inv.ID, "u-bob"); err != nil {
t.Fatalf("decline: %v", err)
}
row, _ := invRepo.GetByID(ctx, inv.ID)
if row.Status != types.TenantInvitationStatusDeclined {
t.Fatalf("want declined status, got %s", row.Status)
}
if err := svc.Decline(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
t.Fatalf("double-decline must reject, got %v", err)
}
}
func TestInvitationService_Revoke_MarksRevoked(t *testing.T) {
svc, invRepo, _ := newInvitationSvc()
ctx := context.Background()
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if err := svc.Revoke(ctx, inv.ID); err != nil {
t.Fatalf("revoke: %v", err)
}
row, _ := invRepo.GetByID(ctx, inv.ID)
if row.Status != types.TenantInvitationStatusRevoked {
t.Fatalf("want revoked status, got %s", row.Status)
}
// Revoked rows can be re-invited via a fresh Create — the
// partial unique index only guards PENDING.
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
t.Fatalf("re-invite after revoke must succeed, got %v", err)
}
}
func TestInvitationService_LazySweepExpires(t *testing.T) {
// Drop a row directly into the repo with an ExpiresAt in the past,
// then call ListByInvitee — the sweep must flip it to expired
// before the read returns.
svc, invRepo, _ := newInvitationSvc()
now := time.Now()
stale := &types.TenantInvitation{
TenantID: 1,
InviteeUserID: "u-bob",
Role: types.TenantRoleViewer,
Status: types.TenantInvitationStatusPending,
ExpiresAt: now.Add(-time.Hour),
}
if err := invRepo.Create(context.Background(), stale); err != nil {
t.Fatalf("seed stale: %v", err)
}
rows, err := svc.ListByInvitee(context.Background(), "u-bob", true)
if err != nil {
t.Fatalf("list: %v", err)
}
if len(rows) != 1 || rows[0].Status != types.TenantInvitationStatusExpired {
t.Fatalf("expected expired row after sweep, got %+v", rows)
}
// And accepting an expired invitation must fail loudly rather than
// quietly creating the membership.
if _, err := svc.Accept(context.Background(), stale.ID, "u-bob"); err == nil {
t.Fatalf("accept on expired invitation must fail")
}
}
func TestInvitationService_CountPending(t *testing.T) {
svc, _, _ := newInvitationSvc()
ctx := context.Background()
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, ""); err != nil {
t.Fatalf("seed1: %v", err)
}
if _, err := svc.Create(ctx, 2, "u-bob", types.TenantRoleAdmin, nil, ""); err != nil {
t.Fatalf("seed2: %v", err)
}
n, err := svc.CountPendingByInvitee(ctx, "u-bob")
if err != nil {
t.Fatalf("count: %v", err)
}
if n != 2 {
t.Fatalf("want 2 pending, got %d", n)
}
// Decline one; count drops.
rows, _ := svc.ListByInvitee(ctx, "u-bob", false)
if err := svc.Decline(ctx, rows[0].ID, "u-bob"); err != nil {
t.Fatalf("decline: %v", err)
}
n, _ = svc.CountPendingByInvitee(ctx, "u-bob")
if n != 1 {
t.Fatalf("want 1 pending after decline, got %d", n)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"strings"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
@@ -33,6 +34,11 @@ var (
ErrLastOwner = errors.New("cannot demote or remove the last active owner of the tenant")
)
const (
listMembersDefaultPageSize = 20
listMembersMaxPageSize = 100
)
// tenantMemberService implements interfaces.TenantMemberService.
type tenantMemberService struct {
repo interfaces.TenantMemberRepository
@@ -172,6 +178,36 @@ func (s *tenantMemberService) ListByTenant(ctx context.Context, tenantID uint64)
return s.repo.ListByTenant(ctx, tenantID)
}
// ListMembersPage returns a slice plus total matching query (handlers parse
// page/page_size; defensive clamps here mirror list handler limits).
func (s *tenantMemberService) ListMembersPage(
ctx context.Context,
tenantID uint64,
query string,
page, pageSize int,
) ([]*types.TenantMember, int64, error) {
query = strings.TrimSpace(query)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = listMembersDefaultPageSize
}
if pageSize > listMembersMaxPageSize {
pageSize = listMembersMaxPageSize
}
total, err := s.repo.CountFilteredByTenant(ctx, tenantID, query)
if err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
members, err := s.repo.ListPagedByTenant(ctx, tenantID, query, offset, pageSize)
if err != nil {
return nil, 0, err
}
return members, total, nil
}
// HasAnyMembers proxies to the repository.
func (s *tenantMemberService) HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error) {
return s.repo.HasAnyMembers(ctx, tenantID)
@@ -3,6 +3,8 @@ package service
import (
"context"
"errors"
"sort"
"strings"
"testing"
"time"
@@ -90,6 +92,50 @@ func (r *fakeTenantMemberRepo) ListByTenant(ctx context.Context, tenantID uint64
return out, nil
}
func (r *fakeTenantMemberRepo) filterTenantRows(tenantID uint64, search string) []*types.TenantMember {
search = strings.TrimSpace(strings.ToLower(search))
var out []*types.TenantMember
for _, e := range r.rows {
if e.TenantID != tenantID || e.DeletedAt.Valid {
continue
}
if search != "" {
if !strings.Contains(strings.ToLower(e.UserID), search) {
continue
}
}
cp := *e
out = append(out, &cp)
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].JoinedAt.Equal(out[j].JoinedAt) {
return out[i].ID < out[j].ID
}
return out[i].JoinedAt.Before(out[j].JoinedAt)
})
return out
}
func (r *fakeTenantMemberRepo) CountFilteredByTenant(
ctx context.Context, tenantID uint64, search string,
) (int64, error) {
return int64(len(r.filterTenantRows(tenantID, search))), nil
}
func (r *fakeTenantMemberRepo) ListPagedByTenant(
ctx context.Context, tenantID uint64, search string, offset, limit int,
) ([]*types.TenantMember, error) {
all := r.filterTenantRows(tenantID, search)
if offset >= len(all) {
return []*types.TenantMember{}, nil
}
end := offset + limit
if end > len(all) {
end = len(all)
}
return append([]*types.TenantMember(nil), all[offset:end]...), nil
}
func (r *fakeTenantMemberRepo) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
if r.failUpdateRole != nil {
return r.failUpdateRole
+3
View File
@@ -136,6 +136,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering repositories...")
must(container.Provide(repository.NewTenantRepository))
must(container.Provide(repository.NewTenantMemberRepository))
must(container.Provide(repository.NewTenantInvitationRepository))
must(container.Provide(repository.NewAuditLogRepository))
must(container.Provide(repository.NewKnowledgeBaseRepository))
must(container.Provide(repository.NewKnowledgeRepository))
@@ -172,6 +173,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering business services...")
must(container.Provide(service.NewTenantService))
must(container.Provide(service.NewTenantMemberService))
must(container.Provide(service.NewTenantInvitationService))
must(container.Provide(service.NewAuditLogService))
must(container.Provide(service.NewAuditLogRetentionRunner))
must(container.Provide(service.NewKnowledgeBaseService))
@@ -290,6 +292,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering HTTP handlers...")
must(container.Provide(handler.NewTenantHandler))
must(container.Provide(handler.NewTenantMemberHandler))
must(container.Provide(handler.NewTenantInvitationHandler))
must(container.Provide(handler.NewAuditLogHandler))
must(container.Provide(handler.NewKnowledgeBaseHandler))
must(container.Provide(handler.NewKnowledgeHandler))
+42
View File
@@ -0,0 +1,42 @@
package handler
import (
"fmt"
"strconv"
"strings"
"github.com/gin-gonic/gin"
apperrors "github.com/Tencent/WeKnora/internal/errors"
)
const (
defaultListPageSize = 20
maxListPageSize = 100
)
// parseListPagination parses ?page and ?page_size for tenant-scoped list
// endpoints. Omitted keys default to page=1 and page_size=20. A present but
// malformed or out-of-range value yields a validation error on the context.
func parseListPagination(c *gin.Context) (page, pageSize int, ok bool) {
page = 1
pageSize = defaultListPageSize
if s := strings.TrimSpace(c.Query("page")); s != "" {
p, err := strconv.Atoi(s)
if err != nil || p < 1 {
c.Error(apperrors.NewValidationError("page must be a positive integer"))
return 0, 0, false
}
page = p
}
if s := strings.TrimSpace(c.Query("page_size")); s != "" {
ps, err := strconv.Atoi(s)
if err != nil || ps < 1 || ps > maxListPageSize {
c.Error(apperrors.NewValidationError(fmt.Sprintf("page_size must be between 1 and %d", maxListPageSize)))
return 0, 0, false
}
pageSize = ps
}
return page, pageSize, true
}
+506
View File
@@ -0,0 +1,506 @@
package handler
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// TenantInvitationHandler exposes the tenant-scoped CRUD on the
// `tenant_invitations` table plus the user-self-service inbox endpoints
// (/me/invitations*). Route-level RBAC: tenant routes are Owner-gated
// (POST/DELETE) or Viewer-gated (GET); inbox routes only require
// authentication (the service enforces "only invitee can act").
type TenantInvitationHandler struct {
invitationService interfaces.TenantInvitationService
userService interfaces.UserService
tenantService interfaces.TenantService
}
// NewTenantInvitationHandler wires the dependencies. tenantService is
// used to hydrate tenant names in the inbox view so the invitee sees
// "join Foo Workspace" instead of a raw numeric tenant id.
func NewTenantInvitationHandler(
invitationService interfaces.TenantInvitationService,
userService interfaces.UserService,
tenantService interfaces.TenantService,
) *TenantInvitationHandler {
return &TenantInvitationHandler{
invitationService: invitationService,
userService: userService,
tenantService: tenantService,
}
}
// createInvitationRequest is the JSON body for POST /tenants/:id/invitations.
// Email is the user-facing identifier; the handler resolves it to a
// User row before delegating to the service. The optional Message is
// surfaced in the invitee's inbox.
type createInvitationRequest struct {
Email string `json:"email" binding:"required,email"`
Role types.TenantRole `json:"role" binding:"required"`
Message string `json:"message"`
}
// parseInvitationIDFromPath reads :inv_id off the gin context.
func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
raw := strings.TrimSpace(c.Param("inv_id"))
if raw == "" {
c.Error(apperrors.NewValidationError("invitation id is required"))
return 0, false
}
v, err := strconv.ParseUint(raw, 10, 64)
if err != nil || v == 0 {
c.Error(apperrors.NewValidationError("invitation id must be a positive integer"))
return 0, false
}
return v, true
}
// projectInvitation hydrates a single TenantInvitation row into the
// API response shape. Inviter / invitee user fields and the tenant
// name are filled best-effort: a missing row degrades to the bare id
// rather than dropping the response. usersByID and tenantsByID let the
// caller batch the lookups when projecting a list.
func projectInvitation(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
tenantsByID map[uint64]*types.Tenant,
) types.TenantInvitationResponse {
resp := types.TenantInvitationResponse{
ID: inv.ID,
TenantID: inv.TenantID,
InviteeUserID: inv.InviteeUserID,
InvitedBy: inv.InvitedBy,
Role: inv.Role,
Status: inv.Status,
Message: inv.Message,
ExpiresAt: inv.ExpiresAt,
RespondedAt: inv.RespondedAt,
CreatedAt: inv.CreatedAt,
}
if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
resp.InviteeEmail = u.Email
resp.InviteeName = u.Username
}
if inv.InvitedBy != nil {
if u, ok := usersByID[*inv.InvitedBy]; ok && u != nil {
resp.InviterEmail = u.Email
resp.InviterName = u.Username
}
}
if t, ok := tenantsByID[inv.TenantID]; ok && t != nil {
resp.TenantName = t.Name
}
return resp
}
// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
// Best-effort: a transient lookup failure logs and returns an empty
// map so the projection falls back to ids.
func (h *TenantInvitationHandler) hydrateUsers(c *gin.Context, invs []*types.TenantInvitation) map[string]*types.User {
if len(invs) == 0 {
return map[string]*types.User{}
}
idSet := make(map[string]struct{}, len(invs)*2)
for _, inv := range invs {
idSet[inv.InviteeUserID] = struct{}{}
if inv.InvitedBy != nil {
idSet[*inv.InvitedBy] = struct{}{}
}
}
ids := make([]string, 0, len(idSet))
for id := range idSet {
ids = append(ids, id)
}
users, err := h.userService.GetUsersByIDs(c.Request.Context(), ids)
if err != nil {
logger.Warnf(c.Request.Context(), "invitation list: batch user hydrate failed: %v", err)
return map[string]*types.User{}
}
return users
}
// hydrateTenants is the same idea over the distinct tenant_ids touched
// by `invs`. Used by the /me inbox view where invitations span tenants.
func (h *TenantInvitationHandler) hydrateTenants(c *gin.Context, invs []*types.TenantInvitation) map[uint64]*types.Tenant {
if len(invs) == 0 || h.tenantService == nil {
return map[uint64]*types.Tenant{}
}
idSet := make(map[uint64]struct{}, len(invs))
for _, inv := range invs {
idSet[inv.TenantID] = struct{}{}
}
ids := make([]uint64, 0, len(idSet))
for id := range idSet {
ids = append(ids, id)
}
tenants, err := h.tenantService.GetTenantsByIDs(c.Request.Context(), ids)
if err != nil {
logger.Warnf(c.Request.Context(), "invitation list: batch tenant hydrate failed: %v", err)
return map[uint64]*types.Tenant{}
}
return tenants
}
// ListTenantInvitations godoc
// @Summary 列出租户邀请
// @Description 按 tenant 列出待接受 / 历史邀请。query include_terminal=true 时附带 accepted/declined/revoked/expired。
// @Tags 租户邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param include_terminal query bool false "是否包含终止态行(默认 false)"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量" default(20)
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations [get]
func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
page, pageSize, ok := parseListPagination(c)
if !ok {
return
}
rows, total, err := h.invitationService.ListTenantInvitationsPage(ctx, tenantID, includeTerminal, page, pageSize)
if err != nil {
logger.Errorf(ctx, "ListTenantInvitationsPage failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
return
}
usersByID := h.hydrateUsers(c, rows)
resp := make([]types.TenantInvitationResponse, 0, len(rows))
for _, inv := range rows {
// Within the tenant view we don't bother hydrating tenant name
// (the caller already knows the tenant). Pass an empty map.
resp = append(resp, projectInvitation(inv, usersByID, nil))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"invitations": resp,
"total": total,
"page": page,
"page_size": pageSize,
},
})
}
// CreateInvitation godoc
// @Summary 发出租户邀请
// @Description Owner 通过邮箱邀请已注册用户加入当前租户;被邀请人需要在 /me/invitations 接受后才会成为成员。
// @Tags 租户邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param request body createInvitationRequest true "邀请请求"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations [post]
func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
var req createInvitationRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
return
}
if !req.Role.IsValid() {
c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
return
}
user, err := h.userService.GetUserByEmail(ctx, strings.TrimSpace(req.Email))
if err != nil {
if errors.Is(err, apprepo.ErrUserNotFound) {
c.Error(apperrors.NewNotFoundError(
"user with this email is not registered; ask them to sign up first"))
return
}
logger.Errorf(ctx, "GetUserByEmail failed: email=%s err=%v",
secutils.SanitizeForLog(req.Email), err)
c.Error(apperrors.NewInternalServerError("failed to look up user").WithDetails(err.Error()))
return
}
caller, _ := types.UserIDFromContext(ctx)
var invitedBy *string
if caller != "" && !types.IsSyntheticUserID(caller) {
invitedBy = &caller
}
inv, err := h.invitationService.Create(ctx, tenantID, user.ID, req.Role, invitedBy, req.Message)
if err != nil {
switch {
case errors.Is(err, service.ErrInvalidTenantRole):
c.Error(apperrors.NewValidationError(err.Error()))
case errors.Is(err, service.ErrPendingInvitationExists):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrAlreadyMember):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "CreateInvitation failed: user=%s tenant=%d err=%v",
user.ID, tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to create invitation").WithDetails(err.Error()))
}
return
}
usersByID := map[string]*types.User{user.ID: user}
if invitedBy != nil {
// Best-effort hydrate inviter too. Errors are swallowed —
// the response degrades to just the invitee fields.
if u, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && u != nil {
usersByID[u.ID] = u
}
}
resp := projectInvitation(inv, usersByID, nil)
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": resp,
})
}
// RevokeInvitation godoc
// @Summary 撤销待接受邀请
// @Description Owner 取消一条还在 pending 的邀请;已 accepted/declined/revoked/expired 的行不可再撤销。
// @Tags 租户邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations/{inv_id} [delete]
func (h *TenantInvitationHandler) RevokeInvitation(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
// Cross-check the invitation lives in the URL :id. The route layer
// already verifies the caller has Owner on the active tenant AND
// the URL :id matches the active tenant (PathTenantMatch), but the
// invitation row itself carries its own tenant_id we have to honour
// — otherwise an Owner of A could revoke invitations of B by URL-
// crafting against /tenants/A/invitations/<inv-of-B>.
inv, err := h.invitationService.GetByID(ctx, invID)
if err != nil {
logger.Errorf(ctx, "GetByID invitation failed: id=%d err=%v", invID, err)
c.Error(apperrors.NewInternalServerError("failed to load invitation").WithDetails(err.Error()))
return
}
if inv == nil {
c.Error(apperrors.NewNotFoundError("invitation not found"))
return
}
if inv.TenantID != tenantID {
// Render the same 404 as "missing" so we don't leak existence
// across tenants.
c.Error(apperrors.NewNotFoundError("invitation not found"))
return
}
if err := h.invitationService.Revoke(ctx, invID); err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "RevokeInvitation failed: id=%d err=%v", invID, err)
c.Error(apperrors.NewInternalServerError("failed to revoke invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ListMyInvitations godoc
// @Summary 列出我的待接受邀请
// @Description 返回当前登录用户的待接受邀请(默认仅 pending),用于头像入口和 /invitations 收件箱页。
// @Tags 我的邀请
// @Produce json
// @Param include_terminal query bool false "是否包含已处理 / 已过期等终止态行(默认 false)"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations [get]
func (h *TenantInvitationHandler) ListMyInvitations(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
rows, err := h.invitationService.ListByInvitee(ctx, caller, includeTerminal)
if err != nil {
logger.Errorf(ctx, "ListByInvitee invitations failed: user=%s err=%v", caller, err)
c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
return
}
usersByID := h.hydrateUsers(c, rows)
tenantsByID := h.hydrateTenants(c, rows)
resp := make([]types.TenantInvitationResponse, 0, len(rows))
for _, inv := range rows {
resp = append(resp, projectInvitation(inv, usersByID, tenantsByID))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"invitations": resp,
"total": len(resp),
},
})
}
// CountMyPendingInvitations godoc
// @Summary 获取我的待处理邀请数
// @Description 轻量级 endpoint,返回当前登录用户的 pending 邀请数,用于头像旁的角标轮询。
// @Tags 我的邀请
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/pending-count [get]
func (h *TenantInvitationHandler) CountMyPendingInvitations(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
count, err := h.invitationService.CountPendingByInvitee(ctx, caller)
if err != nil {
logger.Errorf(ctx, "CountPendingByInvitee failed: user=%s err=%v", caller, err)
c.Error(apperrors.NewInternalServerError("failed to count pending invitations").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{"pending_count": count},
})
}
// AcceptMyInvitation godoc
// @Summary 接受邀请
// @Description 当前登录用户接受一条 pending 邀请;服务端会同时写入 tenant_members 行。
// @Tags 我的邀请
// @Produce json
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/{inv_id}/accept [post]
func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
member, err := h.invitationService.Accept(ctx, invID, caller)
if err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationForbidden):
c.Error(apperrors.NewForbiddenError(err.Error()))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrInvitationExpired):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "AcceptMyInvitation failed: id=%d user=%s err=%v",
invID, caller, err)
c.Error(apperrors.NewInternalServerError("failed to accept invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"membership": gin.H{
"tenant_id": member.TenantID,
"role": member.Role,
"status": member.Status,
"joined_at": member.JoinedAt,
},
},
})
}
// DeclineMyInvitation godoc
// @Summary 拒绝邀请
// @Description 当前登录用户拒绝一条 pending 邀请;不创建 tenant_members 行。
// @Tags 我的邀请
// @Produce json
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/{inv_id}/decline [post]
func (h *TenantInvitationHandler) DeclineMyInvitation(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
if err := h.invitationService.Decline(ctx, invID, caller); err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationForbidden):
c.Error(apperrors.NewForbiddenError(err.Error()))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrInvitationExpired):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "DeclineMyInvitation failed: id=%d user=%s err=%v",
invID, caller, err)
c.Error(apperrors.NewInternalServerError("failed to decline invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+33 -8
View File
@@ -86,10 +86,13 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
// ListMembers godoc
// @Summary 列出租户成员
// @Description 返回当前租户内全部 active 成员(含每位成员的角色、邮箱、头像)
// @Description 分页返回当前租户内 active 成员(含每位成员的角色、邮箱、头像);支持 q 按邮箱/用户名筛选
// @Tags 租户成员
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "租户 ID"
// @Param q query string false "按邮箱/用户名模糊筛选"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量(最大 100)" default(20)
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/members [get]
@@ -100,9 +103,15 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
return
}
members, err := h.memberService.ListByTenant(ctx, tenantID)
q := strings.TrimSpace(c.Query("q"))
page, pageSize, ok := parseListPagination(c)
if !ok {
return
}
members, total, err := h.memberService.ListMembersPage(ctx, tenantID, q, page, pageSize)
if err != nil {
logger.Errorf(ctx, "ListByTenant failed: tenant=%d err=%v", tenantID, err)
logger.Errorf(ctx, "ListMembersPage failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to list members").WithDetails(err.Error()))
return
}
@@ -144,15 +153,31 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"members": resp,
"total": len(resp),
"members": resp,
"total": total,
"page": page,
"page_size": pageSize,
},
})
}
// AddMember godoc
// @Summary 添加租户成员
// @Description Owner 通过 email 邀请已经存在的用户加入当前租户
// @Summary 直接添加租户成员(直加路径)
// @Description
//
// Owner 通过 email 直接把用户作为 active 成员添加进当前租户。
//
// 这是【直加路径】,被加入的用户没有任何确认机会就出现在租户里——
// 保留它是为了三类不需要走邀请确认的场景:
// 1. 自动化脚本 / 平台运维 / 数据迁移;
// 2. 跨租户超管 (CanAccessAllTenants) 的批量编排;
// 3. 对接外部 IdP 时由身份源单向同步成员。
//
// 所有由 UI 触发的「邀请伙伴加入」交互应改走
// POST /tenants/:id/invitations,那条路径会先创建 pending 行,让被邀请
// 人在 /me/invitations 主动接受后再写 tenant_members 行(PR #1303 后续)。
// 这条路径与 invitations 路径共存而不互相替代。
//
// @Tags 租户成员
// @Accept json
// @Produce json
+48 -4
View File
@@ -26,10 +26,46 @@ import (
// gotten here" assertions.
type stubMemberService struct {
interfaces.TenantMemberService
add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
remove func(ctx context.Context, userID string, tenantID uint64) error
add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
listMembersPage func(ctx context.Context, tenantID uint64, query string, page, pageSize int) ([]*types.TenantMember, int64, error)
updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
remove func(ctx context.Context, userID string, tenantID uint64) error
}
func (s *stubMemberService) ListMembersPage(
ctx context.Context,
tenantID uint64,
query string,
page, pageSize int,
) ([]*types.TenantMember, int64, error) {
if s.listMembersPage != nil {
return s.listMembersPage(ctx, tenantID, query, page, pageSize)
}
if s.listTenant != nil {
members, err := s.listTenant(ctx, tenantID)
if err != nil {
return nil, 0, err
}
total := int64(len(members))
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
off := (page - 1) * pageSize
if off >= len(members) {
return []*types.TenantMember{}, total, nil
}
end := off + pageSize
if end > len(members) {
end = len(members)
}
slice := append([]*types.TenantMember(nil), members[off:end]...)
return slice, total, nil
}
return []*types.TenantMember{}, 0, nil
}
func (s *stubMemberService) AddMember(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error) {
@@ -260,6 +296,14 @@ func TestTenantMember_ListMembers_RejectsBadTenantID(t *testing.T) {
}
}
func TestTenantMember_ListMembers_RejectsInvalidPage(t *testing.T) {
h := newTestMemberHandler(&stubMemberService{}, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members?page=0", nil, "u1")
if w.Code != http.StatusBadRequest {
t.Fatalf("page=0 must 400, got %d body=%s", w.Code, w.Body.String())
}
}
// ---------- AddMember ----------
func TestTenantMember_AddMember_HappyPath(t *testing.T) {
+5
View File
@@ -107,6 +107,11 @@ func (f *fakeMemberService) ListByUser(ctx context.Context, userID string) ([]*t
func (f *fakeMemberService) ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error) {
return nil, nil
}
func (f *fakeMemberService) ListMembersPage(
ctx context.Context, tenantID uint64, query string, page, pageSize int,
) ([]*types.TenantMember, int64, error) {
return nil, 0, nil
}
func (f *fakeMemberService) HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error) {
if f.failHasAny != nil {
return false, f.failHasAny
+45 -1
View File
@@ -52,6 +52,7 @@ type RouterParams struct {
TenantService interfaces.TenantService
TenantMemberService interfaces.TenantMemberService
TenantMemberHandler *handler.TenantMemberHandler
TenantInvitationHandler *handler.TenantInvitationHandler
AuditLogHandler *handler.AuditLogHandler
AuditLogService interfaces.AuditLogService
ChunkHandler *handler.ChunkHandler
@@ -174,7 +175,8 @@ func NewRouter(params RouterParams) *gin.Engine {
)
RegisterAuthRoutes(v1, params.AuthHandler)
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.AuditLogHandler, rbacGuards)
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.TenantInvitationHandler, params.AuditLogHandler, rbacGuards)
RegisterMyInvitationRoutes(v1, params.TenantInvitationHandler)
RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards)
RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards)
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards)
@@ -487,6 +489,7 @@ func RegisterTenantRoutes(
r *gin.RouterGroup,
handler *handler.TenantHandler,
memberHandler *handler.TenantMemberHandler,
invitationHandler *handler.TenantInvitationHandler,
auditLogHandler *handler.AuditLogHandler,
g *rbacGuards,
) {
@@ -537,6 +540,21 @@ func RegisterTenantRoutes(
tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant)
}
// Tenant invitation flow. The UI-driven "Invite Member"
// button hits POST /invitations rather than POST /members,
// so the invitee gets to confirm via /me/invitations
// before any tenant_members row is written. List is
// Viewer+ so any member can see pending invites in the
// management view; create/revoke are Owner+ to match the
// existing /members mutation gates. nil-skip pattern
// mirrors memberHandler above for environments built
// without the invitation dependency wired.
if invitationHandler != nil {
tenantByID.GET("/invitations", g.Viewer(), invitationHandler.ListTenantInvitations)
tenantByID.POST("/invitations", g.Owner(), invitationHandler.CreateInvitation)
tenantByID.DELETE("/invitations/:inv_id", g.Owner(), invitationHandler.RevokeInvitation)
}
// Audit log feed (PR 6 of #1303). Admin+ so denied-action
// histories don't surface to ordinary members; the
// PathTenantMatch group already prevents cross-tenant
@@ -592,6 +610,32 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
}
}
// RegisterMyInvitationRoutes wires the per-user invitation inbox under
// /me/invitations. The v1 group already applies middleware.Auth so we
// don't need a role gate here — the service enforces "only the invitee
// can accept/decline". The list endpoint mounts under /me to make the
// "show me MY invitations" semantics obvious in URLs and logs (vs the
// tenant-scoped /tenants/:id/invitations which lists ALL invitations
// for the tenant). pending-count is a separate, ultra-light endpoint
// the avatar-row badge polls; splitting it off so polling doesn't
// transfer the full list every cycle.
//
// invitationHandler may be nil in environments built without the
// invitation dependency wired; that's a no-op registration which is
// preferable to a startup crash.
func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.TenantInvitationHandler) {
if invitationHandler == nil {
return
}
me := r.Group("/me")
{
me.GET("/invitations", invitationHandler.ListMyInvitations)
me.GET("/invitations/pending-count", invitationHandler.CountMyPendingInvitations)
me.POST("/invitations/:inv_id/accept", invitationHandler.AcceptMyInvitation)
me.POST("/invitations/:inv_id/decline", invitationHandler.DeclineMyInvitation)
}
}
// RegisterAuthRoutes registers authentication routes
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/register", handler.Register)
+20
View File
@@ -30,6 +30,26 @@ const (
// EnableRBAC=true. Subject to 1-minute sliding-window dedup so a
// probing client cannot fill the table.
AuditActionAccessDenied AuditAction = "rbac.access_denied"
// AuditActionInvitationSent fires when an Owner issues a new
// tenant invitation. Actor is the inviter, TargetUserID is the
// invitee. Note: AuditActionMemberAdded only fires when the
// invitee actually accepts and the tenant_members row is created.
AuditActionInvitationSent AuditAction = "rbac.invitation_sent"
// AuditActionInvitationAccepted fires when the invitee accepts a
// pending invitation. Actor is the invitee (acting on their own
// inbox); the matching rbac.member_added is emitted in the same
// transaction.
AuditActionInvitationAccepted AuditAction = "rbac.invitation_accepted"
// AuditActionInvitationDeclined fires when the invitee rejects a
// pending invitation. Actor and target are the same user.
AuditActionInvitationDeclined AuditAction = "rbac.invitation_declined"
// AuditActionInvitationRevoked fires when a tenant Owner cancels
// a still-pending invitation before the invitee acts. Actor is
// the Owner; target is the invitee.
AuditActionInvitationRevoked AuditAction = "rbac.invitation_revoked"
// AuditActionInvitationExpired fires when the lazy sweep transitions
// an overdue pending row to expired. Actor is empty (system).
AuditActionInvitationExpired AuditAction = "rbac.invitation_expired"
)
// AuditOutcome distinguishes successful mutations from middleware-level
@@ -0,0 +1,74 @@
package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// TenantInvitationRepository persists tenant_invitations rows that
// capture the "pending invite" intent before it becomes a real
// tenant_members row. All read methods skip GORM soft-deleted rows.
type TenantInvitationRepository interface {
// Create inserts a new pending invitation. Returns the conflict
// error sentinel (ErrPendingInvitationExists) if the (tenant_id,
// invitee) partial unique index rejects the insert.
Create(ctx context.Context, inv *types.TenantInvitation) error
// GetByID fetches an invitation by surrogate id, or (nil, nil) if
// missing. Used by Accept/Decline/Revoke handlers.
GetByID(ctx context.Context, id uint64) (*types.TenantInvitation, error)
// GetPendingByPair returns the in-flight pending invitation for
// (tenant, invitee) or (nil, nil) when none exists. Used by the
// service layer to short-circuit duplicate Create calls before
// they hit the unique index.
GetPendingByPair(ctx context.Context, tenantID uint64, inviteeUserID string) (*types.TenantInvitation, error)
// ListByTenant returns invitations for the tenant ordered by
// id DESC (newest first). includeTerminal controls whether
// non-pending rows (accepted/declined/revoked/expired) are
// returned — the management UI shows pending by default, with
// a "history" toggle for the rest.
ListByTenant(ctx context.Context, tenantID uint64, includeTerminal bool) ([]*types.TenantInvitation, error)
// CountByTenantList counts invitation rows matching the same filter as
// ListByTenant (tenant_id + optional pending-only vs include-terminal).
CountByTenantList(ctx context.Context, tenantID uint64, includeTerminal bool) (int64, error)
// ListByTenantPage returns invitations for the tenant with id DESC
// paging, same filtering semantics as ListByTenant.
ListByTenantPage(ctx context.Context, tenantID uint64, includeTerminal bool, offset, limit int) ([]*types.TenantInvitation, error)
// ListByInvitee returns invitations addressed to the user across
// all tenants. Ordered by id DESC. Used both by the inbox page
// (includeTerminal=false) and by /me/invitations/history if/when
// we expose history (includeTerminal=true).
ListByInvitee(ctx context.Context, inviteeUserID string, includeTerminal bool) ([]*types.TenantInvitation, error)
// CountPendingByInvitee returns the number of pending invitations
// for the user. Used by the avatar-row badge so the UI doesn't
// have to fetch the full list just to render a count.
CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
// MarkStatusIfPending atomically transitions a row from pending
// to the supplied status. respondedAt is recorded as the
// transition time. Returns gorm.ErrRecordNotFound when the row
// does not exist or is already in a non-pending state, which the
// service layer maps to ErrInvitationNotPending — that error is
// the "stale state machine" signal callers care about.
MarkStatusIfPending(
ctx context.Context,
id uint64,
status types.TenantInvitationStatus,
respondedAt time.Time,
) error
// SweepExpired transitions all pending rows whose expires_at is
// before `now` into the expired state. Returns the affected row
// count so callers can decide whether to emit per-row audit
// events (we don't — the volume could be high and the audit-log
// table already records the original invitation_sent rows).
SweepExpired(ctx context.Context, now time.Time) (int64, error)
}
@@ -0,0 +1,67 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// TenantInvitationService is the business-logic layer over
// TenantInvitationRepository. It enforces the lifecycle invariants
// described in TenantInvitationStatus, runs the lazy expiry sweep, and
// brokers the accept-time hand-off into TenantMemberService so that
// "accept" produces both the invitation transition AND the
// tenant_members row in a single audit story.
type TenantInvitationService interface {
// Create issues a new pending invitation for (tenantID, inviteeUserID)
// with the given role. Caller passes the inviter user id (may be
// nil for service-internal flows). Returns the freshly created row
// or a sentinel error (ErrPendingInvitationExists / ErrAlreadyMember /
// ErrInvalidTenantRole) for the common conflicts.
Create(
ctx context.Context,
tenantID uint64,
inviteeUserID string,
role types.TenantRole,
invitedBy *string,
message string,
) (*types.TenantInvitation, error)
// Accept transitions the pending row into accepted AND creates the
// active tenant_members row in the same transaction. The callerUserID
// MUST equal inv.InviteeUserID — the service rejects anyone else.
// Returns the freshly created membership for the response shape.
Accept(ctx context.Context, invID uint64, callerUserID string) (*types.TenantMember, error)
// Decline transitions the pending row into declined. Same caller
// rule as Accept: only the invitee themselves.
Decline(ctx context.Context, invID uint64, callerUserID string) error
// Revoke transitions the pending row into revoked. Callable by an
// Owner of the tenant the invitation belongs to (the handler
// applies the Owner gate via g.Owner() route middleware, so this
// method does not re-check role).
Revoke(ctx context.Context, invID uint64) error
// GetByID returns an invitation or (nil, nil). Used by handlers to
// authorise per-row operations (e.g. is the caller the invitee?).
GetByID(ctx context.Context, invID uint64) (*types.TenantInvitation, error)
// ListByTenant returns invitations for a tenant. Always runs the
// lazy expiry sweep before reading so stale-pending rows surface
// as expired in the UI.
ListByTenant(ctx context.Context, tenantID uint64, includeTerminal bool) ([]*types.TenantInvitation, error)
// ListTenantInvitationsPage paginates invitations for the tenant
// management UI after the lazy sweep (same filtering as ListByTenant).
ListTenantInvitationsPage(ctx context.Context, tenantID uint64, includeTerminal bool, page, pageSize int) ([]*types.TenantInvitation, int64, error)
// ListByInvitee returns invitations addressed to the user across
// all tenants. Always runs the lazy sweep first.
ListByInvitee(ctx context.Context, inviteeUserID string, includeTerminal bool) ([]*types.TenantInvitation, error)
// CountPendingByInvitee returns the user's pending invitation count
// after running the lazy sweep, so the inbox badge can poll a
// lightweight endpoint without paginating the full list.
CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
}
@@ -30,6 +30,16 @@ type TenantMemberRepository interface {
// ordered by joined_at ascending.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
// CountFilteredByTenant counts active memberships in tenant. Optional
// search matches user email/username (join users table); empty search
// counts all memberships.
CountFilteredByTenant(ctx context.Context, tenantID uint64, search string) (int64, error)
// ListPagedByTenant returns active memberships sorted joined_at ASC, id ASC.
// search filters by user email/username (join users table); empty
// search lists all memberships in tenant.
ListPagedByTenant(ctx context.Context, tenantID uint64, search string, offset, limit int) ([]*types.TenantMember, error)
// UpdateRole changes the role of an existing active membership. Returns
// gorm.ErrRecordNotFound if no active row matches.
UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error
@@ -33,6 +33,10 @@ type TenantMemberService interface {
// ListByTenant returns every active membership inside the tenant.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
// ListMembersPage lists members with pagination. Query matches email or
// username case-insensitively; empty query returns full tenant list slice.
ListMembersPage(ctx context.Context, tenantID uint64, query string, page, pageSize int) ([]*types.TenantMember, int64, error)
// HasAnyMembers reports whether the tenant has at least one active
// member. The auth middleware uses this to recover orphan tenants
// (e.g. API-key-only tenants that never had a human member): the
+125
View File
@@ -0,0 +1,125 @@
package types
import (
"time"
"gorm.io/gorm"
)
// TenantInvitationStatus enumerates the lifecycle states of a single
// invitation row. The legal transitions are:
//
// pending -> accepted | declined | revoked | expired
//
// All non-pending states are terminal; once a row leaves pending it is
// kept for the audit trail and a new pending row can be issued.
type TenantInvitationStatus string
const (
// TenantInvitationStatusPending is the initial state: the invitee
// has not yet acted and the row has not been revoked or aged out.
TenantInvitationStatusPending TenantInvitationStatus = "pending"
// TenantInvitationStatusAccepted means the invitee confirmed and
// a corresponding active tenant_members row has been created in
// the same transaction.
TenantInvitationStatusAccepted TenantInvitationStatus = "accepted"
// TenantInvitationStatusDeclined means the invitee rejected the
// invitation. The row stays for auditability; a new pending
// invitation can be issued afterwards.
TenantInvitationStatusDeclined TenantInvitationStatus = "declined"
// TenantInvitationStatusRevoked means a tenant Owner cancelled
// the pending invitation before the invitee acted.
TenantInvitationStatusRevoked TenantInvitationStatus = "revoked"
// TenantInvitationStatusExpired means the row outlived its
// expires_at without being accepted/declined/revoked. Set by the
// lazy-sweep run before every List/Accept/Decline.
TenantInvitationStatusExpired TenantInvitationStatus = "expired"
)
// IsTerminal reports whether s is a non-pending state. Used by the
// service layer to short-circuit accept/decline/revoke on rows that
// have already been finalised.
func (s TenantInvitationStatus) IsTerminal() bool {
switch s {
case TenantInvitationStatusAccepted,
TenantInvitationStatusDeclined,
TenantInvitationStatusRevoked,
TenantInvitationStatusExpired:
return true
}
return false
}
// TenantInvitation is one pending or finalised invitation issued by an
// Owner of `TenantID` to the user identified by `InviteeUserID`. The
// row is created in `pending` state when the Owner clicks "invite"; it
// flips to a terminal state when the invitee accepts/declines, the
// Owner revokes, or the row expires.
//
// A tenant_members row is created only on accept; the invitation table
// is therefore the single source of truth for "pending intent" without
// polluting the authoritative member roster.
type TenantInvitation struct {
// Surrogate primary key.
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
// TenantID references tenants.id.
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
// InviteeUserID references users.id (always a registered user; the
// handler resolves the email to a User row before insertion).
InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;index"`
// InvitedBy records the user id that issued this invitation. NULL
// for invitations created via service-internal / synthetic actors
// (mirrors the same treatment TenantMember.InvitedBy gets).
InvitedBy *string `json:"invited_by,omitempty" gorm:"type:varchar(36)"`
// Role the invitee will receive in tenant_members if they accept.
Role TenantRole `json:"role" gorm:"type:varchar(20);not null"`
// Status holds the lifecycle state. Default pending; mutated to
// accepted/declined/revoked/expired exactly once.
Status TenantInvitationStatus `json:"status" gorm:"type:varchar(20);not null;default:'pending'"`
// Message is an optional free-text note the Owner can include in
// the invitation (e.g. "joining the design squad — welcome!").
Message string `json:"message,omitempty" gorm:"type:varchar(500)"`
// ExpiresAt is when this row auto-flips to expired if still pending.
// Set at creation time from RBAC_INVITATION_TTL (default 7d).
ExpiresAt time.Time `json:"expires_at"`
// RespondedAt records when the row left pending. Nil while pending.
RespondedAt *time.Time `json:"responded_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// TableName binds TenantInvitation to the tenant_invitations table.
func (TenantInvitation) TableName() string { return "tenant_invitations" }
// IsExpired reports whether this invitation is past its expires_at at
// the given reference time. The service layer uses this both for the
// lazy sweep and to reject an accept/decline arriving after timeout.
func (inv *TenantInvitation) IsExpired(at time.Time) bool {
if inv == nil || inv.ExpiresAt.IsZero() {
return false
}
return inv.ExpiresAt.Before(at)
}
// TenantInvitationResponse is the API projection joined with tenant
// name and inviter / invitee user fields the UI needs. The model is
// intentionally NOT serialised directly so we don't leak DeletedAt /
// UpdatedAt and lock the DB schema into the public API.
type TenantInvitationResponse struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name,omitempty"`
InviteeUserID string `json:"invitee_user_id"`
InviteeEmail string `json:"invitee_email,omitempty"`
InviteeName string `json:"invitee_name,omitempty"`
InvitedBy *string `json:"invited_by,omitempty"`
InviterEmail string `json:"inviter_email,omitempty"`
InviterName string `json:"inviter_name,omitempty"`
Role TenantRole `json:"role"`
Status TenantInvitationStatus `json:"status"`
Message string `json:"message,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
RespondedAt *time.Time `json:"responded_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}