fix(rbac): polish tenant member UI; add /leave endpoint
Self-review of PR 3's TenantMembers.vue surfaced a handful of real bugs
and a few rough edges. This commit fixes them and adds the self-leave
endpoint that PR 3's design called out as a follow-up.
Frontend bug fixes
- Read err.status (not err.response.status). The axios interceptor in
utils/request.ts already flattens errors into { status, message,
... }, so the original branch-by-status code never matched and every
4xx fell through to the generic toast. Fixes 404/409 surfacing as
"userNotFound" / "alreadyMember" / "lastOwner" instead of "Something
went wrong".
- t-dialog @confirm replaces :on-confirm so the dialog stays open on
validation failure and on API error. Users can fix and retry without
retyping the email.
- Drop the t-select revert hack; with :model-value the rendered value
is already source-of-truth-on-row.role, so no setTimeout dance is
needed.
- Don't toast "no active tenant" on cold mount; watch the activeTenantId
ref and load once the auth store hydrates.
Frontend UX additions
- Empty state via t-empty (also covers the search-no-results case).
- Compact role-permissions matrix above the table, mirroring
OrganizationSettingsModal so Owners can see what each role grants
before promoting/inviting.
- Search box filtering by username/email (client-side, sufficient for
expected per-tenant member counts).
- "Leave Tenant" button — visible to any active member except the
last-Owner case (server still enforces).
Backend
- New POST /tenants/:id/leave route. Calls TenantMemberService.RemoveMember
with the caller's own user id so non-Owners can quit on their own.
Gated Viewer+ in the matrix; the existing last-Owner invariant in the
service still rejects last-Owner self-leave with 409.
- 3 new handler tests cover the happy path, the last-Owner 409 path,
and the missing-caller-id 401 path (defensive — auth middleware
always attaches a user, but the test pins the contract).
i18n
- Add tenantMember.permissions / search / leave / empty strings in all
four locales (en/zh/ko/ru).
This commit is contained in:
@@ -310,3 +310,45 @@ func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// LeaveTenant godoc
|
||||
// @Summary 退出当前租户
|
||||
// @Description 调用方主动退出当前租户。等价于以自己的 user_id 调 RemoveMember,
|
||||
//
|
||||
// 但不需要 Owner 权限——非 Owner 也可以自助离开。最后一位 Owner 仍然不能离开
|
||||
// (需先把其他成员提升为 Owner),由服务层 ErrLastOwner 拦截。
|
||||
//
|
||||
// @Tags 租户成员
|
||||
// @Produce json
|
||||
// @Param id path string true "租户 ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /tenants/{id}/leave [post]
|
||||
func (h *TenantMemberHandler) LeaveTenant(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID, ok := parseTenantIDFromPath(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
caller, ok := types.UserIDFromContext(ctx)
|
||||
if !ok || caller == "" {
|
||||
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.memberService.RemoveMember(ctx, caller, tenantID); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrMembershipNotFound):
|
||||
c.Error(apperrors.NewNotFoundError("you are not a member of this tenant"))
|
||||
case errors.Is(err, service.ErrLastOwner):
|
||||
c.Error(apperrors.NewConflictError(err.Error()))
|
||||
default:
|
||||
logger.Errorf(ctx, "LeaveTenant failed: user=%s tenant=%d err=%v",
|
||||
caller, tenantID, err)
|
||||
c.Error(apperrors.NewInternalServerError("failed to leave tenant").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ func memberTestRouter(h *TenantMemberHandler) *gin.Engine {
|
||||
r.POST("/tenants/:id/members", h.AddMember)
|
||||
r.PUT("/tenants/:id/members/:user_id", h.UpdateMemberRole)
|
||||
r.DELETE("/tenants/:id/members/:user_id", h.RemoveMember)
|
||||
r.POST("/tenants/:id/leave", h.LeaveTenant)
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -355,3 +356,65 @@ func TestTenantMember_RemoveMember_LastOwnerMaps409(t *testing.T) {
|
||||
t.Fatalf("last-owner remove must 409, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- LeaveTenant ----------
|
||||
|
||||
func TestTenantMember_LeaveTenant_HappyPath(t *testing.T) {
|
||||
// LeaveTenant must invoke RemoveMember with the caller's own user
|
||||
// id, regardless of any path :user_id segment. The route doesn't
|
||||
// have a :user_id; the caller's id comes from the auth context.
|
||||
ms := &stubMemberService{
|
||||
remove: func(_ context.Context, userID string, tenantID uint64) error {
|
||||
if userID != "u-self" || tenantID != 1 {
|
||||
t.Fatalf("LeaveTenant must use caller id; got user=%s tenant=%d", userID, tenantID)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
|
||||
|
||||
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "u-self")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantMember_LeaveTenant_LastOwnerMaps409(t *testing.T) {
|
||||
// The whole point of having a separate leave endpoint is that
|
||||
// non-Owners can quit, but the same last-Owner invariant still
|
||||
// applies — an Owner that's the only one left must transfer
|
||||
// ownership before they can leave.
|
||||
ms := &stubMemberService{
|
||||
remove: func(_ context.Context, _ string, _ uint64) error {
|
||||
return service.ErrLastOwner
|
||||
},
|
||||
}
|
||||
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
|
||||
|
||||
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "u-only-owner")
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("last-owner self-leave must 409, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantMember_LeaveTenant_MissingCallerReturns401(t *testing.T) {
|
||||
// Defensive: if the auth middleware ever fails to attach a user id,
|
||||
// LeaveTenant must NOT silently call RemoveMember(""), it should
|
||||
// surface 401 so the caller knows their session is broken.
|
||||
called := false
|
||||
ms := &stubMemberService{
|
||||
remove: func(_ context.Context, _ string, _ uint64) error {
|
||||
called = true
|
||||
return nil
|
||||
},
|
||||
}
|
||||
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
|
||||
|
||||
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "")
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("missing caller must 401, got %d", w.Code)
|
||||
}
|
||||
if called {
|
||||
t.Fatalf("RemoveMember must not be called without a caller id")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user