Repository navigation
feat(go-api): implement tenant member management (issue #15294) - #15295
Conversation
) Add 4 endpoints under /api/v1/tenants/:tenant_id/ mirroring the Python tenant_api team management endpoints: GET /tenants/:tenant_id/users - list non-owner members (owner only) POST /tenants/:tenant_id/users - invite user by email (owner only) DELETE /tenants/:tenant_id/users - remove member (owner or self) PATCH /tenants/:tenant_id - accept pending invitation New DAO methods (internal/dao/user_tenant.go): - GetMembersByTenantID: JOIN with user table for member listing - DeleteByUserAndTenant: hard-delete by user+tenant pair - UpdateRoleByUserAndTenant: update role for invite acceptance New service methods (internal/service/tenant.go): - ListMembers, AddMember, RemoveMember, AcceptInvite - Role constants: TenantRoleOwner/Normal/Invite/Admin - AddMemberRequest/Response, TenantMemberResponse types - userDAO added to TenantService for email lookup New handler methods (internal/handler/tenant.go): - ListTenantMembers, AddTenantMember, RemoveTenantMember, AcceptTenantInvite New test file (internal/service/tenant_test.go): - Auth check and validation unit tests for pure service logic
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughAdds tenant team management: DAO member listing and mutations, TenantService member flows with authorization and validation, Gin handlers and routes for list/add/remove/accept, and unit tests covering auth and argument/error cases. ChangesTenant Member Management
Sequence Diagram(s)sequenceDiagram
participant Client
participant TenantHandler
participant TenantService
participant UserDAO
participant UserTenantDAO
Client->>TenantHandler: HTTP request (list/add/remove/accept)
TenantHandler->>TenantService: call method with userID, tenantID, payload
TenantService->>UserDAO: lookup user by email (AddMember)
UserDAO->>UserTenantDAO: (optional) check existing membership
TenantService->>UserTenantDAO: Get/Create/Update/Delete membership rows
UserTenantDAO->>Database: SQL operations
Database-->>UserTenantDAO: results
UserTenantDAO-->>TenantService: DAO results
TenantService-->>TenantHandler: ErrorCode + data
TenantHandler-->>Client: JSON response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
internal/service/tenant_test.go (2)
1-100: ⚡ Quick winAdd test coverage for AcceptInvite method.
The test suite covers
ListMembers,AddMember, andRemoveMemberauthorization and validation, butAcceptInvitehas no test coverage. SinceAcceptInviteis one of the four methods implemented in this PR (per PR objectives), it should have at least basic authorization/validation tests following the same pattern as the existing tests.💡 Suggested test structure for AcceptInvite
// TestAcceptInviteValidation verifies the auth/validation behavior. func TestAcceptInviteValidation(t *testing.T) { s := &TenantService{} // Test case: verify method can be called with matching userID/tenantID // (will fail at DB layer with nil DAO, but validates the method signature and basic flow) code, err := s.AcceptInvite("user-abc", "tenant-xyz") // Assert expected error behavior based on service implementation // Add additional validation tests as needed }Optional: Consider adding positive test cases with mocked DAOs to validate successful operations, though the current authorization-focused tests provide good value.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/tenant_test.go` around lines 1 - 100, The test suite is missing coverage for TenantService.AcceptInvite; add a unit test mirroring the pattern used for ListMembers/AddMember/RemoveMember to validate auth/validation behavior. Create a TestAcceptInviteValidation in internal/service/tenant_test.go that instantiates s := &TenantService{}, calls s.AcceptInvite with both non-owner (userID != tenantID) to assert it returns CodeAuthenticationError and non-nil error, and calls s.AcceptInvite with userID == tenantID to assert it does not return CodeAuthenticationError (it may return a DB-layer error due to nil DAOs). Use the same common.CodeAuthenticationError and common.CodeArgumentError checks and message style as the other tests and reference the AcceptInvite and TenantService symbols.
87-99: 💤 Low valueConsider direct assertions for clearer intent.
The map-based pattern works but is indirect. Direct assertions would make the test easier to understand at a glance and follow common Go testing conventions.
📝 Proposed refactor to direct assertions
-// TestTenantRoleConstants verifies the role string values match the Python enums. -func TestTenantRoleConstants(t *testing.T) { - cases := map[string]string{ - TenantRoleOwner: "owner", - TenantRoleNormal: "normal", - TenantRoleInvite: "invite", - TenantRoleAdmin: "admin", - } - for got, want := range cases { - if got != want { - t.Errorf("role constant = %q, want %q", got, want) - } - } -} +// TestTenantRoleConstants verifies the role string values match the Python enums. +func TestTenantRoleConstants(t *testing.T) { + if TenantRoleOwner != "owner" { + t.Errorf("TenantRoleOwner = %q, want %q", TenantRoleOwner, "owner") + } + if TenantRoleNormal != "normal" { + t.Errorf("TenantRoleNormal = %q, want %q", TenantRoleNormal, "normal") + } + if TenantRoleInvite != "invite" { + t.Errorf("TenantRoleInvite = %q, want %q", TenantRoleInvite, "invite") + } + if TenantRoleAdmin != "admin" { + t.Errorf("TenantRoleAdmin = %q, want %q", TenantRoleAdmin, "admin") + } +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/tenant_test.go` around lines 87 - 99, The test TestTenantRoleConstants uses an indirect map loop which obscures intent; replace it with direct assertions comparing each constant to its expected string (e.g., check TenantRoleOwner == "owner", TenantRoleNormal == "normal", TenantRoleInvite == "invite", TenantRoleAdmin == "admin") and call t.Errorf (or t.Fatalf) with clear messages when a mismatch occurs so failures point to the specific constant (reference symbols: TestTenantRoleConstants, TenantRoleOwner, TenantRoleNormal, TenantRoleInvite, TenantRoleAdmin).internal/dao/user_tenant.go (1)
176-181: 💤 Low valueSilent no-op when record doesn't exist.
Deletereturns no error when no rows match. If the caller needs to distinguish "successfully removed" from "nothing to remove" (e.g., to return 404), consider returningRowsAffectedor checking it internally.This may be acceptable if the service layer treats "already gone" as success.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/user_tenant.go` around lines 176 - 181, DeleteByUserAndTenant currently performs an Unscoped Delete and returns DB error only, which is silent when no rows matched; change it to inspect the result of DB.Unscoped().Where(...).Delete(&entity.UserTenant{}) and if result.Error != nil return that error, otherwise check result.RowsAffected and return a distinct error (or sentinel like sql.ErrNoRows or a custom NotFound error) when RowsAffected == 0 so callers can distinguish "nothing to remove" from "successfully removed".
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/user_tenant.go`:
- Around line 183-188: UpdateRoleByUserAndTenant currently returns only the DB
error so callers can't tell if no rows were changed; change the implementation
in UpdateRoleByUserAndTenant to capture the result of
DB.Model(&entity.UserTenant{}).Where(...).Update("role", role) into a variable,
check result.Error and return it if set, then check result.RowsAffected and
either return a not-found error (e.g. fmt.Errorf or gorm.ErrRecordNotFound) when
RowsAffected == 0 or change the function signature to return (int64, error) and
return result.RowsAffected along with nil error; update callers (e.g.
AcceptInvite) to handle the zero-rows case accordingly.
In `@internal/handler/tenant.go`:
- Around line 416-418: The Swagger annotations for RemoveTenantMember are
missing the JSON body parameter; update the docblock for the RemoveTenantMember
handler to add a body param that documents the expected JSON payload containing
the required "user_id" field (e.g., `@Param` body body object true "Member removal
payload" schema with user_id string). Ensure the annotation references the
RemoveTenantMember function and matches the actual JSON decoding code that reads
"user_id" so generated docs/clients include the request body.
In `@internal/service/tenant.go`:
- Around line 670-679: The check in AddMember (use
s.userTenantDAO.FilterByUserIDAndTenantID and inspect existing.Role) currently
rejects Owner/Admin/Normal but misses TenantRoleInvite, allowing duplicate
invites; update the switch on existing.Role to include a case for
TenantRoleInvite that returns an appropriate error or the existing invitation
(e.g., return nil, common.CodeDataError, fmt.Errorf("user is already invited"))
so duplicate user_tenant records are not created.
- Around line 706-716: The RemoveMember function currently allows the owner to
remove themselves because it permits userID == targetUserID; add a guard that
prevents deleting the tenant owner by checking if targetUserID == tenantID and
returning an appropriate error (e.g., common.CodeValidationError or a
CodeOperationNotAllowed) before calling userTenantDAO.DeleteByUserAndTenant;
update the error message to clearly state "cannot remove tenant owner" and keep
references to RemoveMember, userID, tenantID, targetUserID, and
userTenantDAO.DeleteByUserAndTenant so the check is added immediately after the
authorization block.
- Around line 718-724: AcceptInvite currently unconditionally sets role to
TenantRoleNormal which can demote an owner; first fetch the membership record
(e.g., via userTenantDAO.GetByUserAndTenant or equivalent) and validate its role
equals TenantRoleInvite before calling userTenantDAO.UpdateRoleByUserAndTenant;
if the record is missing or the role is not TenantRoleInvite, return an
appropriate error code (e.g., common.CodeInvalidRequest or common.CodeForbidden)
and do not perform the update.
---
Nitpick comments:
In `@internal/dao/user_tenant.go`:
- Around line 176-181: DeleteByUserAndTenant currently performs an Unscoped
Delete and returns DB error only, which is silent when no rows matched; change
it to inspect the result of
DB.Unscoped().Where(...).Delete(&entity.UserTenant{}) and if result.Error != nil
return that error, otherwise check result.RowsAffected and return a distinct
error (or sentinel like sql.ErrNoRows or a custom NotFound error) when
RowsAffected == 0 so callers can distinguish "nothing to remove" from
"successfully removed".
In `@internal/service/tenant_test.go`:
- Around line 1-100: The test suite is missing coverage for
TenantService.AcceptInvite; add a unit test mirroring the pattern used for
ListMembers/AddMember/RemoveMember to validate auth/validation behavior. Create
a TestAcceptInviteValidation in internal/service/tenant_test.go that
instantiates s := &TenantService{}, calls s.AcceptInvite with both non-owner
(userID != tenantID) to assert it returns CodeAuthenticationError and non-nil
error, and calls s.AcceptInvite with userID == tenantID to assert it does not
return CodeAuthenticationError (it may return a DB-layer error due to nil DAOs).
Use the same common.CodeAuthenticationError and common.CodeArgumentError checks
and message style as the other tests and reference the AcceptInvite and
TenantService symbols.
- Around line 87-99: The test TestTenantRoleConstants uses an indirect map loop
which obscures intent; replace it with direct assertions comparing each constant
to its expected string (e.g., check TenantRoleOwner == "owner", TenantRoleNormal
== "normal", TenantRoleInvite == "invite", TenantRoleAdmin == "admin") and call
t.Errorf (or t.Fatalf) with clear messages when a mismatch occurs so failures
point to the specific constant (reference symbols: TestTenantRoleConstants,
TenantRoleOwner, TenantRoleNormal, TenantRoleInvite, TenantRoleAdmin).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e1e06c8b-c49d-4eb3-8303-c0d53d373784
📒 Files selected for processing (5)
internal/dao/user_tenant.gointernal/handler/tenant.gointernal/router/router.gointernal/service/tenant.gointernal/service/tenant_test.go
|
Hi, @JinHai-CN , |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @web-dev0521
Do some change will be ok
| func (s *TenantService) ListMembers(userID, tenantID string) ([]*TenantMemberResponse, common.ErrorCode, error) { | ||
| if userID != tenantID { | ||
| return nil, common.CodeAuthenticationError, fmt.Errorf("no authorization") | ||
| } | ||
| rows, err := s.userTenantDAO.GetMembersByTenantID(tenantID) | ||
| if err != nil { | ||
| return nil, common.CodeServerError, err | ||
| } | ||
| result := make([]*TenantMemberResponse, 0, len(rows)) | ||
| for _, r := range rows { | ||
| delta, _ := common.DeltaSeconds(r.UpdateDate) | ||
| result = append(result, &TenantMemberResponse{ | ||
| ID: r.ID, | ||
| UserID: r.UserID, | ||
| Role: r.Role, | ||
| Nickname: r.Nickname, | ||
| Email: r.Email, | ||
| Avatar: r.Avatar, | ||
| IsAuthenticated: r.IsAuthenticated, | ||
| IsActive: r.IsActive, | ||
| IsAnonymous: r.IsAnonymous, | ||
| IsSuperuser: r.IsSuperuser, | ||
| UpdateDate: r.UpdateDate, | ||
| DeltaSeconds: delta, | ||
| }) | ||
| } | ||
| return result, common.CodeSuccess, nil | ||
| } |
There was a problem hiding this comment.
Python response json
{
"code": 0,
"data": [
{
"avatar": null,
"delta_seconds": 3043.117559,
"email": "[email protected]",
"id": "febe9a1c41fc11f1baad2f5f479c7fb2",
"is_active": "1",
"is_anonymous": "0",
"is_authenticated": "1",
"is_superuser": false,
"nickname": "zzz",
"role": "normal",
"status": "1",
"update_date": "2026-05-28T10:17:34",
"user_id": "feb2009a41fc11f1baad2f5f479c7fb2"
}
],
"message": "success"
}
your code response json
{
"code": 0,
"data": [
{
"id": "febe9a1c41fc11f1baad2f5f479c7fb2",
"user_id": "feb2009a41fc11f1baad2f5f479c7fb2",
"role": "normal",
"nickname": "zzz",
"email": "[email protected]",
"avatar": "",
"is_authenticated": true,
"is_active": "1",
"is_anonymous": false,
"is_superuser": false,
"update_date": "2026-05-28T10:17:34+08:00",
"delta_seconds": 3026.635342179
}
],
"message": "success"
}
please align with python
| type AddMemberRequest struct { | ||
| Email string `json:"email"` | ||
| } | ||
|
|
||
| // AddMemberResponse holds the new member's public data. | ||
| type AddMemberResponse struct { | ||
| ID string `json:"id"` | ||
| Avatar string `json:"avatar"` | ||
| Email string `json:"email"` | ||
| Nickname string `json:"nickname"` | ||
| } | ||
|
|
||
| // AddMember invites a user (by email) to the tenant. | ||
| // Only the tenant owner (userID == tenantID) may call this. | ||
| func (s *TenantService) AddMember(userID, tenantID string, req *AddMemberRequest) (*AddMemberResponse, common.ErrorCode, error) { | ||
| if userID != tenantID { | ||
| return nil, common.CodeAuthenticationError, fmt.Errorf("no authorization") | ||
| } | ||
| if req.Email == "" { | ||
| return nil, common.CodeArgumentError, fmt.Errorf("email is required") | ||
| } | ||
|
|
||
| invitee, err := s.userDAO.GetByEmail(req.Email) | ||
| if err != nil { | ||
| return nil, common.CodeDataError, fmt.Errorf("user not found") | ||
| } | ||
|
|
||
| // Reject if already a member (owner or normal). | ||
| existing, _ := s.userTenantDAO.FilterByUserIDAndTenantID(invitee.ID, tenantID) | ||
| if existing != nil { | ||
| switch existing.Role { | ||
| case TenantRoleOwner: | ||
| return nil, common.CodeDataError, fmt.Errorf("user is already the tenant owner") | ||
| case TenantRoleNormal, TenantRoleAdmin: | ||
| return nil, common.CodeDataError, fmt.Errorf("user is already a member") | ||
| } | ||
| } | ||
|
|
||
| status := "1" | ||
| ut := &entity.UserTenant{ | ||
| ID: common.GenerateUUID(), | ||
| UserID: invitee.ID, | ||
| TenantID: tenantID, | ||
| Role: TenantRoleInvite, | ||
| InvitedBy: userID, | ||
| Status: &status, | ||
| } | ||
| if err := s.userTenantDAO.Create(ut); err != nil { | ||
| return nil, common.CodeServerError, fmt.Errorf("failed to create invitation: %w", err) | ||
| } | ||
|
|
||
| avatar := "" | ||
| if invitee.Avatar != nil { | ||
| avatar = *invitee.Avatar | ||
| } | ||
| return &AddMemberResponse{ | ||
| ID: invitee.ID, | ||
| Avatar: avatar, | ||
| Email: invitee.Email, | ||
| Nickname: invitee.Nickname, | ||
| }, common.CodeSuccess, nil | ||
| } |
There was a problem hiding this comment.
Resending invitations is not allowed.
…ove, duplicate invites, status field, timestamp format, Swagger annotation
|
Hi, @Haruko386 , |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15295 +/- ##
==========================================
- Coverage 94.53% 93.16% -1.37%
==========================================
Files 10 10
Lines 713 717 +4
Branches 116 118 +2
==========================================
- Hits 674 668 -6
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
|
Hi, @JinHai-CN , |
Summary
Ports the Python
tenant_apiteam/member management endpoints to Go, adding 4 endpoints under/api/v1/tenants/:tenant_id/:GET /tenants/:tenant_id/users— list non-owner members with user details (owner only)POST /tenants/:tenant_id/users— invite a user by email; creates invite-role join record (owner only)DELETE /tenants/:tenant_id/users— remove a member byuser_id; owner can remove anyone, members can remove themselvesPATCH /tenants/:tenant_id— accept a pending invitation, transitioning roleinvite → normalChanges
internal/dao/user_tenant.goGetMembersByTenantID(JOIN with user table),DeleteByUserAndTenant,UpdateRoleByUserAndTenantinternal/service/tenant.goListMembers,AddMember,RemoveMember,AcceptInvite; role constants; adduserDAOfor email lookupinternal/handler/tenant.goListTenantMembers,AddTenantMember,RemoveTenantMember,AcceptTenantInviteinternal/router/router.gotenantsgroupinternal/service/tenant_test.goPermission model
Mirrors Python exactly:
userID == tenantID(owner check)userID == tenantID(owner) ORuserID == targetUserID(self-removal)Closes #15294