diff --git a/.env.example b/.env.example index b9876e98..ccbb1f27 100644 --- a/.env.example +++ b/.env.example @@ -542,6 +542,8 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!! # WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB=10 # 空间邀请链接 TTL(Go duration,默认 168h=7 天)。 # WEKNORA_INVITATION_TTL=168h +# 全局开关:邀请已注册用户时直接加入空间。默认 false,可在系统设置页修改。 +# WEKNORA_TENANT_AUTO_ACCEPT_INVITATION=false # 审计日志保留天数(0 禁用清理,默认 90)。 # WEKNORA_AUDIT_RETENTION_DAYS=90 diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts index ffc19b29..ab730caa 100644 --- a/frontend/src/api/auth/index.ts +++ b/frontend/src/api/auth/index.ts @@ -321,6 +321,7 @@ export interface MembershipInfo { */ export interface AuthCapabilities { can_create_tenant: boolean + auto_accept_invitation: boolean } export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities }; message?: string }> { diff --git a/frontend/src/api/tenant/invitations.ts b/frontend/src/api/tenant/invitations.ts index 4012582d..fcd16866 100644 --- a/frontend/src/api/tenant/invitations.ts +++ b/frontend/src/api/tenant/invitations.ts @@ -1,5 +1,5 @@ import { get, post, del } from '@/utils/request' -import type { TenantRole } from '@/api/tenant/members' +import type { TenantMember, TenantRole } from '@/api/tenant/members' // TenantInvitationStatus mirrors internal/types/tenant_invitation.go's // five-state machine. pending is the only non-terminal state; the rest @@ -78,7 +78,9 @@ export interface CreateInvitationRequest { export interface CreateInvitationResponse { success: boolean - data?: TenantInvitation + // With tenant.auto_accept_invitation enabled the backend returns a + // TenantMember (user_id set) instead of a pending TenantInvitation. + data?: TenantInvitation | TenantMember message?: string } diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index ab2df37a..4e293beb 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -59,6 +59,8 @@ export const useAuthStore = defineStore('auth', () => { // then reject with 403/2005. const canCreateTenant = ref(false) + const autoAcceptInvitation = ref(false) + // 计算属性 const isLoggedIn = computed(() => { return !!token.value && !!user.value @@ -368,6 +370,8 @@ export const useAuthStore = defineStore('auth', () => { setCanCreateTenant(createCapability) } + autoAcceptInvitation.value = response.data?.capabilities?.auto_accept_invitation === true + return true } catch { return false @@ -423,6 +427,7 @@ export const useAuthStore = defineStore('auth', () => { memberships.value = [] pendingInvitationCount.value = 0 canCreateTenant.value = false + autoAcceptInvitation.value = false clearSessionResourceCaches() // 清空localStorage @@ -527,6 +532,13 @@ export const useAuthStore = defineStore('auth', () => { } isLiteMode.value = localStorage.getItem('weknora_lite_mode') === 'true' + + // localStorage only caches user/tenant/memberships — never capabilities. + // Reconcile with /auth/me so deployment switches (can_create_tenant, + // auto_accept_invitation) track the live server, not last-login state. + if (storedToken) { + refreshFromAuthMe() + } } // 初始化时从localStorage恢复状态 @@ -546,6 +558,7 @@ export const useAuthStore = defineStore('auth', () => { memberships, pendingInvitationCount, canCreateTenant, + autoAcceptInvitation, // 计算属性 isLoggedIn, diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue index f6914862..6f78b289 100644 --- a/frontend/src/views/settings/TenantMembers.vue +++ b/frontend/src/views/settings/TenantMembers.vue @@ -1300,10 +1300,16 @@ const addConfirmRoleLabel = computed(() => t('tenantMember.role.' + addForm.role // submitAdd is wired to the popup footer primary CTA. On step='form' it // validates and swaps to summary; on step='confirm' it fires the API. +// With auto-accept the action is a direct add, so we skip the invitation +// confirm step entirely and fire the API right after validation. async function submitAdd() { if (addDialogStep.value === 'form') { const valid = await addFormRef.value?.validate?.() if (valid !== true) return + if (authStore.autoAcceptInvitation) { + await sendInvitation(addForm.email.trim(), addForm.role) + return + } addDialogStep.value = 'confirm' return } @@ -1315,11 +1321,12 @@ function goBackToForm() { addDialogStep.value = 'form' } -// dialogConfirmLabel drives the primary action label across the two steps. +// dialogConfirmLabel: "Send" on the confirm step, or when auto-accept makes +// the form step a direct add; otherwise "Send invitation". const dialogConfirmLabel = computed(() => - addDialogStep.value === 'form' - ? t('tenantInvitation.inviteSubmit') - : t('tenantInvitation.confirmSend'), + addDialogStep.value === 'confirm' || authStore.autoAcceptInvitation + ? t('tenantInvitation.confirmSend') + : t('tenantInvitation.inviteSubmit'), ) // sendInvitation actually fires the create-invitation API call. @@ -1328,10 +1335,18 @@ async function sendInvitation(email: string, role: TenantRole) { try { const resp = await createInvitation(activeTenantId.value, { email, role }) if (resp.success) { - invitationsPage.value = 1 - await loadInvitations() + // auto-accept returns a member (user_id) instead of an invitation (id) + const autoJoined = !!resp.data && 'user_id' in resp.data invitePopupVisible.value = false - MessagePlugin.success(t('tenantInvitation.inviteSuccess')) + if (autoJoined) { + // The invitee is already a member — refresh the roster so they + // appear immediately. No toast: the new row is the feedback. + await loadMembers() + } else { + invitationsPage.value = 1 + await loadInvitations() + MessagePlugin.success(t('tenantInvitation.inviteSuccess')) + } } else { MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic')) } diff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.go index fa3c586e..c40696a6 100644 --- a/internal/application/service/system_setting.go +++ b/internal/application/service/system_setting.go @@ -200,6 +200,16 @@ var registry = map[string]settingSpec{ "用于兼容旧版本「创建空间即下发默认 API Key」的行为(属于破坏性变更的回退开关)。" + "每次创建空间时实时读取,修改后立即生效。默认 false(不自动创建,需通过 API Key 管理显式创建)。", }, + // tenant.auto_accept_invitation: invite = auto-join switch (default false). + "tenant.auto_accept_invitation": { + Type: "bool", + EnvName: "WEKNORA_TENANT_AUTO_ACCEPT_INVITATION", + Default: false, + Category: "tenant", + Description: "全局开关:开启后,空间管理员通过邮箱邀请已注册用户加入空间时," + + "被邀请人将被立即自动加入(直接写入成员关系),无需在收件箱手动接受,也不再生成待接受的邀请记录。" + + "关闭时保持原有「发出邀请 → 被邀请人收件箱确认」流程。每次邀请时实时读取,修改后立即生效。默认 false。", + }, "asynq.core_concurrency": { Type: "int", EnvName: "WEKNORA_ASYNQ_CORE_CONCURRENCY", diff --git a/internal/handler/auth.go b/internal/handler/auth.go index efcf9f0e..b4370baf 100644 --- a/internal/handler/auth.go +++ b/internal/handler/auth.go @@ -571,6 +571,8 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) { memberships := h.userService.BuildLoginMemberships(ctx, user, tenant) canCreateTenant := user.CanAccessAllTenants || resolveTenantSelfServiceCreationEnabled(ctx, h.configInfo, h.systemSettingSvc) + autoAcceptInvitation := h.systemSettingSvc != nil && + h.systemSettingSvc.GetBool(ctx, "tenant.auto_accept_invitation", "WEKNORA_TENANT_AUTO_ACCEPT_INVITATION", false) c.JSON(http.StatusOK, gin.H{ "success": true, "data": gin.H{ @@ -579,7 +581,8 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) { "memberships": memberships, "tenant_required": tenant == nil, "capabilities": gin.H{ - "can_create_tenant": canCreateTenant, + "can_create_tenant": canCreateTenant, + "auto_accept_invitation": autoAcceptInvitation, }, }, }) diff --git a/internal/handler/tenant_invitation.go b/internal/handler/tenant_invitation.go index 0cfe9ea8..32b99df5 100644 --- a/internal/handler/tenant_invitation.go +++ b/internal/handler/tenant_invitation.go @@ -27,23 +27,30 @@ type TenantInvitationHandler struct { invitationService interfaces.TenantInvitationService userService interfaces.UserService tenantService interfaces.TenantService + memberService interfaces.TenantMemberService + systemSettingSvc interfaces.SystemSettingService configInfo *config.Config } -// 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. configInfo -// supplies FrontendBaseURL for share-link URL composition. +// NewTenantInvitationHandler wires the dependencies. tenantService hydrates +// tenant names in the inbox view; configInfo supplies FrontendBaseURL for +// share-link URL composition. memberService + systemSettingSvc back the +// auto-accept switch (tenant.auto_accept_invitation); both are nil-guarded +// for tests (production wiring always injects both). func NewTenantInvitationHandler( invitationService interfaces.TenantInvitationService, userService interfaces.UserService, tenantService interfaces.TenantService, + memberService interfaces.TenantMemberService, + systemSettingSvc interfaces.SystemSettingService, configInfo *config.Config, ) *TenantInvitationHandler { return &TenantInvitationHandler{ invitationService: invitationService, userService: userService, tenantService: tenantService, + memberService: memberService, + systemSettingSvc: systemSettingSvc, configInfo: configInfo, } } @@ -245,7 +252,7 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) { // CreateInvitation godoc // @Summary 发出空间邀请 -// @Description Owner 通过邮箱邀请已注册用户加入当前空间;被邀请人需要在 /me/invitations 接受后才会成为成员。 +// @Description Owner 通过邮箱邀请已注册用户加入空间。开启 tenant.auto_accept_invitation 后被邀请人立即自动加入(响应为成员结构),否则需在 /me/invitations 接受后成为成员。 // @Tags 空间邀请 // @Accept json // @Produce json @@ -290,6 +297,20 @@ func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) { invitedBy = &caller } + // Auto-accept switch (tenant.auto_accept_invitation): skip the pending + // invitation and add the already-registered invitee as a member. + if h.systemSettingSvc != nil && + h.systemSettingSvc.GetBool(ctx, "tenant.auto_accept_invitation", "WEKNORA_TENANT_AUTO_ACCEPT_INVITATION", false) { + if h.memberService == nil { + logger.Errorf(ctx, "auto_accept_invitation enabled but memberService is nil; tenant=%d", tenantID) + c.Error(apperrors.NewInternalServerError("failed to add member")) + return + } + // Writes the 201 member response / mapped error; auto-accept is done. + addMemberAndRespond(c, ctx, h.memberService, user, tenantID, req.Role, invitedBy) + return + } + inv, err := h.invitationService.Create(ctx, tenantID, user.ID, req.Role, invitedBy, req.Message) if err != nil { switch { diff --git a/internal/handler/tenant_invitation_auto_accept_test.go b/internal/handler/tenant_invitation_auto_accept_test.go new file mode 100644 index 00000000..00939cee --- /dev/null +++ b/internal/handler/tenant_invitation_auto_accept_test.go @@ -0,0 +1,254 @@ +package handler + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// autoAcceptSettingSvc returns a fixed answer for GetBool so the +// tenant.auto_accept_invitation switch can be flipped per-test. +type autoAcceptSettingSvc struct { + interfaces.SystemSettingService + enabled bool +} + +func (s *autoAcceptSettingSvc) GetBool(_ context.Context, _ string, _ string, _ bool) bool { + return s.enabled +} + +// autoAcceptMemberSvc records whether AddMember was reached (the +// auto-join branch must call it instead of invitationService.Create). +type autoAcceptMemberSvc struct { + interfaces.TenantMemberService + member *types.TenantMember + addErr error + addCalled bool +} + +func (s *autoAcceptMemberSvc) AddMember(_ context.Context, userID string, _ uint64, role types.TenantRole, _ *string) (*types.TenantMember, error) { + s.addCalled = true + if s.addErr != nil { + return nil, s.addErr + } + if s.member != nil { + return s.member, nil + } + return &types.TenantMember{ + UserID: userID, + Role: role, + Status: types.TenantMemberStatusActive, + }, nil +} + +// autoAcceptUserSvc resolves GetUserByEmail for the 404 / happy paths. +type autoAcceptUserSvc struct { + interfaces.UserService + user *types.User + uerr error +} + +func (s *autoAcceptUserSvc) GetUserByEmail(_ context.Context, _ string) (*types.User, error) { + return s.user, s.uerr +} + +func (s *autoAcceptUserSvc) GetUserByID(_ context.Context, _ string) (*types.User, error) { + return nil, nil +} + +// autoAcceptInvitationSvc records whether the classic pending-invitation +// flow was reached (it must NOT run when auto-accept is on). +type autoAcceptInvitationSvc struct { + interfaces.TenantInvitationService + created bool +} + +func (s *autoAcceptInvitationSvc) Create(_ context.Context, tenantID uint64, userID string, role types.TenantRole, _ *string, _ string) (*types.TenantInvitation, error) { + s.created = true + return &types.TenantInvitation{ + ID: 1, + TenantID: tenantID, + InviteeUserID: userID, + Role: role, + Status: types.TenantInvitationStatusPending, + }, nil +} + +func newAutoAcceptTestRouter(h *TenantInvitationHandler) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), types.UserIDContextKey, "u-owner")) + }, errorCapture()) + r.POST("/tenants/:id/invitations", h.CreateInvitation) + return r +} + +func postAutoAcceptInvitation(t *testing.T, r *gin.Engine, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/tenants/7/invitations", bytes.NewReader([]byte(body))) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +func TestCreateInvitation_AutoAcceptEnabled_AddsMemberDirectly(t *testing.T) { + users := &autoAcceptUserSvc{user: &types.User{ID: "u-bob", Email: "bob@x.com", Username: "bob"}} + members := &autoAcceptMemberSvc{} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + memberService: members, + systemSettingSvc: &autoAcceptSettingSvc{enabled: true}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"bob@x.com","role":"contributor"}`) + if w.Code != http.StatusCreated { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + if !members.addCalled { + t.Fatal("auto-accept should call memberService.AddMember") + } + if invites.created { + t.Fatal("auto-accept must not create a pending invitation row") + } + var resp struct { + Success bool `json:"success"` + Data struct { + UserID string `json:"user_id"` + Role string `json:"role"` + Status string `json:"status"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal: %v body=%s", err, w.Body.String()) + } + if !resp.Success || resp.Data.UserID != "u-bob" { + t.Fatalf("expected member-shaped response, got %+v", resp) + } + if resp.Data.Status != string(types.TenantMemberStatusActive) { + t.Fatalf("member should be active, got %q", resp.Data.Status) + } +} + +func TestCreateInvitation_AutoAcceptDisabled_UsesInvitationFlow(t *testing.T) { + users := &autoAcceptUserSvc{user: &types.User{ID: "u-bob", Email: "bob@x.com", Username: "bob"}} + members := &autoAcceptMemberSvc{} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + memberService: members, + systemSettingSvc: &autoAcceptSettingSvc{enabled: false}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"bob@x.com","role":"viewer"}`) + if w.Code != http.StatusCreated { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + if members.addCalled { + t.Fatal("auto-accept disabled must NOT call AddMember") + } + if !invites.created { + t.Fatal("disabled switch should fall through to the pending-invitation flow") + } + var resp struct { + Success bool `json:"success"` + Data struct { + ID uint64 `json:"id"` + Status string `json:"status"` + } `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal: %v body=%s", err, w.Body.String()) + } + if resp.Data.Status != string(types.TenantInvitationStatusPending) { + t.Fatalf("expected pending invitation, got %q", resp.Data.Status) + } +} + +func TestCreateInvitation_AutoAccept_AlreadyMemberReturns409(t *testing.T) { + users := &autoAcceptUserSvc{user: &types.User{ID: "u-bob", Email: "bob@x.com"}} + members := &autoAcceptMemberSvc{addErr: service.ErrMembershipAlreadyExists} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + memberService: members, + systemSettingSvc: &autoAcceptSettingSvc{enabled: true}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"bob@x.com","role":"viewer"}`) + if w.Code != http.StatusConflict { + t.Fatalf("status=%d body=%s, want 409", w.Code, w.Body.String()) + } +} + +func TestCreateInvitation_AutoAccept_UnknownEmailReturns404(t *testing.T) { + users := &autoAcceptUserSvc{uerr: apprepo.ErrUserNotFound} + members := &autoAcceptMemberSvc{} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + memberService: members, + systemSettingSvc: &autoAcceptSettingSvc{enabled: true}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"ghost@x.com","role":"viewer"}`) + if w.Code != http.StatusNotFound { + t.Fatalf("status=%d body=%s, want 404", w.Code, w.Body.String()) + } +} + +func TestCreateInvitation_AutoAccept_APICannotAssignOwnerReturns403(t *testing.T) { + users := &autoAcceptUserSvc{user: &types.User{ID: "u-bob", Email: "bob@x.com"}} + members := &autoAcceptMemberSvc{addErr: service.ErrAPIKeyCannotAssignOwner} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + memberService: members, + systemSettingSvc: &autoAcceptSettingSvc{enabled: true}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"bob@x.com","role":"owner"}`) + if w.Code != http.StatusForbidden { + t.Fatalf("status=%d body=%s, want 403", w.Code, w.Body.String()) + } +} + +func TestCreateInvitation_AutoAcceptEnabled_NilMemberServiceReturns500(t *testing.T) { + users := &autoAcceptUserSvc{user: &types.User{ID: "u-bob", Email: "bob@x.com"}} + invites := &autoAcceptInvitationSvc{} + h := &TenantInvitationHandler{ + invitationService: invites, + userService: users, + systemSettingSvc: &autoAcceptSettingSvc{enabled: true}, + } + r := newAutoAcceptTestRouter(h) + + w := postAutoAcceptInvitation(t, r, `{"email":"bob@x.com","role":"viewer"}`) + if w.Code != http.StatusInternalServerError { + t.Fatalf("status=%d body=%s, want 500", w.Code, w.Body.String()) + } + if invites.created { + t.Fatal("memberService nil must not silently fall back to invitation flow") + } +} diff --git a/internal/handler/tenant_member.go b/internal/handler/tenant_member.go index 445dd63f..4badbae9 100644 --- a/internal/handler/tenant_member.go +++ b/internal/handler/tenant_member.go @@ -1,6 +1,7 @@ package handler import ( + "context" "errors" "net/http" "strconv" @@ -234,7 +235,27 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) { invitedBy = &caller } - member, err := h.memberService.AddMember(ctx, user.ID, tenantID, req.Role, invitedBy) + // Add the member and write the 201 / mapped-error response through the + // shared helper (also used by the invitation auto-accept path). + addMemberAndRespond(c, ctx, h.memberService, user, tenantID, req.Role, invitedBy) +} + +// addMemberAndRespond calls TenantMemberService.AddMember and writes the +// HTTP response: 201 with a TenantMemberResponse on success, or the service +// sentinel mapped to its HTTP status (400 / 403 / 409 / 500) on error. It +// always writes exactly one response, so the caller MUST return right after. +// Shared by TenantMemberHandler.AddMember and the auto-accept branch of +// TenantInvitationHandler.CreateInvitation so the mapping never drifts. +func addMemberAndRespond( + c *gin.Context, + ctx context.Context, + memberService interfaces.TenantMemberService, + user *types.User, + tenantID uint64, + role types.TenantRole, + invitedBy *string, +) { + member, err := memberService.AddMember(ctx, user.ID, tenantID, role, invitedBy) if err != nil { switch { case errors.Is(err, service.ErrInvalidTenantRole): @@ -252,23 +273,21 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) { } return } - // Project the freshly added row through the same response shape the // list endpoint uses, so the UI can swap "Add Member" UX into the // table without an extra round-trip. - resp := types.TenantMemberResponse{ - UserID: member.UserID, - Email: user.Email, - Username: user.Username, - Avatar: user.Avatar, - Role: member.Role, - Status: member.Status, - InvitedBy: member.InvitedBy, - JoinedAt: member.JoinedAt, - } c.JSON(http.StatusCreated, gin.H{ "success": true, - "data": resp, + "data": types.TenantMemberResponse{ + UserID: member.UserID, + Email: user.Email, + Username: user.Username, + Avatar: user.Avatar, + Role: member.Role, + Status: member.Status, + InvitedBy: member.InvitedBy, + JoinedAt: member.JoinedAt, + }, }) }