feat: 邀请链接在 invite_only 模式下改为登录后加入空间
parent
355d161d64
commit
8309370fa9
|
|
@ -105,6 +105,19 @@ const persistOIDCLoginResponse = async (response: any) => {
|
|||
|
||||
await syncOIDCUserContext()
|
||||
|
||||
// OIDC 跳转前暂存的邀请 token:拿到会话后兑换并进入对应空间。
|
||||
const pendingInviteToken = sessionStorage.getItem('weknora_pending_invite_token')
|
||||
if (pendingInviteToken) {
|
||||
sessionStorage.removeItem('weknora_pending_invite_token')
|
||||
const result = await authStore.acceptInvitationByTokenAndRefresh(pendingInviteToken)
|
||||
await nextTick()
|
||||
if (result.ok) MessagePlugin.success(t('inviteRegister.joined'))
|
||||
else MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||
// 会话已有效,无论 token 是否兑换成功都进入应用。
|
||||
router.replace('/platform/knowledge-bases')
|
||||
return
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,6 +100,21 @@ export interface AcceptInvitationResponse {
|
|||
message?: string
|
||||
}
|
||||
|
||||
// AcceptInvitationByTokenResponse:已登录用户用 token 加入空间的响应(tenant_name 供前端展示)。
|
||||
export interface AcceptInvitationByTokenResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
membership: {
|
||||
tenant_id: number
|
||||
role: TenantRole
|
||||
status: string
|
||||
joined_at: string
|
||||
}
|
||||
tenant_name?: string
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface PendingCountResponse {
|
||||
success: boolean
|
||||
data?: { pending_count: number }
|
||||
|
|
@ -193,6 +208,20 @@ export async function acceptInvitation(invId: number): Promise<AcceptInvitationR
|
|||
)) as unknown as AcceptInvitationResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* 已登录用户用共享链接 token 加入空间(需鉴权,不创建新账号)。
|
||||
* 用于 invite_only 模式下的邀请链接流程:链接导向登录而非注册,登录后再兑换 token。
|
||||
* Backend: POST /api/v1/me/invitations/accept-by-token (authenticated).
|
||||
*/
|
||||
export async function acceptInvitationByToken(
|
||||
token: string,
|
||||
): Promise<AcceptInvitationByTokenResponse> {
|
||||
return (await post(
|
||||
`/api/v1/me/invitations/accept-by-token`,
|
||||
{ token },
|
||||
)) as unknown as AcceptInvitationByTokenResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Decline one of MY pending invitations.
|
||||
* Backend: POST /api/v1/me/invitations/:inv_id/decline (authenticated).
|
||||
|
|
|
|||
|
|
@ -1439,6 +1439,7 @@ export default {
|
|||
inviteRegister: {
|
||||
bannerTitle: 'You have been invited to join "{tenant}"',
|
||||
bannerHint: 'Fill in the details below to register. You will join the team automatically once registration completes.',
|
||||
bannerHintLogin: 'Log in to join this team automatically.',
|
||||
loading: 'Verifying invitation link…',
|
||||
invalidTitle: 'Invitation link is invalid or revoked',
|
||||
invalidBody: 'Ask your inviter to send a new link, or sign in with an existing account.',
|
||||
|
|
@ -1457,6 +1458,7 @@ export default {
|
|||
submit: 'Complete registration',
|
||||
submitting: 'Submitting…',
|
||||
success: 'Registration successful — entering workspace…',
|
||||
joined: 'You have joined the team.',
|
||||
failed: 'Registration failed; please try again later',
|
||||
usernameRequired: 'Display name is required',
|
||||
passwordTooShort: 'Password must be at least 6 characters',
|
||||
|
|
|
|||
|
|
@ -4459,6 +4459,7 @@ export default {
|
|||
inviteRegister: {
|
||||
bannerTitle: '「{tenant}」에 초대되었습니다',
|
||||
bannerHint: '아래 정보를 입력해 가입을 완료하세요. 등록이 끝나면 자동으로 팀에 합류합니다.',
|
||||
bannerHintLogin: '로그인하면 자동으로 팀에 합류됩니다.',
|
||||
loading: '초대 링크를 확인하는 중…',
|
||||
invalidTitle: '초대 링크가 유효하지 않거나 취소되었습니다',
|
||||
invalidBody: '초대한 분께 새 링크를 요청하거나 기존 계정으로 로그인하세요.',
|
||||
|
|
@ -4477,6 +4478,7 @@ export default {
|
|||
submit: '가입 완료',
|
||||
submitting: '전송 중…',
|
||||
success: '가입 완료, 워크스페이스로 이동합니다…',
|
||||
joined: '팀에 합류했습니다.',
|
||||
failed: '가입에 실패했습니다. 잠시 후 다시 시도해 주세요',
|
||||
usernameRequired: '이름을 입력하세요',
|
||||
passwordTooShort: '비밀번호는 최소 6자 이상이어야 합니다',
|
||||
|
|
|
|||
|
|
@ -4459,6 +4459,7 @@ export default {
|
|||
inviteRegister: {
|
||||
bannerTitle: 'You have been invited to join "{tenant}"',
|
||||
bannerHint: 'Fill in the details below to register. You will join the team automatically once registration completes.',
|
||||
bannerHintLogin: 'Log in to join this team automatically.',
|
||||
loading: 'Verifying invitation link…',
|
||||
invalidTitle: 'Invitation link is invalid or revoked',
|
||||
invalidBody: 'Ask your inviter to send a new link, or sign in with an existing account.',
|
||||
|
|
@ -4477,6 +4478,7 @@ export default {
|
|||
submit: 'Complete registration',
|
||||
submitting: 'Submitting…',
|
||||
success: 'Registration successful — entering workspace…',
|
||||
joined: 'You have joined the team.',
|
||||
failed: 'Registration failed; please try again later',
|
||||
usernameRequired: 'Display name is required',
|
||||
passwordTooShort: 'Password must be at least 6 characters',
|
||||
|
|
|
|||
|
|
@ -4459,6 +4459,7 @@ export default {
|
|||
inviteRegister: {
|
||||
bannerTitle: '您被邀请加入「{tenant}」',
|
||||
bannerHint: '填写下方信息完成注册,注册成功后将自动加入该团队。',
|
||||
bannerHintLogin: '登录后将自动加入该团队。',
|
||||
loading: '正在校验邀请链接…',
|
||||
invalidTitle: '邀请链接无效或已撤销',
|
||||
invalidBody: '请联系邀请人重新发送链接,或前往登录使用现有账号。',
|
||||
|
|
@ -4477,6 +4478,7 @@ export default {
|
|||
submit: '完成注册',
|
||||
submitting: '提交中…',
|
||||
success: '注册成功,正在进入工作空间…',
|
||||
joined: '已加入该团队',
|
||||
failed: '注册失败,请稍后重试',
|
||||
usernameRequired: '请输入姓名',
|
||||
passwordTooShort: '密码至少 6 位',
|
||||
|
|
|
|||
|
|
@ -374,6 +374,28 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
}
|
||||
}
|
||||
|
||||
// 用 token 加入空间并刷新成员关系、切到新空间。token 无效时返回 ok:false(不抛异常),
|
||||
// 提示与跳转交给调用方(store 不碰 router)。
|
||||
const acceptInvitationByTokenAndRefresh = async (
|
||||
token: string,
|
||||
): Promise<{ ok: boolean; tenantId?: number; tenantName?: string }> => {
|
||||
try {
|
||||
const { acceptInvitationByToken } = await import('@/api/tenant/invitations')
|
||||
const resp = await acceptInvitationByToken(token)
|
||||
if (!resp.success || !resp.data?.membership) {
|
||||
return { ok: false }
|
||||
}
|
||||
const tenantId = resp.data.membership.tenant_id
|
||||
const tenantName = resp.data.tenant_name
|
||||
// 刷新成员关系,并切到刚加入的空间。
|
||||
await refreshFromAuthMe()
|
||||
setSelectedTenant(tenantId, tenantName ?? null)
|
||||
return { ok: true, tenantId, tenantName }
|
||||
} catch {
|
||||
return { ok: false }
|
||||
}
|
||||
}
|
||||
|
||||
const getSelectedTenant = () => {
|
||||
return selectedTenantId.value
|
||||
}
|
||||
|
|
@ -552,6 +574,7 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
setCanCreateTenant,
|
||||
fetchPendingInvitationCount,
|
||||
refreshFromAuthMe,
|
||||
acceptInvitationByTokenAndRefresh,
|
||||
getSelectedTenant,
|
||||
setLiteMode,
|
||||
logout,
|
||||
|
|
|
|||
|
|
@ -177,6 +177,21 @@
|
|||
<div class="form-panel">
|
||||
<!-- Login Card -->
|
||||
<div class="form-card" v-if="!isRegisterMode">
|
||||
<!-- invite_only 模式下共享链接停在登录卡,同样需要邀请上下文。 -->
|
||||
<div v-if="inviteLookup" class="invite-banner">
|
||||
<t-icon name="link" class="invite-banner__icon" />
|
||||
<div class="invite-banner__text">
|
||||
<div class="invite-banner__title">
|
||||
{{ $t('inviteRegister.bannerTitle', { tenant: inviteLookup.tenant_name || '' }) }}
|
||||
</div>
|
||||
<div class="invite-banner__hint">
|
||||
{{ $t('inviteRegister.bannerHintLogin') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="inviteLookupError" class="invite-banner invite-banner--error">
|
||||
{{ inviteLookupError }}
|
||||
</div>
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">{{ $t('auth.login') }}</h2>
|
||||
<p class="form-welcome">{{ $t('auth.subtitle') }}</p>
|
||||
|
|
@ -533,7 +548,7 @@ onBeforeUnmount(() => {
|
|||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
const persistLoginResponse = async (response: any) => {
|
||||
const persistLoginResponse = async (response: any, skipRedirect = false) => {
|
||||
// Backend renamed `tenant` to `active_tenant` and added `memberships`
|
||||
// when tenant-level RBAC landed (issue #1303). The two are otherwise
|
||||
// identical — `active_tenant` is the tenant whose ID is encoded in the
|
||||
|
|
@ -584,6 +599,7 @@ const persistLoginResponse = async (response: any) => {
|
|||
// briefly when the deployment is invitation-only.
|
||||
await authStore.refreshFromAuthMe()
|
||||
await nextTick()
|
||||
if (skipRedirect) return
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
|
|
@ -623,6 +639,10 @@ const handleOIDCLogin = async () => {
|
|||
return
|
||||
}
|
||||
|
||||
// 跳转 IdP 会丢失 URL 中的 token,暂存到 sessionStorage,回调后由 App.vue 兑换。
|
||||
if (inviteToken.value) {
|
||||
sessionStorage.setItem('weknora_pending_invite_token', inviteToken.value)
|
||||
}
|
||||
window.location.href = authorizationURL
|
||||
} catch (error: any) {
|
||||
console.error('OIDC 登录跳转失败:', error)
|
||||
|
|
@ -632,6 +652,25 @@ const handleOIDCLogin = async () => {
|
|||
}
|
||||
}
|
||||
|
||||
// 用 token 加入空间并进入应用。会话此时已有效,故即便 token 失效也照常进入(避免困在登录页)。
|
||||
const acceptAndEnter = async (token: string) => {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await authStore.acceptInvitationByTokenAndRefresh(token)
|
||||
if (result.ok) {
|
||||
MessagePlugin.success(t('inviteRegister.joined'))
|
||||
} else {
|
||||
MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||
}
|
||||
} catch {
|
||||
MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||
} finally {
|
||||
loading.value = false
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle login
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
|
|
@ -646,6 +685,12 @@ const handleLogin = async () => {
|
|||
})
|
||||
|
||||
if (response.success) {
|
||||
if (inviteToken.value) {
|
||||
// 从邀请链接登录:持久化会话后兑换 token 并进入对应空间。
|
||||
await persistLoginResponse(response, true)
|
||||
await acceptAndEnter(inviteToken.value)
|
||||
return
|
||||
}
|
||||
await persistLoginResponse(response)
|
||||
notifyLoginSuccess(response, t, tm, formatRole, roleIcon)
|
||||
} else {
|
||||
|
|
@ -731,25 +776,37 @@ onMounted(async () => {
|
|||
if (tokenFromQuery) {
|
||||
inviteToken.value = tokenFromQuery
|
||||
inviteLookupLoading.value = true
|
||||
// 1. 先校验 token:无效/过期则停在登录页报错,不进注册模式。
|
||||
try {
|
||||
const resp = await getInvitationByToken(tokenFromQuery)
|
||||
if (resp.success && resp.data) {
|
||||
inviteLookup.value = resp.data
|
||||
// Token bypasses invite_only — show the register card even
|
||||
// when self-service registration is otherwise disabled.
|
||||
registrationEnabled.value = true
|
||||
isRegisterMode.value = true
|
||||
} else {
|
||||
inviteLookupError.value = resp.message || t('inviteRegister.invalidBody')
|
||||
loadOIDCConfig()
|
||||
loadAuthConfig()
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
inviteLookupError.value = t('inviteRegister.invalidBody')
|
||||
loadOIDCConfig()
|
||||
loadAuthConfig()
|
||||
return
|
||||
} finally {
|
||||
inviteLookupLoading.value = false
|
||||
}
|
||||
// Don't run auto-setup when the user came in via an invite link —
|
||||
// they're explicitly trying to register, not bootstrap a Lite
|
||||
// single-user instance.
|
||||
|
||||
// 2. 已登录则直接兑换 token 进入空间(两种模式通用)。
|
||||
if (authStore.isLoggedIn && (await authStore.refreshFromAuthMe())) {
|
||||
await acceptAndEnter(tokenFromQuery)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 未登录:按注册模式决定界面。invite_only 停在登录页、登录后再兑换;self_serve 保持注册流程。
|
||||
const cfg = await getAuthConfig()
|
||||
const inviteOnly = cfg.registration_mode === 'invite_only'
|
||||
registrationEnabled.value = !inviteOnly
|
||||
isRegisterMode.value = !inviteOnly
|
||||
loadOIDCConfig()
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -518,6 +518,90 @@ func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
// acceptInvitationByTokenRequest: POST /me/invitations/accept-by-token 的请求体。
|
||||
// 已登录用户用 token 加入空间(与 register-by-invite 不同,不创建新账号)。
|
||||
type acceptInvitationByTokenRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
}
|
||||
|
||||
// AcceptMyInvitationByToken godoc
|
||||
// @Summary 通过共享链接加入空间
|
||||
// @Description 已登录用户用共享邀请链接 token 加入空间,不创建新账号;对已是成员的用户幂等。
|
||||
// @Tags 我的邀请
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body acceptInvitationByTokenRequest true "邀请 token"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
|
||||
// @Security Bearer
|
||||
// @Router /me/invitations/accept-by-token [post]
|
||||
func (h *TenantInvitationHandler) AcceptMyInvitationByToken(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
|
||||
}
|
||||
|
||||
var req acceptInvitationByTokenRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewValidationError("token is required").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(req.Token)
|
||||
if token == "" {
|
||||
c.Error(apperrors.NewValidationError("token is required"))
|
||||
return
|
||||
}
|
||||
|
||||
member, err := h.invitationService.AcceptByToken(ctx, token, caller)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvitationTokenInvalid):
|
||||
// 无效/过期/撤销统一返回 410(与 LookupInvitationByToken 一致)。
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrNotFound,
|
||||
Message: "invitation link is invalid or has been revoked",
|
||||
HTTPCode: http.StatusGone,
|
||||
})
|
||||
default:
|
||||
logger.Errorf(ctx, "AcceptMyInvitationByToken failed: user=%s err=%v", caller, err)
|
||||
c.Error(apperrors.NewInternalServerError("failed to accept invitation").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 无租户用户将首个加入的空间设为默认空间(与 AcceptMyInvitation 同理)。
|
||||
if user, userErr := h.userService.GetUserByID(ctx, caller); userErr == nil && user != nil && user.TenantID == 0 {
|
||||
user.TenantID = member.TenantID
|
||||
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
|
||||
logger.Errorf(ctx, "AcceptMyInvitationByToken failed to set default tenant: user=%s tenant=%d err=%v",
|
||||
caller, member.TenantID, updateErr)
|
||||
c.Error(apperrors.NewInternalServerError("invitation accepted but default workspace update failed").WithDetails(updateErr.Error()))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 供前端切换空间展示用。
|
||||
tenantName := ""
|
||||
if tenant, terr := h.tenantService.GetTenantByID(ctx, member.TenantID); terr == nil && tenant != nil {
|
||||
tenantName = tenant.Name
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
"tenant_name": tenantName,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// DeclineMyInvitation godoc
|
||||
// @Summary 拒绝邀请
|
||||
// @Description 当前登录用户拒绝一条 pending 邀请;不创建 tenant_members 行。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,238 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// acceptByTokenInvitationSvc only implements AcceptByToken; the embedded
|
||||
// interface panics on any other call so the test stays focused.
|
||||
type acceptByTokenInvitationSvc struct {
|
||||
interfaces.TenantInvitationService
|
||||
member *types.TenantMember
|
||||
acceptErr error
|
||||
}
|
||||
|
||||
func (s *acceptByTokenInvitationSvc) AcceptByToken(_ context.Context, _ string, userID string) (*types.TenantMember, error) {
|
||||
if s.acceptErr != nil {
|
||||
return nil, s.acceptErr
|
||||
}
|
||||
if s.member != nil {
|
||||
return s.member, nil
|
||||
}
|
||||
return &types.TenantMember{TenantID: 42, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive}, nil
|
||||
}
|
||||
|
||||
// acceptByTokenUserSvc returns a user with the configured home tenant so
|
||||
// the handler's tenantless-adoption branch can be exercised.
|
||||
type acceptByTokenUserSvc struct {
|
||||
interfaces.UserService
|
||||
homeTenant uint64
|
||||
updatedTenant uint64
|
||||
updateCalled bool
|
||||
}
|
||||
|
||||
func (s *acceptByTokenUserSvc) GetUserByID(_ context.Context, _ string) (*types.User, error) {
|
||||
return &types.User{ID: "u-test", TenantID: s.homeTenant, IsActive: true}, nil
|
||||
}
|
||||
|
||||
func (s *acceptByTokenUserSvc) UpdateUser(_ context.Context, user *types.User) error {
|
||||
s.updateCalled = true
|
||||
s.updatedTenant = user.TenantID
|
||||
return nil
|
||||
}
|
||||
|
||||
type acceptByTokenTenantSvc struct {
|
||||
interfaces.TenantService
|
||||
}
|
||||
|
||||
func (s *acceptByTokenTenantSvc) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: id, Name: "Invited Workspace"}, nil
|
||||
}
|
||||
|
||||
func newAcceptByTokenTestRouter(h *TenantInvitationHandler) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
// Production auth middleware injects the caller via the request
|
||||
// context (context.WithValue), which is what UserIDFromContext
|
||||
// reads — NOT gin's c.Keys. Mirror that here.
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), types.UserIDContextKey, "u-test"))
|
||||
c.Next()
|
||||
}, errorCapture())
|
||||
r.POST("/me/invitations/accept-by-token", h.AcceptMyInvitationByToken)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestAcceptMyInvitationByTokenSuccess(t *testing.T) {
|
||||
users := &acceptByTokenUserSvc{homeTenant: 0} // tenantless -> adopts invited tenant
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{},
|
||||
userService: users,
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{"token":"invite-token"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if !users.updateCalled || users.updatedTenant != 42 {
|
||||
t.Fatalf("tenantless user should adopt tenant 42, updateCalled=%v updatedTenant=%d",
|
||||
users.updateCalled, users.updatedTenant)
|
||||
}
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Membership struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
Role string `json:"role"`
|
||||
} `json:"membership"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
} `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.Membership.TenantID != 42 || resp.Data.TenantName != "Invited Workspace" {
|
||||
t.Fatalf("unexpected response: %+v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMyInvitationByTokenDoesNotMutateUserWithHomeTenant(t *testing.T) {
|
||||
users := &acceptByTokenUserSvc{homeTenant: 7} // already has a home tenant
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{},
|
||||
userService: users,
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{"token":"invite-token"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if users.updateCalled {
|
||||
t.Fatalf("user with home tenant must not be rewritten; updateCalled=%v", users.updateCalled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMyInvitationByTokenInvalidTokenIsGone(t *testing.T) {
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{acceptErr: service.ErrInvitationTokenInvalid},
|
||||
userService: &acceptByTokenUserSvc{},
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{"token":"stale-token"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusGone {
|
||||
t.Fatalf("status=%d body=%s, want 410 for invalid token", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMyInvitationByTokenMissingTokenIsBadRequest(t *testing.T) {
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{},
|
||||
userService: &acceptByTokenUserSvc{},
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s, want 400 for missing token", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// AcceptByToken is idempotent: an existing membership is returned
|
||||
// untouched. The handler treats that member the same as a freshly
|
||||
// created one (200 + membership), so a user clicking the same link
|
||||
// twice from two devices never sees a role downgrade or an error.
|
||||
func TestAcceptMyInvitationByTokenIdempotent(t *testing.T) {
|
||||
users := &acceptByTokenUserSvc{homeTenant: 42}
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{
|
||||
member: &types.TenantMember{TenantID: 42, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive},
|
||||
},
|
||||
userService: users,
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{"token":"invite-token"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Data struct {
|
||||
Membership struct {
|
||||
Role string `json:"role"`
|
||||
} `json:"membership"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.Data.Membership.Role != string(types.TenantRoleContributor) {
|
||||
t.Fatalf("role=%s, want contributor (existing membership preserved)", resp.Data.Membership.Role)
|
||||
}
|
||||
// homeTenant is already 42, so the adoption branch must not fire.
|
||||
if users.updateCalled {
|
||||
t.Fatalf("idempotent re-accept should not rewrite user; updateCalled=%v", users.updateCalled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMyInvitationByTokenUnexpectedErrorIs500(t *testing.T) {
|
||||
h := &TenantInvitationHandler{
|
||||
invitationService: &acceptByTokenInvitationSvc{acceptErr: errors.New("boom")},
|
||||
userService: &acceptByTokenUserSvc{},
|
||||
tenantService: &acceptByTokenTenantSvc{},
|
||||
}
|
||||
r := newAcceptByTokenTestRouter(h)
|
||||
|
||||
body := []byte(`{"token":"invite-token"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/me/invitations/accept-by-token", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s, want 500 for unexpected error", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -170,6 +170,8 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
|
|||
me.GET("/invitations/pending-count", invitationHandler.CountMyPendingInvitations)
|
||||
me.POST("/invitations/:inv_id/accept", invitationHandler.AcceptMyInvitation)
|
||||
me.POST("/invitations/:inv_id/decline", invitationHandler.DeclineMyInvitation)
|
||||
// 已登录用户用共享链接 token 加入空间(对应 register-by-invite,但不建新账号)。
|
||||
me.POST("/invitations/accept-by-token", invitationHandler.AcceptMyInvitationByToken)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue