feat(rbac): lift org membership from per-user to per-tenant (Plan 3, #1303)
Before this change, the `organization_members` table keyed on user_id — joining an org as a Viewer in tenant T meant only that one user got visibility on shared KBs/agents, while the rest of T (including its Owner) saw nothing. The mismatch surfaced as confusing UX bugs: "my colleague shared this with us, why can't I see it?" This change replaces `organization_members` with `organization_tenant_members`. Membership and Org-RBAC role now key on (org_id, tenant_id); `representative_user_id` stays as a display-only label of the user who first brought the tenant in. Permission resolution gains a 3-D cap so tenant-RBAC stays honest under cross-tenant sharing: effective = min(share.Permission, tenant_org_role, tenant_role_cap) where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless of the org-level grant. A Viewer in their own tenant cannot edit a shared KB even if the org granted Editor — preserves the "Viewer = read-only everywhere" promise. Migration 000045 backfills `organization_tenant_members` from the old table by collapsing each (org, tenant) group to its max role, then renames the old table to `organization_members_pre_plan3` for safe rollback. Sqlite mirror (Lite mode) is fresh-bootstrap: the init schema replaces the old table directly. Routes: member-management URLs change from `:user_id` to `:tenant_id`. Org create / join / leave now require Admin+ in the caller's tenant — joining an Org affects everyone in T, so the decision can't sit with a Viewer. Frontend: OrganizationSettingsModal + store update to address members by tenant_id.
This commit is contained in:
@@ -470,11 +470,11 @@ export async function listMembers(orgId: string): Promise<ApiResponse<ListMember
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update member role
|
* Update member role (member is identified by tenant_id)
|
||||||
*/
|
*/
|
||||||
export async function updateMemberRole(orgId: string, userId: string, req: UpdateMemberRoleRequest): Promise<ApiResponse<void>> {
|
export async function updateMemberRole(orgId: string, tenantId: number, req: UpdateMemberRoleRequest): Promise<ApiResponse<void>> {
|
||||||
try {
|
try {
|
||||||
const response = await put(`/api/v1/organizations/${orgId}/members/${userId}`, req)
|
const response = await put(`/api/v1/organizations/${orgId}/members/${tenantId}`, req)
|
||||||
return response as unknown as ApiResponse<void>
|
return response as unknown as ApiResponse<void>
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return { success: false, message: error.message || 'Failed to update member role' }
|
return { success: false, message: error.message || 'Failed to update member role' }
|
||||||
@@ -482,11 +482,11 @@ export async function updateMemberRole(orgId: string, userId: string, req: Updat
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove member
|
* Remove member (member is identified by tenant_id)
|
||||||
*/
|
*/
|
||||||
export async function removeMember(orgId: string, userId: string): Promise<ApiResponse<void>> {
|
export async function removeMember(orgId: string, tenantId: number): Promise<ApiResponse<void>> {
|
||||||
try {
|
try {
|
||||||
const response = await del(`/api/v1/organizations/${orgId}/members/${userId}`)
|
const response = await del(`/api/v1/organizations/${orgId}/members/${tenantId}`)
|
||||||
return response as unknown as ApiResponse<void>
|
return response as unknown as ApiResponse<void>
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return { success: false, message: error.message || 'Failed to remove member' }
|
return { success: false, message: error.message || 'Failed to remove member' }
|
||||||
|
|||||||
@@ -294,15 +294,15 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update a member's role
|
* Update a member's role (member identified by tenant_id)
|
||||||
*/
|
*/
|
||||||
async function changeMemberRole(orgId: string, userId: string, role: 'admin' | 'editor' | 'viewer') {
|
async function changeMemberRole(orgId: string, tenantId: number, role: 'admin' | 'editor' | 'viewer') {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
error.value = null
|
error.value = null
|
||||||
try {
|
try {
|
||||||
const response = await updateMemberRole(orgId, userId, { role })
|
const response = await updateMemberRole(orgId, tenantId, { role })
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
const member = currentMembers.value.find(m => m.user_id === userId)
|
const member = currentMembers.value.find(m => m.tenant_id === tenantId)
|
||||||
if (member) {
|
if (member) {
|
||||||
member.role = role
|
member.role = role
|
||||||
}
|
}
|
||||||
@@ -320,15 +320,15 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a member from organization
|
* Remove a member from organization (member identified by tenant_id)
|
||||||
*/
|
*/
|
||||||
async function kickMember(orgId: string, userId: string) {
|
async function kickMember(orgId: string, tenantId: number) {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
error.value = null
|
error.value = null
|
||||||
try {
|
try {
|
||||||
const response = await removeMember(orgId, userId)
|
const response = await removeMember(orgId, tenantId)
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
currentMembers.value = currentMembers.value.filter(m => m.user_id !== userId)
|
currentMembers.value = currentMembers.value.filter(m => m.tenant_id !== tenantId)
|
||||||
return true
|
return true
|
||||||
} else {
|
} else {
|
||||||
error.value = response.message || 'Failed to remove member'
|
error.value = response.message || 'Failed to remove member'
|
||||||
|
|||||||
@@ -1172,7 +1172,7 @@ const handleSave = async () => {
|
|||||||
const handleRoleChange = async (member: OrganizationMember, newRole: string) => {
|
const handleRoleChange = async (member: OrganizationMember, newRole: string) => {
|
||||||
if (!props.orgId) return
|
if (!props.orgId) return
|
||||||
try {
|
try {
|
||||||
const res = await updateMemberRole(props.orgId, member.user_id, {
|
const res = await updateMemberRole(props.orgId, member.tenant_id, {
|
||||||
role: newRole as 'admin' | 'editor' | 'viewer'
|
role: newRole as 'admin' | 'editor' | 'viewer'
|
||||||
})
|
})
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
@@ -1196,7 +1196,7 @@ const confirmRemoveMember = async () => {
|
|||||||
if (!removingMember.value || !props.orgId) return
|
if (!removingMember.value || !props.orgId) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await removeMember(props.orgId, removingMember.value.user_id)
|
const res = await removeMember(props.orgId, removingMember.value.tenant_id)
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
MessagePlugin.success(t('organization.memberRemoved'))
|
MessagePlugin.success(t('organization.memberRemoved'))
|
||||||
showRemoveDialog.value = false
|
showRemoveDialog.value = false
|
||||||
|
|||||||
@@ -166,16 +166,18 @@ func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to
|
// ListSharedAgentsForTenant lists all agents shared to organizations that the
|
||||||
func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) {
|
// caller's tenant participates in. Plan 3 of #1303 keys this on tenant rather
|
||||||
|
// than user.
|
||||||
|
func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, tenantID uint64) ([]*types.AgentShare, error) {
|
||||||
var shares []*types.AgentShare
|
var shares []*types.AgentShare
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||||
Preload("Agent").
|
Preload("Agent").
|
||||||
Preload("Organization").
|
Preload("Organization").
|
||||||
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
|
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||||
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
|
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||||
Where("organization_members.user_id = ?", userID).
|
Where("otm.tenant_id = ?", tenantID).
|
||||||
Where("agent_shares.deleted_at IS NULL").
|
Where("agent_shares.deleted_at IS NULL").
|
||||||
Order("agent_shares.created_at DESC").
|
Order("agent_shares.created_at DESC").
|
||||||
Find(&shares).Error
|
Find(&shares).Error
|
||||||
@@ -185,13 +187,15 @@ func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, user
|
|||||||
return shares, nil
|
return shares, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. Single query.
|
// GetShareByAgentIDForTenant returns one share for the given agentID that the
|
||||||
func (r *agentShareRepository) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
// tenant can reach (tenant participates in some org with the share), excluding
|
||||||
|
// source_tenant_id == excludeTenantID. Single query.
|
||||||
|
func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
||||||
var share types.AgentShare
|
var share types.AgentShare
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
|
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||||
Where("agent_shares.agent_id = ?", agentID).
|
Where("agent_shares.agent_id = ?", agentID).
|
||||||
Where("organization_members.user_id = ?", userID).
|
Where("otm.tenant_id = ?", tenantID).
|
||||||
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
|
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
|
||||||
Where("agent_shares.deleted_at IS NULL").
|
Where("agent_shares.deleted_at IS NULL").
|
||||||
First(&share).Error
|
First(&share).Error
|
||||||
|
|||||||
@@ -145,19 +145,19 @@ func (r *kbShareRepository) ListByOrganizations(ctx context.Context, orgIDs []st
|
|||||||
return shares, nil
|
return shares, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedKBsForUser lists all knowledge bases shared to organizations that the user belongs to.
|
// ListSharedKBsForTenant lists all knowledge bases shared to organizations that the tenant participates in.
|
||||||
// Excludes shares for soft-deleted organizations and soft-deleted knowledge bases.
|
// Excludes shares for soft-deleted organizations and soft-deleted knowledge bases.
|
||||||
func (r *kbShareRepository) ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) {
|
func (r *kbShareRepository) ListSharedKBsForTenant(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBaseShare, error) {
|
||||||
var shares []*types.KnowledgeBaseShare
|
var shares []*types.KnowledgeBaseShare
|
||||||
|
|
||||||
// Get shares for organizations that the user is a member of; exclude deleted orgs and deleted KBs
|
// Get shares for organizations the tenant is a member of; exclude deleted orgs and deleted KBs.
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||||
Preload("KnowledgeBase").
|
Preload("KnowledgeBase").
|
||||||
Preload("Organization").
|
Preload("Organization").
|
||||||
Joins("JOIN organization_members ON organization_members.organization_id = kb_shares.organization_id").
|
Joins("JOIN organization_tenant_members otm ON otm.organization_id = kb_shares.organization_id").
|
||||||
Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL").
|
Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||||
Where("organization_members.user_id = ?", userID).
|
Where("otm.tenant_id = ?", tenantID).
|
||||||
Where("kb_shares.deleted_at IS NULL").
|
Where("kb_shares.deleted_at IS NULL").
|
||||||
Order("kb_shares.created_at DESC").
|
Order("kb_shares.created_at DESC").
|
||||||
Find(&shares).Error
|
Find(&shares).Error
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ var (
|
|||||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||||
)
|
)
|
||||||
|
|
||||||
// organizationRepository implements OrganizationRepository interface
|
// organizationRepository implements OrganizationRepository.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303 lifts membership from per-user to per-tenant (see
|
||||||
|
// migration 000045). All "member" methods on this repo now operate on
|
||||||
|
// the (org, tenant) tuple; the underlying table is
|
||||||
|
// organization_tenant_members.
|
||||||
type organizationRepository struct {
|
type organizationRepository struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
}
|
}
|
||||||
@@ -60,14 +65,13 @@ func (r *organizationRepository) GetByInviteCode(ctx context.Context, inviteCode
|
|||||||
return &org, nil
|
return &org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListByUserID lists organizations that a user belongs to
|
// ListByTenantID lists organizations whose tenant participates as a member.
|
||||||
func (r *organizationRepository) ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error) {
|
func (r *organizationRepository) ListByTenantID(ctx context.Context, tenantID uint64) ([]*types.Organization, error) {
|
||||||
var orgs []*types.Organization
|
var orgs []*types.Organization
|
||||||
|
|
||||||
// Get organizations where user is a member
|
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Joins("JOIN organization_members ON organization_members.organization_id = organizations.id").
|
Joins("JOIN organization_tenant_members otm ON otm.organization_id = organizations.id").
|
||||||
Where("organization_members.user_id = ?", userID).
|
Where("otm.tenant_id = ?", tenantID).
|
||||||
Order("organizations.created_at DESC").
|
Order("organizations.created_at DESC").
|
||||||
Find(&orgs).Error
|
Find(&orgs).Error
|
||||||
|
|
||||||
@@ -108,12 +112,14 @@ func (r *organizationRepository) Delete(ctx context.Context, id string) error {
|
|||||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error
|
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMember adds a member to an organization
|
// AddTenantMember inserts a new (org, tenant) membership row. Returns
|
||||||
func (r *organizationRepository) AddMember(ctx context.Context, member *types.OrganizationMember) error {
|
// ErrOrgMemberAlreadyExists if a row already exists for this tuple — the
|
||||||
// Check if member already exists
|
// service layer treats that as a no-op when the caller is just confirming
|
||||||
|
// an idempotent join.
|
||||||
|
func (r *organizationRepository) AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember) error {
|
||||||
var count int64
|
var count int64
|
||||||
r.db.WithContext(ctx).Model(&types.OrganizationMember{}).
|
r.db.WithContext(ctx).Model(&types.OrganizationTenantMember{}).
|
||||||
Where("organization_id = ? AND user_id = ?", member.OrganizationID, member.UserID).
|
Where("organization_id = ? AND tenant_id = ?", member.OrganizationID, member.TenantID).
|
||||||
Count(&count)
|
Count(&count)
|
||||||
|
|
||||||
if count > 0 {
|
if count > 0 {
|
||||||
@@ -123,11 +129,11 @@ func (r *organizationRepository) AddMember(ctx context.Context, member *types.Or
|
|||||||
return r.db.WithContext(ctx).Create(member).Error
|
return r.db.WithContext(ctx).Create(member).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveMember removes a member from an organization
|
// RemoveTenantMember removes the (org, tenant) membership row.
|
||||||
func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string, userID string) error {
|
func (r *organizationRepository) RemoveTenantMember(ctx context.Context, orgID string, tenantID uint64) error {
|
||||||
result := r.db.WithContext(ctx).
|
result := r.db.WithContext(ctx).
|
||||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||||
Delete(&types.OrganizationMember{})
|
Delete(&types.OrganizationTenantMember{})
|
||||||
|
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
return result.Error
|
return result.Error
|
||||||
@@ -138,11 +144,11 @@ func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string,
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateMemberRole updates a member's role in an organization
|
// UpdateTenantMemberRole updates the role for a (org, tenant) membership.
|
||||||
func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error {
|
func (r *organizationRepository) UpdateTenantMemberRole(ctx context.Context, orgID string, tenantID uint64, role types.OrgMemberRole) error {
|
||||||
result := r.db.WithContext(ctx).
|
result := r.db.WithContext(ctx).
|
||||||
Model(&types.OrganizationMember{}).
|
Model(&types.OrganizationTenantMember{}).
|
||||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||||
Update("role", role)
|
Update("role", role)
|
||||||
|
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
@@ -154,11 +160,11 @@ func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID str
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMembers lists all members of an organization
|
// ListTenantMembers lists all tenant memberships for an organization.
|
||||||
func (r *organizationRepository) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
func (r *organizationRepository) ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) {
|
||||||
var members []*types.OrganizationMember
|
var members []*types.OrganizationTenantMember
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Preload("User").
|
Preload("RepresentativeUser").
|
||||||
Where("organization_id = ?", orgID).
|
Where("organization_id = ?", orgID).
|
||||||
Order("created_at ASC").
|
Order("created_at ASC").
|
||||||
Find(&members).Error
|
Find(&members).Error
|
||||||
@@ -169,11 +175,14 @@ func (r *organizationRepository) ListMembers(ctx context.Context, orgID string)
|
|||||||
return members, nil
|
return members, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMember gets a specific member of an organization
|
// GetTenantMember returns the (org, tenant) membership row, or
|
||||||
func (r *organizationRepository) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
// ErrOrgMemberNotFound when missing. This is the canonical permission
|
||||||
var member types.OrganizationMember
|
// check primitive — callers compose this with the share permission
|
||||||
|
// to compute effective access.
|
||||||
|
func (r *organizationRepository) GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) {
|
||||||
|
var member types.OrganizationTenantMember
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
Where("organization_id = ? AND tenant_id = ?", orgID, tenantID).
|
||||||
First(&member).Error
|
First(&member).Error
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -185,19 +194,20 @@ func (r *organizationRepository) GetMember(ctx context.Context, orgID string, us
|
|||||||
return &member, nil
|
return &member, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMembersByUserForOrgs returns one member record per org where the user is a member (batch).
|
// ListTenantMembersByTenantForOrgs returns one membership row per org where
|
||||||
func (r *organizationRepository) ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error) {
|
// the tenant participates (batch).
|
||||||
|
func (r *organizationRepository) ListTenantMembersByTenantForOrgs(ctx context.Context, tenantID uint64, orgIDs []string) (map[string]*types.OrganizationTenantMember, error) {
|
||||||
if len(orgIDs) == 0 {
|
if len(orgIDs) == 0 {
|
||||||
return make(map[string]*types.OrganizationMember), nil
|
return make(map[string]*types.OrganizationTenantMember), nil
|
||||||
}
|
}
|
||||||
var members []*types.OrganizationMember
|
var members []*types.OrganizationTenantMember
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Where("user_id = ? AND organization_id IN ?", userID, orgIDs).
|
Where("tenant_id = ? AND organization_id IN ?", tenantID, orgIDs).
|
||||||
Find(&members).Error
|
Find(&members).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
out := make(map[string]*types.OrganizationMember, len(members))
|
out := make(map[string]*types.OrganizationTenantMember, len(members))
|
||||||
for _, m := range members {
|
for _, m := range members {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
out[m.OrganizationID] = m
|
out[m.OrganizationID] = m
|
||||||
@@ -206,11 +216,11 @@ func (r *organizationRepository) ListMembersByUserForOrgs(ctx context.Context, u
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CountMembers counts the number of members in an organization
|
// CountTenantMembers counts the number of tenant members in an organization.
|
||||||
func (r *organizationRepository) CountMembers(ctx context.Context, orgID string) (int64, error) {
|
func (r *organizationRepository) CountTenantMembers(ctx context.Context, orgID string) (int64, error) {
|
||||||
var count int64
|
var count int64
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Model(&types.OrganizationMember{}).
|
Model(&types.OrganizationTenantMember{}).
|
||||||
Where("organization_id = ?", orgID).
|
Where("organization_id = ?", orgID).
|
||||||
Count(&count).Error
|
Count(&count).Error
|
||||||
return count, err
|
return count, err
|
||||||
@@ -252,11 +262,15 @@ func (r *organizationRepository) GetJoinRequestByID(ctx context.Context, id stri
|
|||||||
return &request, nil
|
return &request, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPendingJoinRequest gets a pending join request for a user in an organization (any type)
|
// GetPendingJoinRequestByTenant returns a pending request for the given
|
||||||
func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
// (org, tenant). After Plan 3 the dedup key is per-tenant, not per-user
|
||||||
|
// — the user requesting and the user reviewing may be different humans
|
||||||
|
// in the same tenant, but the resource being granted is tenant-level
|
||||||
|
// access.
|
||||||
|
func (r *organizationRepository) GetPendingJoinRequestByTenant(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) {
|
||||||
var request types.OrganizationJoinRequest
|
var request types.OrganizationJoinRequest
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Where("organization_id = ? AND user_id = ? AND status = ?", orgID, userID, types.JoinRequestStatusPending).
|
Where("organization_id = ? AND tenant_id = ? AND status = ?", orgID, tenantID, types.JoinRequestStatusPending).
|
||||||
First(&request).Error
|
First(&request).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
@@ -267,11 +281,12 @@ func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgI
|
|||||||
return &request, nil
|
return &request, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPendingRequestByType gets a pending request for a user filtered by request type
|
// GetPendingRequestByTenantAndType narrows the (org, tenant) pending
|
||||||
func (r *organizationRepository) GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) {
|
// dedup query to a specific request_type (join | upgrade).
|
||||||
|
func (r *organizationRepository) GetPendingRequestByTenantAndType(ctx context.Context, orgID string, tenantID uint64, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) {
|
||||||
var request types.OrganizationJoinRequest
|
var request types.OrganizationJoinRequest
|
||||||
err := r.db.WithContext(ctx).
|
err := r.db.WithContext(ctx).
|
||||||
Where("organization_id = ? AND user_id = ? AND status = ? AND request_type = ?", orgID, userID, types.JoinRequestStatusPending, requestType).
|
Where("organization_id = ? AND tenant_id = ? AND status = ? AND request_type = ?", orgID, tenantID, types.JoinRequestStatusPending, requestType).
|
||||||
First(&request).Error
|
First(&request).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
|||||||
@@ -49,7 +49,11 @@ func agentRequiresRerankModel(agent *types.CustomAgent) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// agentShareService implements AgentShareService interface
|
// agentShareService implements AgentShareService.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: visibility and access checks key on the caller's
|
||||||
|
// tenant. callerTenantRole flows through every read path so the 3-D
|
||||||
|
// cap (tenant Viewer → at most OrgRoleViewer) lands consistently.
|
||||||
type agentShareService struct {
|
type agentShareService struct {
|
||||||
shareRepo interfaces.AgentShareRepository
|
shareRepo interfaces.AgentShareRepository
|
||||||
disabledRepo interfaces.TenantDisabledSharedAgentRepository
|
disabledRepo interfaces.TenantDisabledSharedAgentRepository
|
||||||
@@ -75,7 +79,8 @@ func NewAgentShareService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShareAgent shares an agent to an organization
|
// ShareAgent shares an agent to an organization. Permission is forced to
|
||||||
|
// OrgRoleViewer (cross-tenant agent edit is not part of v1).
|
||||||
func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) {
|
func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) {
|
||||||
logger.Infof(ctx, "Sharing agent %s to organization %s", agentID, orgID)
|
logger.Infof(ctx, "Sharing agent %s to organization %s", agentID, orgID)
|
||||||
|
|
||||||
@@ -87,10 +92,6 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI
|
|||||||
return nil, ErrNotAgentOwner
|
return nil, ErrNotAgentOwner
|
||||||
}
|
}
|
||||||
|
|
||||||
// Require agent to be fully configured before sharing (same rules as for
|
|
||||||
// conversation — see session_agent_qa.go). Rerank model is only required
|
|
||||||
// when the `knowledge_search` tool is enabled; Wiki-only agents
|
|
||||||
// (wiki_search / wiki_read_page) don't call the reranker at runtime.
|
|
||||||
if agent.Config.ModelID == "" {
|
if agent.Config.ModelID == "" {
|
||||||
return nil, ErrAgentNotConfigured
|
return nil, ErrAgentNotConfigured
|
||||||
}
|
}
|
||||||
@@ -106,18 +107,19 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
// Caller's tenant must be an org member with editor+ role to share.
|
||||||
|
tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !member.Role.HasPermission(types.OrgRoleEditor) {
|
if !tm.Role.HasPermission(types.OrgRoleEditor) {
|
||||||
return nil, ErrOrgRoleCannotShareAgent
|
return nil, ErrOrgRoleCannotShareAgent
|
||||||
}
|
}
|
||||||
|
|
||||||
// 智能体共享仅支持只读,不支持可编辑
|
// 智能体共享仅支持只读
|
||||||
permission = types.OrgRoleViewer
|
permission = types.OrgRoleViewer
|
||||||
|
|
||||||
share := &types.AgentShare{
|
share := &types.AgentShare{
|
||||||
@@ -151,8 +153,9 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI
|
|||||||
return share, nil
|
return share, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveShare removes an agent share
|
// RemoveShare removes an agent share.
|
||||||
func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
|
// Same authz envelope as KB-share remove: original sharer or org admin.
|
||||||
|
func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error {
|
||||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrAgentShareNotFound) {
|
if errors.Is(err, repository.ErrAgentShareNotFound) {
|
||||||
@@ -163,8 +166,8 @@ func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, use
|
|||||||
if share.SharedByUserID == userID {
|
if share.SharedByUserID == userID {
|
||||||
return s.shareRepo.Delete(ctx, shareID)
|
return s.shareRepo.Delete(ctx, shareID)
|
||||||
}
|
}
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
|
||||||
if err == nil && member.Role == types.OrgRoleAdmin {
|
if err == nil && tm.Role == types.OrgRoleAdmin {
|
||||||
return s.shareRepo.Delete(ctx, shareID)
|
return s.shareRepo.Delete(ctx, shareID)
|
||||||
}
|
}
|
||||||
return ErrAgentSharePermission
|
return ErrAgentSharePermission
|
||||||
@@ -180,35 +183,33 @@ func (s *agentShareService) ListSharesByOrganization(ctx context.Context, orgID
|
|||||||
return s.shareRepo.ListByOrganization(ctx, orgID)
|
return s.shareRepo.ListByOrganization(ctx, orgID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedAgents lists agents shared to the user through organizations, deduplicated by agent ID (keep highest permission)
|
// ListSharedAgents lists agents reachable from the caller's tenant.
|
||||||
func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error) {
|
func (s *agentShareService) ListSharedAgents(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedAgentInfo, error) {
|
||||||
shares, err := s.shareRepo.ListSharedAgentsForUser(ctx, userID)
|
shares, err := s.shareRepo.ListSharedAgentsForTenant(ctx, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
agentInfoMap := make(map[string]*types.SharedAgentInfo)
|
agentInfoMap := make(map[string]*types.SharedAgentInfo)
|
||||||
for _, share := range shares {
|
for _, share := range shares {
|
||||||
if share.SourceTenantID == currentTenantID {
|
if share.SourceTenantID == tenantID {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if share.Agent == nil {
|
if share.Agent == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
effectivePermission := share.Permission
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
info := &types.SharedAgentInfo{
|
info := &types.SharedAgentInfo{
|
||||||
Agent: share.Agent,
|
Agent: share.Agent,
|
||||||
ShareID: share.ID,
|
ShareID: share.ID,
|
||||||
OrganizationID: share.OrganizationID,
|
OrganizationID: share.OrganizationID,
|
||||||
OrgName: "",
|
OrgName: "",
|
||||||
Permission: effectivePermission,
|
Permission: effective,
|
||||||
SourceTenantID: share.SourceTenantID,
|
SourceTenantID: share.SourceTenantID,
|
||||||
SharedAt: share.CreatedAt,
|
SharedAt: share.CreatedAt,
|
||||||
SharedByUserID: share.SharedByUserID,
|
SharedByUserID: share.SharedByUserID,
|
||||||
@@ -225,7 +226,7 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string,
|
|||||||
existing, exists := agentInfoMap[key]
|
existing, exists := agentInfoMap[key]
|
||||||
if !exists {
|
if !exists {
|
||||||
agentInfoMap[key] = info
|
agentInfoMap[key] = info
|
||||||
} else if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
|
} else if effective.HasPermission(existing.Permission) && effective != existing.Permission {
|
||||||
agentInfoMap[key] = info
|
agentInfoMap[key] = info
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -236,9 +237,9 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set DisabledByMe from tenant_disabled_shared_agents for current tenant
|
// Set DisabledByMe from tenant_disabled_shared_agents for current tenant
|
||||||
disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID)
|
disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return result, nil // non-fatal: return list without DisabledByMe
|
return result, nil
|
||||||
}
|
}
|
||||||
disabledSet := make(map[string]bool)
|
disabledSet := make(map[string]bool)
|
||||||
for _, d := range disabledList {
|
for _, d := range disabledList {
|
||||||
@@ -253,12 +254,14 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string,
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedAgentsInOrganization returns all agents shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
|
// ListSharedAgentsInOrganization returns all agents shared to the given
|
||||||
func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error) {
|
// organization (including those shared by the caller's tenant), for list-page
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
// display when a space is selected.
|
||||||
|
func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) {
|
||||||
|
tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -274,10 +277,8 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
effectivePermission := share.Permission
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
|
|
||||||
orgName := ""
|
orgName := ""
|
||||||
if share.Organization != nil {
|
if share.Organization != nil {
|
||||||
@@ -288,7 +289,7 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
|
|||||||
ShareID: share.ID,
|
ShareID: share.ID,
|
||||||
OrganizationID: share.OrganizationID,
|
OrganizationID: share.OrganizationID,
|
||||||
OrgName: orgName,
|
OrgName: orgName,
|
||||||
Permission: effectivePermission,
|
Permission: effective,
|
||||||
SourceTenantID: share.SourceTenantID,
|
SourceTenantID: share.SourceTenantID,
|
||||||
SharedAt: share.CreatedAt,
|
SharedAt: share.CreatedAt,
|
||||||
SharedByUserID: share.SharedByUserID,
|
SharedByUserID: share.SharedByUserID,
|
||||||
@@ -301,13 +302,12 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
|
|||||||
|
|
||||||
item := &types.OrganizationSharedAgentItem{
|
item := &types.OrganizationSharedAgentItem{
|
||||||
SharedAgentInfo: *info,
|
SharedAgentInfo: *info,
|
||||||
IsMine: share.SourceTenantID == currentTenantID,
|
IsMine: share.SourceTenantID == tenantID,
|
||||||
}
|
}
|
||||||
result = append(result, item)
|
result = append(result, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set DisabledByMe for entries shared by others (mine entries stay false)
|
disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID)
|
||||||
disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
disabledSet := make(map[string]bool)
|
disabledSet := make(map[string]bool)
|
||||||
for _, d := range disabledList {
|
for _, d := range disabledList {
|
||||||
@@ -323,13 +323,14 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedAgentsInOrganizations returns per-org agent lists (batch); only orgs where user is member.
|
// ListSharedAgentsInOrganizations returns per-org agent lists (batch); only
|
||||||
func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error) {
|
// orgs where the caller's tenant is a member.
|
||||||
|
func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, tenantID uint64, callerTenantRole types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) {
|
||||||
out := make(map[string][]*types.OrganizationSharedAgentItem)
|
out := make(map[string][]*types.OrganizationSharedAgentItem)
|
||||||
if len(orgIDs) == 0 {
|
if len(orgIDs) == 0 {
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs)
|
members, err := s.orgRepo.ListTenantMembersByTenantForOrgs(ctx, tenantID, orgIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -344,22 +345,20 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
disabledSet := make(map[string]bool)
|
disabledSet := make(map[string]bool)
|
||||||
if disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID); err == nil {
|
if disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID); err == nil {
|
||||||
for _, d := range disabledList {
|
for _, d := range disabledList {
|
||||||
disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true
|
disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for orgID, list := range byOrg {
|
for orgID, list := range byOrg {
|
||||||
member := members[orgID]
|
tm := members[orgID]
|
||||||
result := make([]*types.OrganizationSharedAgentItem, 0, len(list))
|
result := make([]*types.OrganizationSharedAgentItem, 0, len(list))
|
||||||
for _, share := range list {
|
for _, share := range list {
|
||||||
if share.Agent == nil {
|
if share.Agent == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
effectivePermission := share.Permission
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
orgName := ""
|
orgName := ""
|
||||||
if share.Organization != nil {
|
if share.Organization != nil {
|
||||||
orgName = share.Organization.Name
|
orgName = share.Organization.Name
|
||||||
@@ -369,7 +368,7 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context,
|
|||||||
ShareID: share.ID,
|
ShareID: share.ID,
|
||||||
OrganizationID: share.OrganizationID,
|
OrganizationID: share.OrganizationID,
|
||||||
OrgName: orgName,
|
OrgName: orgName,
|
||||||
Permission: effectivePermission,
|
Permission: effective,
|
||||||
SourceTenantID: share.SourceTenantID,
|
SourceTenantID: share.SourceTenantID,
|
||||||
SharedAt: share.CreatedAt,
|
SharedAt: share.CreatedAt,
|
||||||
SharedByUserID: share.SharedByUserID,
|
SharedByUserID: share.SharedByUserID,
|
||||||
@@ -381,7 +380,7 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context,
|
|||||||
}
|
}
|
||||||
item := &types.OrganizationSharedAgentItem{
|
item := &types.OrganizationSharedAgentItem{
|
||||||
SharedAgentInfo: *info,
|
SharedAgentInfo: *info,
|
||||||
IsMine: share.SourceTenantID == currentTenantID,
|
IsMine: share.SourceTenantID == tenantID,
|
||||||
}
|
}
|
||||||
if item.Agent != nil && !item.IsMine {
|
if item.Agent != nil && !item.IsMine {
|
||||||
item.DisabledByMe = disabledSet[fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)]
|
item.DisabledByMe = disabledSet[fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)]
|
||||||
@@ -406,12 +405,18 @@ func (s *agentShareService) SetSharedAgentDisabledByMe(ctx context.Context, tena
|
|||||||
return s.disabledRepo.Remove(ctx, tenantID, agentID, sourceTenantID)
|
return s.disabledRepo.Remove(ctx, tenantID, agentID, sourceTenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSharedAgentForUser returns the shared agent by agentID if the user has access; source tenant is resolved from the user's share. One share lookup + one agent lookup.
|
// GetSharedAgentForTenant returns the shared agent by agentID if the caller's
|
||||||
func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error) {
|
// tenant has access; source tenant is resolved from the share. One share
|
||||||
|
// lookup + one agent lookup.
|
||||||
|
//
|
||||||
|
// callerTenantRole is currently only used for symmetry / future caps on
|
||||||
|
// agent execution (e.g. tenant Viewers might be banned from
|
||||||
|
// state-changing tool calls in a follow-up).
|
||||||
|
func (s *agentShareService) GetSharedAgentForTenant(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, agentID string) (*types.CustomAgent, error) {
|
||||||
if agentID == "" {
|
if agentID == "" {
|
||||||
return nil, ErrAgentShareNotFound
|
return nil, ErrAgentShareNotFound
|
||||||
}
|
}
|
||||||
share, err := s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, currentTenantID)
|
share, err := s.shareRepo.GetShareByAgentIDForTenant(ctx, tenantID, agentID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrAgentShareNotFound) {
|
if errors.Is(err, repository.ErrAgentShareNotFound) {
|
||||||
return nil, ErrAgentSharePermission
|
return nil, ErrAgentSharePermission
|
||||||
@@ -425,15 +430,18 @@ func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID st
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
_ = callerTenantRole
|
||||||
return agent, nil
|
return agent, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (used when opening KB detail from space list without agent_id).
|
// TenantCanAccessKBViaSomeSharedAgent returns true if the caller's tenant has
|
||||||
func (s *agentShareService) UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error) {
|
// at least one shared agent that can access the given KB (used when opening KB
|
||||||
|
// detail from "通过智能体可见" list without agent_id).
|
||||||
|
func (s *agentShareService) TenantCanAccessKBViaSomeSharedAgent(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, kb *types.KnowledgeBase) (bool, error) {
|
||||||
if kb == nil || kb.ID == "" {
|
if kb == nil || kb.ID == "" {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
list, err := s.ListSharedAgents(ctx, userID, currentTenantID)
|
list, err := s.ListSharedAgents(ctx, tenantID, callerTenantRole)
|
||||||
if err != nil || len(list) == 0 {
|
if err != nil || len(list) == 0 {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
@@ -487,7 +495,8 @@ func (s *agentShareService) GetShareByAgentAndOrg(ctx context.Context, agentID s
|
|||||||
return share, nil
|
return share, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
|
// GetShareByAgentIDForTenant returns one share for the given agentID that the
|
||||||
func (s *agentShareService) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
// tenant can reach, excluding source_tenant_id == excludeTenantID.
|
||||||
return s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, excludeTenantID)
|
func (s *agentShareService) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
||||||
|
return s.shareRepo.GetShareByAgentIDForTenant(ctx, tenantID, agentID, excludeTenantID)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,11 +17,22 @@ var (
|
|||||||
ErrSharePermissionDenied = errors.New("permission denied for this share operation")
|
ErrSharePermissionDenied = errors.New("permission denied for this share operation")
|
||||||
ErrKBNotFound = errors.New("knowledge base not found")
|
ErrKBNotFound = errors.New("knowledge base not found")
|
||||||
ErrNotKBOwner = errors.New("only knowledge base owner can share")
|
ErrNotKBOwner = errors.New("only knowledge base owner can share")
|
||||||
// ErrOrgRoleCannotShare: only editors and admins in the org can share KBs to that org; viewers cannot
|
// ErrOrgRoleCannotShare: only editors and admins (in tenant's org role) may share KBs to that org; viewers cannot
|
||||||
ErrOrgRoleCannotShare = errors.New("only editors and admins can share knowledge bases to this organization")
|
ErrOrgRoleCannotShare = errors.New("only editors and admins can share knowledge bases to this organization")
|
||||||
)
|
)
|
||||||
|
|
||||||
// kbShareService implements KBShareService interface
|
// kbShareService implements KBShareService.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: permission checks resolve "is the *caller's tenant*
|
||||||
|
// in this org, with what role" rather than "is this user". The 3-D cap
|
||||||
|
// inside CheckTenantKBPermission encodes:
|
||||||
|
//
|
||||||
|
// effective = min(share.Permission, tenant_org_role, tenant_role_cap)
|
||||||
|
//
|
||||||
|
// where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless
|
||||||
|
// of what the org-level grant said. That keeps the tenant RBAC promise
|
||||||
|
// — Viewer in your own tenant cannot write — even when the access is
|
||||||
|
// routed through cross-tenant sharing.
|
||||||
type kbShareService struct {
|
type kbShareService struct {
|
||||||
shareRepo interfaces.KBShareRepository
|
shareRepo interfaces.KBShareRepository
|
||||||
orgRepo interfaces.OrganizationRepository
|
orgRepo interfaces.OrganizationRepository
|
||||||
@@ -47,22 +58,31 @@ func NewKBShareService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShareKnowledgeBase shares a knowledge base to an organization
|
// applyTenantRoleCap applies the third dimension of the cap: a caller
|
||||||
|
// whose own tenant role is Viewer cannot exceed OrgRoleViewer on any
|
||||||
|
// shared resource, regardless of what the org-level grant said. Higher
|
||||||
|
// roles (Contributor / Admin / Owner) pass through unchanged.
|
||||||
|
func applyTenantRoleCap(p types.OrgMemberRole, callerTenantRole types.TenantRole) types.OrgMemberRole {
|
||||||
|
if callerTenantRole == types.TenantRoleViewer && p.HasPermission(types.OrgRoleEditor) {
|
||||||
|
return types.OrgRoleViewer
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareKnowledgeBase shares a knowledge base to an organization.
|
||||||
|
// Caller must be in a tenant that owns the KB *and* be a member of the
|
||||||
|
// target org with at least editor role.
|
||||||
func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
||||||
logger.Infof(ctx, "Sharing knowledge base %s to organization %s", kbID, orgID)
|
logger.Infof(ctx, "Sharing knowledge base %s to organization %s", kbID, orgID)
|
||||||
|
|
||||||
// Verify knowledge base exists and user is the owner (same tenant)
|
|
||||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, ErrKBNotFound
|
return nil, ErrKBNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user's tenant owns the knowledge base
|
|
||||||
if kb.TenantID != tenantID {
|
if kb.TenantID != tenantID {
|
||||||
return nil, ErrNotKBOwner
|
return nil, ErrNotKBOwner
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify organization exists
|
|
||||||
_, err = s.orgRepo.GetByID(ctx, orgID)
|
_, err = s.orgRepo.GetByID(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||||
@@ -71,15 +91,15 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user is a member of the organization and has at least editor role (viewers cannot share KBs to the org)
|
// Caller's tenant must be an org member with editor+ role to share.
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !member.Role.HasPermission(types.OrgRoleEditor) {
|
if !tm.Role.HasPermission(types.OrgRoleEditor) {
|
||||||
return nil, ErrOrgRoleCannotShare
|
return nil, ErrOrgRoleCannotShare
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +120,6 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or
|
|||||||
|
|
||||||
if err := s.shareRepo.Create(ctx, share); err != nil {
|
if err := s.shareRepo.Create(ctx, share); err != nil {
|
||||||
if errors.Is(err, repository.ErrKBShareAlreadyExists) {
|
if errors.Is(err, repository.ErrKBShareAlreadyExists) {
|
||||||
// Update existing share
|
|
||||||
existingShare, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
existingShare, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -119,9 +138,11 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or
|
|||||||
return share, nil
|
return share, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateSharePermission updates the permission of a share.
|
// UpdateSharePermission updates a share's permission.
|
||||||
// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization.
|
// Allowed if (1) the caller is the original sharer (same user id), or
|
||||||
func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error {
|
// (2) the caller's tenant is admin in the target org. The latter lets
|
||||||
|
// org admins repair shares when the original sharer leaves.
|
||||||
|
func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string, tenantID uint64) error {
|
||||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||||
@@ -130,10 +151,9 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sharer can always update; org admin can also update (e.g. when sharer left)
|
|
||||||
if share.SharedByUserID != userID {
|
if share.SharedByUserID != userID {
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
|
||||||
if err != nil || member.Role != types.OrgRoleAdmin {
|
if err != nil || tm.Role != types.OrgRoleAdmin {
|
||||||
return ErrSharePermissionDenied
|
return ErrSharePermissionDenied
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,9 +169,8 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RemoveShare removes a share.
|
// RemoveShare removes a share.
|
||||||
// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization.
|
// Same authz envelope as UpdateSharePermission: original sharer or org admin.
|
||||||
// Org admins can unlink any KB shared to their org (e.g. content governance, sharer left).
|
func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error {
|
||||||
func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
|
|
||||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||||
@@ -160,14 +179,12 @@ func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sharer can always remove their own share
|
|
||||||
if share.SharedByUserID == userID {
|
if share.SharedByUserID == userID {
|
||||||
return s.shareRepo.Delete(ctx, shareID)
|
return s.shareRepo.Delete(ctx, shareID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Org admin can remove any share targeting their organization
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
if err == nil && tm.Role == types.OrgRoleAdmin {
|
||||||
if err == nil && member.Role == types.OrgRoleAdmin {
|
|
||||||
return s.shareRepo.Delete(ctx, shareID)
|
return s.shareRepo.Delete(ctx, shareID)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,46 +208,37 @@ func (s *kbShareService) ListSharesByOrganization(ctx context.Context, orgID str
|
|||||||
return s.shareRepo.ListByOrganization(ctx, orgID)
|
return s.shareRepo.ListByOrganization(ctx, orgID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedKnowledgeBases lists all knowledge bases shared to the user through organizations
|
// ListSharedKnowledgeBases lists all knowledge bases reachable from the
|
||||||
// It filters out knowledge bases that belong to the user's own tenant
|
// caller's tenant via cross-tenant org shares. Permission per KB is
|
||||||
// It deduplicates knowledge bases that are shared to multiple organizations the user belongs to
|
// computed via the 3-D cap.
|
||||||
func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error) {
|
func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) {
|
||||||
shares, err := s.shareRepo.ListSharedKBsForUser(ctx, userID)
|
shares, err := s.shareRepo.ListSharedKBsForTenant(ctx, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use a map to deduplicate by knowledge base ID, keeping the one with highest permission
|
|
||||||
kbInfoMap := make(map[string]*types.SharedKnowledgeBaseInfo)
|
kbInfoMap := make(map[string]*types.SharedKnowledgeBaseInfo)
|
||||||
|
|
||||||
for _, share := range shares {
|
for _, share := range shares {
|
||||||
// Skip knowledge bases that belong to the user's own tenant
|
if share.SourceTenantID == tenantID {
|
||||||
// (user already has full ownership of these)
|
|
||||||
if share.SourceTenantID == currentTenantID {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip if knowledge base is nil
|
|
||||||
if share.KnowledgeBase == nil {
|
if share.KnowledgeBase == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
kbID := share.KnowledgeBase.ID
|
kbID := share.KnowledgeBase.ID
|
||||||
|
|
||||||
// Get user's role in the organization
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue // Skip if user is not a member anymore
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Effective permission is the lower of share permission and user's org role
|
// 3-D cap: share × tenant_org_role × tenant_role_cap.
|
||||||
effectivePermission := share.Permission
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
|
|
||||||
kb := share.KnowledgeBase
|
kb := share.KnowledgeBase
|
||||||
// Calculate knowledge/chunk count based on type
|
|
||||||
switch kb.Type {
|
switch kb.Type {
|
||||||
case types.KnowledgeBaseTypeDocument:
|
case types.KnowledgeBaseTypeDocument:
|
||||||
knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
||||||
@@ -253,7 +261,7 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st
|
|||||||
ShareID: share.ID,
|
ShareID: share.ID,
|
||||||
OrganizationID: share.OrganizationID,
|
OrganizationID: share.OrganizationID,
|
||||||
OrgName: "",
|
OrgName: "",
|
||||||
Permission: effectivePermission,
|
Permission: effective,
|
||||||
SourceTenantID: share.SourceTenantID,
|
SourceTenantID: share.SourceTenantID,
|
||||||
SharedAt: share.CreatedAt,
|
SharedAt: share.CreatedAt,
|
||||||
}
|
}
|
||||||
@@ -262,25 +270,16 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st
|
|||||||
info.OrgName = share.Organization.Name
|
info.OrgName = share.Organization.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if we already have this knowledge base
|
|
||||||
existing, exists := kbInfoMap[kbID]
|
existing, exists := kbInfoMap[kbID]
|
||||||
if !exists {
|
if !exists {
|
||||||
// First time seeing this KB, add it
|
|
||||||
kbInfoMap[kbID] = info
|
kbInfoMap[kbID] = info
|
||||||
} else {
|
} else {
|
||||||
// KB already exists, keep the one with higher permission
|
if effective.HasPermission(existing.Permission) && effective != existing.Permission {
|
||||||
// Permission hierarchy: admin(3) > editor(2) > viewer(1)
|
|
||||||
// If current permission is higher than existing, replace
|
|
||||||
// This handles the case where a user belongs to multiple orgs with different permissions
|
|
||||||
if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
|
|
||||||
// Current permission is higher, replace with higher permission
|
|
||||||
kbInfoMap[kbID] = info
|
kbInfoMap[kbID] = info
|
||||||
}
|
}
|
||||||
// If existing permission is higher or equal, keep existing (no change needed)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert map to slice
|
|
||||||
result := make([]*types.SharedKnowledgeBaseInfo, 0, len(kbInfoMap))
|
result := make([]*types.SharedKnowledgeBaseInfo, 0, len(kbInfoMap))
|
||||||
for _, info := range kbInfoMap {
|
for _, info := range kbInfoMap {
|
||||||
result = append(result, info)
|
result = append(result, info)
|
||||||
@@ -289,12 +288,14 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
|
// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to
|
||||||
func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
// the given organization (including those shared from the caller's tenant) for
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
// list-page display when the user picks a space.
|
||||||
|
func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
||||||
|
tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -310,10 +311,8 @@ func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Cont
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
effectivePermission := share.Permission
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
|
|
||||||
kb := share.KnowledgeBase
|
kb := share.KnowledgeBase
|
||||||
switch kb.Type {
|
switch kb.Type {
|
||||||
@@ -337,23 +336,24 @@ func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Cont
|
|||||||
ShareID: share.ID,
|
ShareID: share.ID,
|
||||||
OrganizationID: share.OrganizationID,
|
OrganizationID: share.OrganizationID,
|
||||||
OrgName: orgName,
|
OrgName: orgName,
|
||||||
Permission: effectivePermission,
|
Permission: effective,
|
||||||
SourceTenantID: share.SourceTenantID,
|
SourceTenantID: share.SourceTenantID,
|
||||||
SharedAt: share.CreatedAt,
|
SharedAt: share.CreatedAt,
|
||||||
},
|
},
|
||||||
IsMine: share.SourceTenantID == currentTenantID,
|
IsMine: share.SourceTenantID == tenantID,
|
||||||
}
|
}
|
||||||
result = append(result, item)
|
result = append(result, item)
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch); only orgs where user is member.
|
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB
|
||||||
func (s *kbShareService) ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error) {
|
// IDs (batch); only orgs where the caller's tenant is a member.
|
||||||
|
func (s *kbShareService) ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, tenantID uint64) (map[string][]string, error) {
|
||||||
if len(orgIDs) == 0 {
|
if len(orgIDs) == 0 {
|
||||||
return make(map[string][]string), nil
|
return make(map[string][]string), nil
|
||||||
}
|
}
|
||||||
members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs)
|
members, err := s.orgRepo.ListTenantMembersByTenantForOrgs(ctx, tenantID, orgIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -401,59 +401,55 @@ func (s *kbShareService) GetShareByKBAndOrg(ctx context.Context, kbID string, or
|
|||||||
return share, nil
|
return share, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckUserKBPermission checks a user's permission for a knowledge base
|
// CheckTenantKBPermission resolves the caller's effective permission on a KB
|
||||||
// Returns: permission level, isShared, error
|
// reached via org sharing. Returns (effectiveRole, isShared, err).
|
||||||
func (s *kbShareService) CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error) {
|
//
|
||||||
// Get all shares for this knowledge base
|
// effectiveRole is the maximum role across all shares of this KB into orgs
|
||||||
|
// where the caller's tenant is a member, capped by the 3-D rule. Empty
|
||||||
|
// when isShared is false.
|
||||||
|
func (s *kbShareService) CheckTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole) (types.OrgMemberRole, bool, error) {
|
||||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var highestPermission types.OrgMemberRole
|
var highest types.OrgMemberRole
|
||||||
isShared := false
|
isShared := false
|
||||||
|
|
||||||
for _, share := range shares {
|
for _, share := range shares {
|
||||||
// Check if user is a member of the organization
|
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, callerTenantID)
|
||||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue // User is not a member of this org
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
isShared = true
|
isShared = true
|
||||||
|
|
||||||
// Effective permission is the lower of share permission and user's org role
|
effective := types.MinOrgRole(share.Permission, tm.Role)
|
||||||
effectivePermission := share.Permission
|
effective = applyTenantRoleCap(effective, callerTenantRole)
|
||||||
if !member.Role.HasPermission(share.Permission) {
|
|
||||||
effectivePermission = member.Role
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the highest permission
|
if highest == "" || effective.HasPermission(highest) {
|
||||||
if highestPermission == "" || effectivePermission.HasPermission(highestPermission) {
|
highest = effective
|
||||||
highestPermission = effectivePermission
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return highestPermission, isShared, nil
|
return highest, isShared, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// HasKBPermission checks if a user has at least the required permission level for a knowledge base
|
// HasTenantKBPermission is a thin "do I have at least N" wrapper over
|
||||||
func (s *kbShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) {
|
// CheckTenantKBPermission for callers that don't need the granular role.
|
||||||
permission, isShared, err := s.CheckUserKBPermission(ctx, kbID, userID)
|
func (s *kbShareService) HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error) {
|
||||||
|
role, isShared, err := s.CheckTenantKBPermission(ctx, kbID, callerTenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isShared {
|
if !isShared {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
return role.HasPermission(requiredRole), nil
|
||||||
return permission.HasPermission(requiredRole), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetKBSourceTenant gets the source tenant ID for a shared knowledge base
|
// GetKBSourceTenant gets the source tenant ID for a shared knowledge base
|
||||||
func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) {
|
func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) {
|
||||||
// First check if there are any shares for this KB
|
|
||||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -463,7 +459,6 @@ func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (ui
|
|||||||
return shares[0].SourceTenantID, nil
|
return shares[0].SourceTenantID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not shared, get the tenant from the knowledge base itself
|
|
||||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, ErrKBNotFound
|
return 0, ErrKBNotFound
|
||||||
|
|||||||
@@ -340,6 +340,9 @@ func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context
|
|||||||
if !ok || userID == "" {
|
if !ok || userID == "" {
|
||||||
return ownList, nil
|
return ownList, nil
|
||||||
}
|
}
|
||||||
|
// Plan 3: shared-KB permission is keyed on (tenant, tenant_role)
|
||||||
|
// rather than user. callerTenantRole drives the 3-D cap.
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
for _, id := range ids {
|
for _, id := range ids {
|
||||||
if foundSet[id] {
|
if foundSet[id] {
|
||||||
continue
|
continue
|
||||||
@@ -348,7 +351,7 @@ func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context
|
|||||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, k.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if err != nil || !hasPermission {
|
if err != nil || !hasPermission {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -496,10 +499,13 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared knowledge bases (document type only)
|
// Shared knowledge bases (document type only). Plan 3 of #1303 keys
|
||||||
|
// the share lookup on (tenantID, callerTenantRole); userID is no
|
||||||
|
// longer load-bearing for org-share access.
|
||||||
if userIDVal := ctx.Value(types.UserIDContextKey); userIDVal != nil {
|
if userIDVal := ctx.Value(types.UserIDContextKey); userIDVal != nil {
|
||||||
if userID, ok := userIDVal.(string); ok && userID != "" {
|
if userID, ok := userIDVal.(string); ok && userID != "" {
|
||||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, info := range sharedList {
|
for _, info := range sharedList {
|
||||||
if info != nil && info.KnowledgeBase != nil && info.KnowledgeBase.Type == types.KnowledgeBaseTypeDocument {
|
if info != nil && info.KnowledgeBase != nil && info.KnowledgeBase.Type == types.KnowledgeBaseTypeDocument {
|
||||||
|
|||||||
@@ -40,10 +40,11 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||||||
if userIDVal == nil {
|
if userIDVal == nil {
|
||||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||||
}
|
}
|
||||||
userID := userIDVal.(string)
|
_ = userIDVal.(string) // userID retained only for legacy log fields
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
// Check if user has at least viewer permission through organization sharing
|
// Check if the caller's tenant has at least viewer permission via org sharing.
|
||||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if err != nil || !hasPermission {
|
if err != nil || !hasPermission {
|
||||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ type fakeKBShareService struct {
|
|||||||
func (f *fakeKBShareService) ShareKnowledgeBase(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
func (f *fakeKBShareService) ShareKnowledgeBase(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string) error {
|
func (f *fakeKBShareService) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string, uint64) error {
|
||||||
return errors.New("not implemented")
|
return errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) RemoveShare(context.Context, string, string) error {
|
func (f *fakeKBShareService) RemoveShare(context.Context, string, string, uint64) error {
|
||||||
return errors.New("not implemented")
|
return errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) ListSharesByKnowledgeBase(context.Context, string, uint64) ([]*types.KnowledgeBaseShare, error) {
|
func (f *fakeKBShareService) ListSharesByKnowledgeBase(context.Context, string, uint64) ([]*types.KnowledgeBaseShare, error) {
|
||||||
@@ -33,13 +33,13 @@ func (f *fakeKBShareService) ListSharesByKnowledgeBase(context.Context, string,
|
|||||||
func (f *fakeKBShareService) ListSharesByOrganization(context.Context, string) ([]*types.KnowledgeBaseShare, error) {
|
func (f *fakeKBShareService) ListSharesByOrganization(context.Context, string) ([]*types.KnowledgeBaseShare, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) ListSharedKnowledgeBases(context.Context, string, uint64) ([]*types.SharedKnowledgeBaseInfo, error) {
|
func (f *fakeKBShareService) ListSharedKnowledgeBases(context.Context, uint64, types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) ListSharedKnowledgeBasesInOrganization(context.Context, string, string, uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
func (f *fakeKBShareService) ListSharedKnowledgeBasesInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) ListSharedKnowledgeBaseIDsByOrganizations(context.Context, []string, string) (map[string][]string, error) {
|
func (f *fakeKBShareService) ListSharedKnowledgeBaseIDsByOrganizations(context.Context, []string, uint64) (map[string][]string, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) GetShare(context.Context, string) (*types.KnowledgeBaseShare, error) {
|
func (f *fakeKBShareService) GetShare(context.Context, string) (*types.KnowledgeBaseShare, error) {
|
||||||
@@ -48,10 +48,10 @@ func (f *fakeKBShareService) GetShare(context.Context, string) (*types.Knowledge
|
|||||||
func (f *fakeKBShareService) GetShareByKBAndOrg(context.Context, string, string) (*types.KnowledgeBaseShare, error) {
|
func (f *fakeKBShareService) GetShareByKBAndOrg(context.Context, string, string) (*types.KnowledgeBaseShare, error) {
|
||||||
return nil, errors.New("not implemented")
|
return nil, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) CheckUserKBPermission(context.Context, string, string) (types.OrgMemberRole, bool, error) {
|
func (f *fakeKBShareService) CheckTenantKBPermission(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) {
|
||||||
return "", false, errors.New("not implemented")
|
return "", false, errors.New("not implemented")
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) {
|
func (f *fakeKBShareService) HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error) {
|
||||||
return f.allowedKBs[kbID], nil
|
return f.allowedKBs[kbID], nil
|
||||||
}
|
}
|
||||||
func (f *fakeKBShareService) GetKBSourceTenant(context.Context, string) (uint64, error) {
|
func (f *fakeKBShareService) GetKBSourceTenant(context.Context, string) (uint64, error) {
|
||||||
|
|||||||
@@ -55,13 +55,14 @@ func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID)
|
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID)
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
for _, id := range missingIDs {
|
for _, id := range missingIDs {
|
||||||
k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id)
|
k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id)
|
||||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id)
|
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, k.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err)
|
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err)
|
||||||
continue
|
continue
|
||||||
@@ -110,6 +111,7 @@ func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context,
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID)
|
logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID)
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing)
|
crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err)
|
logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err)
|
||||||
@@ -121,7 +123,7 @@ func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context,
|
|||||||
if c == nil || c.KnowledgeBaseID == "" {
|
if c == nil || c.KnowledgeBaseID == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, c.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, c.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err)
|
logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err)
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
// Default invite code validity in days; allowed values: 0 (never), 1, 7, 30
|
// Default invite code validity in days; allowed values: 0 (never), 1, 7, 30
|
||||||
const DefaultInviteCodeValidityDays = 7
|
const DefaultInviteCodeValidityDays = 7
|
||||||
|
|
||||||
// DefaultMemberLimit is the default max members per organization (0 = unlimited)
|
// DefaultMemberLimit is the default max tenant-members per organization (0 = unlimited)
|
||||||
const DefaultMemberLimit = 200
|
const DefaultMemberLimit = 200
|
||||||
|
|
||||||
// ValidInviteCodeValidityDays are the allowed values for invite_code_validity_days
|
// ValidInviteCodeValidityDays are the allowed values for invite_code_validity_days
|
||||||
@@ -27,9 +27,9 @@ var ValidInviteCodeValidityDays = map[int]bool{0: true, 1: true, 7: true, 30: tr
|
|||||||
var (
|
var (
|
||||||
ErrOrgNotFound = errors.New("organization not found")
|
ErrOrgNotFound = errors.New("organization not found")
|
||||||
ErrOrgPermissionDenied = errors.New("permission denied for this organization")
|
ErrOrgPermissionDenied = errors.New("permission denied for this organization")
|
||||||
ErrCannotRemoveOwner = errors.New("cannot remove organization owner")
|
ErrCannotRemoveOwner = errors.New("cannot remove organization owner tenant")
|
||||||
ErrCannotChangeOwnerRole = errors.New("cannot change organization owner role")
|
ErrCannotChangeOwnerRole = errors.New("cannot change organization owner tenant role")
|
||||||
ErrUserNotInOrg = errors.New("user is not a member of this organization")
|
ErrTenantNotInOrg = errors.New("tenant is not a member of this organization")
|
||||||
ErrInvalidRole = errors.New("invalid role")
|
ErrInvalidRole = errors.New("invalid role")
|
||||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||||
ErrInvalidValidityDays = errors.New("invite_code_validity_days must be 0, 1, 7, or 30")
|
ErrInvalidValidityDays = errors.New("invite_code_validity_days must be 0, 1, 7, or 30")
|
||||||
@@ -37,7 +37,12 @@ var (
|
|||||||
ErrOrgMemberLimitTooLow = errors.New("member limit cannot be lower than current member count")
|
ErrOrgMemberLimitTooLow = errors.New("member limit cannot be lower than current member count")
|
||||||
)
|
)
|
||||||
|
|
||||||
// organizationService implements OrganizationService interface
|
// organizationService implements OrganizationService.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: a "member" of an org is a tenant, identified by
|
||||||
|
// (org_id, tenant_id). The user_id of the requester is recorded only as
|
||||||
|
// the representative for UI/audit; permission decisions ride on the
|
||||||
|
// tenant's role inside the org.
|
||||||
type organizationService struct {
|
type organizationService struct {
|
||||||
orgRepo interfaces.OrganizationRepository
|
orgRepo interfaces.OrganizationRepository
|
||||||
userRepo interfaces.UserRepository
|
userRepo interfaces.UserRepository
|
||||||
@@ -69,9 +74,10 @@ func resolveInviteExpiry(validityDays int, now time.Time) *time.Time {
|
|||||||
return &t
|
return &t
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateOrganization creates a new organization
|
// CreateOrganization creates a new organization. The creator's tenant
|
||||||
|
// is enrolled at admin role and userID is recorded as the representative.
|
||||||
func (s *organizationService) CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) {
|
func (s *organizationService) CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) {
|
||||||
logger.Infof(ctx, "Creating organization: %s by user: %s", req.Name, userID)
|
logger.Infof(ctx, "Creating organization: %s by user: %s in tenant: %d", req.Name, userID, tenantID)
|
||||||
|
|
||||||
validityDays := DefaultInviteCodeValidityDays
|
validityDays := DefaultInviteCodeValidityDays
|
||||||
if req.InviteCodeValidityDays != nil {
|
if req.InviteCodeValidityDays != nil {
|
||||||
@@ -108,19 +114,24 @@ func (s *organizationService) CreateOrganization(ctx context.Context, userID str
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the creator as admin member
|
// Enrol the creator's tenant as admin. Owner tenant is encoded by
|
||||||
member := &types.OrganizationMember{
|
// (Organization.OwnerID points to a user, the user's tenant is the
|
||||||
ID: uuid.New().String(),
|
// owning tenant); the membership row gives that tenant the same
|
||||||
OrganizationID: org.ID,
|
// role plumbing as everyone else for join/leave/role-change UX.
|
||||||
UserID: userID,
|
joinedAt := now
|
||||||
TenantID: tenantID,
|
member := &types.OrganizationTenantMember{
|
||||||
Role: types.OrgRoleAdmin,
|
ID: uuid.New().String(),
|
||||||
CreatedAt: time.Now(),
|
OrganizationID: org.ID,
|
||||||
UpdatedAt: time.Now(),
|
TenantID: tenantID,
|
||||||
|
Role: types.OrgRoleAdmin,
|
||||||
|
RepresentativeUserID: userID,
|
||||||
|
JoinedAt: &joinedAt,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
if err := s.orgRepo.AddTenantMember(ctx, member); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to add creator as member: %v", err)
|
logger.Errorf(ctx, "Failed to add creator tenant as member: %v", err)
|
||||||
// Rollback organization creation
|
// Rollback organization creation
|
||||||
_ = s.orgRepo.Delete(ctx, org.ID)
|
_ = s.orgRepo.Delete(ctx, org.ID)
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -157,15 +168,16 @@ func (s *organizationService) GetOrganizationByInviteCode(ctx context.Context, i
|
|||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListUserOrganizations lists all organizations that a user belongs to
|
// ListTenantOrganizations lists all organizations the tenant participates in.
|
||||||
func (s *organizationService) ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error) {
|
func (s *organizationService) ListTenantOrganizations(ctx context.Context, tenantID uint64) ([]*types.Organization, error) {
|
||||||
return s.orgRepo.ListByUserID(ctx, userID)
|
return s.orgRepo.ListByTenantID(ctx, tenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateOrganization updates an organization
|
// UpdateOrganization updates an organization. Operator's tenant must be
|
||||||
func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error) {
|
// admin in this org; the operator user identity is logged for audit but
|
||||||
// Check if user is admin
|
// not used as the permission key.
|
||||||
isAdmin, err := s.IsOrgAdmin(ctx, id, userID)
|
func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, tenantID uint64, req *types.UpdateOrganizationRequest) (*types.Organization, error) {
|
||||||
|
isAdmin, err := s.IsTenantOrgAdmin(ctx, id, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -204,7 +216,7 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
|
|||||||
return nil, errors.New("member_limit must be >= 0")
|
return nil, errors.New("member_limit must be >= 0")
|
||||||
}
|
}
|
||||||
if *req.MemberLimit > 0 {
|
if *req.MemberLimit > 0 {
|
||||||
count, err := s.orgRepo.CountMembers(ctx, id)
|
count, err := s.orgRepo.CountTenantMembers(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -216,6 +228,7 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
|
|||||||
}
|
}
|
||||||
org.UpdatedAt = time.Now()
|
org.UpdatedAt = time.Now()
|
||||||
|
|
||||||
|
_ = userID // recorded by the caller for audit; not used here
|
||||||
if err := s.orgRepo.Update(ctx, org); err != nil {
|
if err := s.orgRepo.Update(ctx, org); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -223,8 +236,9 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
|
|||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SearchSearchableOrganizations returns searchable (discoverable) organizations for the current user
|
// SearchSearchableOrganizations returns searchable (discoverable) organizations
|
||||||
func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) {
|
// keyed on the caller's tenant — IsAlreadyMember reflects tenant-level membership.
|
||||||
|
func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, tenantID uint64, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) {
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
limit = 20
|
limit = 20
|
||||||
}
|
}
|
||||||
@@ -237,7 +251,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
|
|||||||
agentShareCounts := make(map[string]int)
|
agentShareCounts := make(map[string]int)
|
||||||
memberOrgIDs := make(map[string]bool)
|
memberOrgIDs := make(map[string]bool)
|
||||||
for _, org := range orgs {
|
for _, org := range orgs {
|
||||||
if mc, err := s.orgRepo.CountMembers(ctx, org.ID); err == nil {
|
if mc, err := s.orgRepo.CountTenantMembers(ctx, org.ID); err == nil {
|
||||||
memberCounts[org.ID] = mc
|
memberCounts[org.ID] = mc
|
||||||
}
|
}
|
||||||
shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID)
|
shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID)
|
||||||
@@ -245,7 +259,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
|
|||||||
if agentShares, err := s.agentShareRepo.ListByOrganization(ctx, org.ID); err == nil {
|
if agentShares, err := s.agentShareRepo.ListByOrganization(ctx, org.ID); err == nil {
|
||||||
agentShareCounts[org.ID] = len(agentShares)
|
agentShareCounts[org.ID] = len(agentShares)
|
||||||
}
|
}
|
||||||
_, err := s.orgRepo.GetMember(ctx, org.ID, userID)
|
_, err := s.orgRepo.GetTenantMember(ctx, org.ID, tenantID)
|
||||||
memberOrgIDs[org.ID] = (err == nil)
|
memberOrgIDs[org.ID] = (err == nil)
|
||||||
}
|
}
|
||||||
items := make([]types.SearchableOrganizationItem, 0, len(orgs))
|
items := make([]types.SearchableOrganizationItem, 0, len(orgs))
|
||||||
@@ -269,7 +283,9 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// JoinByOrganizationID joins a searchable organization by ID (no invite code required)
|
// JoinByOrganizationID joins a searchable organization by ID (no invite
|
||||||
|
// code required). Plan 3: the *tenant* joins, with the calling user as
|
||||||
|
// representative.
|
||||||
func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error) {
|
func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error) {
|
||||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -279,17 +295,15 @@ func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID st
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !org.Searchable {
|
if !org.Searchable {
|
||||||
return nil, ErrOrgPermissionDenied // or a dedicated "org not discoverable" error
|
return nil, ErrOrgPermissionDenied
|
||||||
}
|
}
|
||||||
_, err = s.orgRepo.GetMember(ctx, orgID, userID)
|
_, err = s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return org, nil // already member
|
return org, nil // tenant already member; idempotent
|
||||||
}
|
}
|
||||||
// Validate requested role if provided
|
|
||||||
if requestedRole != "" && !requestedRole.IsValid() {
|
if requestedRole != "" && !requestedRole.IsValid() {
|
||||||
return nil, ErrInvalidRole
|
return nil, ErrInvalidRole
|
||||||
}
|
}
|
||||||
// Default to viewer if not specified
|
|
||||||
if requestedRole == "" {
|
if requestedRole == "" {
|
||||||
requestedRole = types.OrgRoleViewer
|
requestedRole = types.OrgRoleViewer
|
||||||
}
|
}
|
||||||
@@ -300,27 +314,28 @@ func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID st
|
|||||||
}
|
}
|
||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
// Searchable direct join: do not validate invite code or expiry (product copy: no invite code required).
|
|
||||||
if err := s.joinAsViewerWithChecks(ctx, org, userID, tenantID); err != nil {
|
if err := s.joinAsViewerWithChecks(ctx, org, userID, tenantID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
logger.Infof(ctx, "User %s joined organization %s via searchable join", userID, org.ID)
|
logger.Infof(ctx, "Tenant %d joined organization %s via searchable join (rep user %s)", tenantID, org.ID, userID)
|
||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteOrganization deletes an organization
|
// DeleteOrganization deletes an organization. Only the owner user may delete.
|
||||||
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error {
|
// (We keep the user-level check here intentionally — Org ownership is
|
||||||
|
// product-defined as the user who created it, not the tenant they were
|
||||||
|
// in at the time.)
|
||||||
|
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string, tenantID uint64) error {
|
||||||
org, err := s.orgRepo.GetByID(ctx, id)
|
org, err := s.orgRepo.GetByID(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only owner can delete organization
|
|
||||||
if org.OwnerID != userID {
|
if org.OwnerID != userID {
|
||||||
return ErrOrgPermissionDenied
|
return ErrOrgPermissionDenied
|
||||||
}
|
}
|
||||||
|
_ = tenantID // accepted for handler symmetry; not part of the gate
|
||||||
|
|
||||||
// Remove all KB shares for this org so members no longer see associated knowledge bases
|
|
||||||
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
|
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
|
||||||
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
|
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
|
||||||
}
|
}
|
||||||
@@ -331,8 +346,8 @@ func (s *organizationService) DeleteOrganization(ctx context.Context, id string,
|
|||||||
return s.orgRepo.Delete(ctx, id)
|
return s.orgRepo.Delete(ctx, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMember adds a member to an organization
|
// AddTenantMember enrols a tenant as a member of an organization.
|
||||||
func (s *organizationService) AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error {
|
func (s *organizationService) AddTenantMember(ctx context.Context, orgID string, tenantID uint64, representativeUserID string, role types.OrgMemberRole) error {
|
||||||
if !role.IsValid() {
|
if !role.IsValid() {
|
||||||
return ErrInvalidRole
|
return ErrInvalidRole
|
||||||
}
|
}
|
||||||
@@ -342,7 +357,7 @@ func (s *organizationService) AddMember(ctx context.Context, orgID string, userI
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if org.MemberLimit > 0 {
|
if org.MemberLimit > 0 {
|
||||||
count, errCount := s.orgRepo.CountMembers(ctx, orgID)
|
count, errCount := s.orgRepo.CountTenantMembers(ctx, orgID)
|
||||||
if errCount != nil {
|
if errCount != nil {
|
||||||
return errCount
|
return errCount
|
||||||
}
|
}
|
||||||
@@ -351,57 +366,60 @@ func (s *organizationService) AddMember(ctx context.Context, orgID string, userI
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
member := &types.OrganizationMember{
|
now := time.Now()
|
||||||
ID: uuid.New().String(),
|
member := &types.OrganizationTenantMember{
|
||||||
OrganizationID: orgID,
|
ID: uuid.New().String(),
|
||||||
UserID: userID,
|
OrganizationID: orgID,
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
Role: role,
|
Role: role,
|
||||||
CreatedAt: time.Now(),
|
RepresentativeUserID: representativeUserID,
|
||||||
UpdatedAt: time.Now(),
|
JoinedAt: &now,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.orgRepo.AddMember(ctx, member)
|
return s.orgRepo.AddTenantMember(ctx, member)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveMember removes a member from an organization.
|
// RemoveTenantMember removes a tenant from an organization.
|
||||||
// When operatorUserID == memberUserID, it is "leave" (self-removal) and does not require admin.
|
// When operatorTenantID == memberTenantID, it's "leave" (self-removal).
|
||||||
// When removing another member, operator must be admin.
|
// Otherwise the operator's tenant must be admin in the org.
|
||||||
func (s *organizationService) RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error {
|
func (s *organizationService) RemoveTenantMember(ctx context.Context, orgID string, memberTenantID uint64, operatorUserID string, operatorTenantID uint64) error {
|
||||||
// Check if trying to remove owner
|
|
||||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if org.OwnerID == memberUserID {
|
// Owner-tenant resolution: derive owner tenant from Organization.OwnerID's
|
||||||
|
// own tenant. If the OwnerID-user has been deleted (very rare during the
|
||||||
|
// org's lifetime) we fall through and refuse the destructive action.
|
||||||
|
if isOwnerTenant, err := s.isOwnerTenant(ctx, org, memberTenantID); err == nil && isOwnerTenant {
|
||||||
return ErrCannotRemoveOwner
|
return ErrCannotRemoveOwner
|
||||||
}
|
}
|
||||||
|
|
||||||
// Self-removal (leave): allow any member to leave
|
if operatorTenantID == memberTenantID {
|
||||||
if operatorUserID == memberUserID {
|
// Self-removal: any tenant can leave on their own behalf.
|
||||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Removing another member: require operator to be admin
|
isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID)
|
||||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !isAdmin {
|
if !isAdmin {
|
||||||
return ErrOrgPermissionDenied
|
return ErrOrgPermissionDenied
|
||||||
}
|
}
|
||||||
|
_ = operatorUserID
|
||||||
|
|
||||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateMemberRole updates a member's role
|
// UpdateTenantMemberRole updates the role for a (org, tenant) membership.
|
||||||
func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error {
|
func (s *organizationService) UpdateTenantMemberRole(ctx context.Context, orgID string, memberTenantID uint64, role types.OrgMemberRole, operatorUserID string, operatorTenantID uint64) error {
|
||||||
if !role.IsValid() {
|
if !role.IsValid() {
|
||||||
return ErrInvalidRole
|
return ErrInvalidRole
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if operator is admin
|
isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID)
|
||||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -409,39 +427,39 @@ func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string
|
|||||||
return ErrOrgPermissionDenied
|
return ErrOrgPermissionDenied
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if trying to change owner's role
|
|
||||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if org.OwnerID == memberUserID {
|
if isOwnerTenant, err := s.isOwnerTenant(ctx, org, memberTenantID); err == nil && isOwnerTenant {
|
||||||
return ErrCannotChangeOwnerRole
|
return ErrCannotChangeOwnerRole
|
||||||
}
|
}
|
||||||
|
_ = operatorUserID
|
||||||
|
|
||||||
return s.orgRepo.UpdateMemberRole(ctx, orgID, memberUserID, role)
|
return s.orgRepo.UpdateTenantMemberRole(ctx, orgID, memberTenantID, role)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMembers lists all members of an organization
|
// ListTenantMembers lists all tenant memberships for an organization.
|
||||||
func (s *organizationService) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
func (s *organizationService) ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) {
|
||||||
return s.orgRepo.ListMembers(ctx, orgID)
|
return s.orgRepo.ListTenantMembers(ctx, orgID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMember gets a specific member of an organization
|
// GetTenantMember returns the (org, tenant) membership row.
|
||||||
func (s *organizationService) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
func (s *organizationService) GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) {
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return member, nil
|
return member, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerateInviteCode generates a new invite code for an organization
|
// GenerateInviteCode generates a new invite code for an organization.
|
||||||
func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error) {
|
// Operator's tenant must be admin in the org.
|
||||||
// Check if user is admin
|
func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string, tenantID uint64) (string, error) {
|
||||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, userID)
|
isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -458,7 +476,6 @@ func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID stri
|
|||||||
if validityDays != 0 && !ValidInviteCodeValidityDays[validityDays] {
|
if validityDays != 0 && !ValidInviteCodeValidityDays[validityDays] {
|
||||||
validityDays = DefaultInviteCodeValidityDays
|
validityDays = DefaultInviteCodeValidityDays
|
||||||
}
|
}
|
||||||
// 0 = never expire (expiresAt nil); 1/7/30 = that many days
|
|
||||||
|
|
||||||
inviteCode := generateInviteCode()
|
inviteCode := generateInviteCode()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
@@ -466,13 +483,16 @@ func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID stri
|
|||||||
if err := s.orgRepo.UpdateInviteCode(ctx, orgID, inviteCode, expiresAt); err != nil {
|
if err := s.orgRepo.UpdateInviteCode(ctx, orgID, inviteCode, expiresAt); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
|
||||||
return inviteCode, nil
|
return inviteCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// joinAsViewerWithChecks adds the user as viewer when not already a member (enforces member limit).
|
// joinAsViewerWithChecks adds the tenant as viewer when not already a
|
||||||
func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *types.Organization, userID string, tenantID uint64) error {
|
// member (enforces member limit). representativeUserID is the user
|
||||||
_, err := s.orgRepo.GetMember(ctx, org.ID, userID)
|
// kicking off the join; recorded for audit only.
|
||||||
|
func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *types.Organization, representativeUserID string, tenantID uint64) error {
|
||||||
|
_, err := s.orgRepo.GetTenantMember(ctx, org.ID, tenantID)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -481,7 +501,7 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t
|
|||||||
}
|
}
|
||||||
|
|
||||||
if org.MemberLimit > 0 {
|
if org.MemberLimit > 0 {
|
||||||
count, errCount := s.orgRepo.CountMembers(ctx, org.ID)
|
count, errCount := s.orgRepo.CountTenantMembers(ctx, org.ID)
|
||||||
if errCount != nil {
|
if errCount != nil {
|
||||||
return errCount
|
return errCount
|
||||||
}
|
}
|
||||||
@@ -490,20 +510,22 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
member := &types.OrganizationMember{
|
now := time.Now()
|
||||||
ID: uuid.New().String(),
|
member := &types.OrganizationTenantMember{
|
||||||
OrganizationID: org.ID,
|
ID: uuid.New().String(),
|
||||||
UserID: userID,
|
OrganizationID: org.ID,
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
Role: types.OrgRoleViewer,
|
Role: types.OrgRoleViewer,
|
||||||
CreatedAt: time.Now(),
|
RepresentativeUserID: representativeUserID,
|
||||||
UpdatedAt: time.Now(),
|
JoinedAt: &now,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.orgRepo.AddMember(ctx, member)
|
return s.orgRepo.AddTenantMember(ctx, member)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JoinByInviteCode allows a user to join an organization via invite code
|
// JoinByInviteCode allows a tenant to join via invite code.
|
||||||
func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) {
|
func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) {
|
||||||
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -516,7 +538,6 @@ func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode s
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if the organization need approval
|
|
||||||
if org.RequireApproval {
|
if org.RequireApproval {
|
||||||
logger.Infof(ctx, "Organization %s requires approval", org.ID)
|
logger.Infof(ctx, "Organization %s requires approval", org.ID)
|
||||||
return nil, ErrOrgPermissionDenied
|
return nil, ErrOrgPermissionDenied
|
||||||
@@ -526,13 +547,13 @@ func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode s
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "User %s joined organization %s via invite code", userID, org.ID)
|
logger.Infof(ctx, "Tenant %d joined organization %s via invite code (rep user %s)", tenantID, org.ID, userID)
|
||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsOrgAdmin checks if a user is an admin of an organization
|
// IsTenantOrgAdmin reports whether the tenant has admin role in the org.
|
||||||
func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error) {
|
func (s *organizationService) IsTenantOrgAdmin(ctx context.Context, orgID string, tenantID uint64) (bool, error) {
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return false, nil
|
return false, nil
|
||||||
@@ -542,18 +563,33 @@ func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, user
|
|||||||
return member.Role == types.OrgRoleAdmin, nil
|
return member.Role == types.OrgRoleAdmin, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUserRoleInOrg gets a user's role in an organization
|
// GetTenantRoleInOrg gets a tenant's role in an organization.
|
||||||
func (s *organizationService) GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error) {
|
func (s *organizationService) GetTenantRoleInOrg(ctx context.Context, orgID string, tenantID uint64) (types.OrgMemberRole, error) {
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return "", ErrUserNotInOrg
|
return "", ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return member.Role, nil
|
return member.Role, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isOwnerTenant returns true when the given tenant is the home tenant of
|
||||||
|
// org.OwnerID. The owner tenant is undeletable / unchangeable in the
|
||||||
|
// org membership table — that lets us preserve the "owner can never be
|
||||||
|
// orphaned" invariant without adding a separate column.
|
||||||
|
func (s *organizationService) isOwnerTenant(ctx context.Context, org *types.Organization, tenantID uint64) (bool, error) {
|
||||||
|
if s.userRepo == nil || org == nil {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
owner, err := s.userRepo.GetUserByID(ctx, org.OwnerID)
|
||||||
|
if err != nil || owner == nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return owner.TenantID == tenantID, nil
|
||||||
|
}
|
||||||
|
|
||||||
// generateInviteCode generates a random 16-character invite code
|
// generateInviteCode generates a random 16-character invite code
|
||||||
func generateInviteCode() string {
|
func generateInviteCode() string {
|
||||||
bytes := make([]byte, 8)
|
bytes := make([]byte, 8)
|
||||||
@@ -569,20 +605,20 @@ var (
|
|||||||
ErrPendingRequestExists = errors.New("pending request already exists")
|
ErrPendingRequestExists = errors.New("pending request already exists")
|
||||||
ErrJoinRequestNotFound = errors.New("join request not found")
|
ErrJoinRequestNotFound = errors.New("join request not found")
|
||||||
ErrCannotUpgradeToSameRole = errors.New("cannot request upgrade to same or lower role")
|
ErrCannotUpgradeToSameRole = errors.New("cannot request upgrade to same or lower role")
|
||||||
ErrAlreadyAdmin = errors.New("user is already an admin")
|
ErrAlreadyAdmin = errors.New("tenant is already an admin")
|
||||||
)
|
)
|
||||||
|
|
||||||
// SubmitJoinRequest submits a request to join an organization
|
// SubmitJoinRequest submits a request for the caller's tenant to join an organization.
|
||||||
|
// Dedup is now per-tenant: any user from a tenant already with a pending join
|
||||||
|
// request is rejected (the same tenant can't queue two simultaneous joins).
|
||||||
func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) {
|
func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) {
|
||||||
logger.Infof(ctx, "User %s submitting join request for organization %s", userID, orgID)
|
logger.Infof(ctx, "Tenant %d (rep user %s) submitting join request for organization %s", tenantID, userID, orgID)
|
||||||
|
|
||||||
// Check if there's already a pending join request
|
existing, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeJoin)
|
||||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeJoin)
|
|
||||||
if err == nil && existing != nil {
|
if err == nil && existing != nil {
|
||||||
return nil, ErrPendingRequestExists
|
return nil, ErrPendingRequestExists
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reject if organization is already at member limit
|
|
||||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||||
@@ -591,7 +627,7 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if org.MemberLimit > 0 {
|
if org.MemberLimit > 0 {
|
||||||
count, errCount := s.orgRepo.CountMembers(ctx, orgID)
|
count, errCount := s.orgRepo.CountTenantMembers(ctx, orgID)
|
||||||
if errCount != nil {
|
if errCount != nil {
|
||||||
return nil, errCount
|
return nil, errCount
|
||||||
}
|
}
|
||||||
@@ -600,7 +636,6 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default to viewer if role is empty or invalid
|
|
||||||
if requestedRole == "" || !requestedRole.IsValid() {
|
if requestedRole == "" || !requestedRole.IsValid() {
|
||||||
requestedRole = types.OrgRoleViewer
|
requestedRole = types.OrgRoleViewer
|
||||||
}
|
}
|
||||||
@@ -622,7 +657,7 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "Join request %s created for organization %s by user %s", request.ID, orgID, userID)
|
logger.Infof(ctx, "Join request %s created for organization %s by tenant %d", request.ID, orgID, tenantID)
|
||||||
return request, nil
|
return request, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,8 +672,9 @@ func (s *organizationService) CountPendingJoinRequests(ctx context.Context, orgI
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ReviewJoinRequest reviews a join request or upgrade request (approve or reject).
|
// ReviewJoinRequest reviews a join request or upgrade request (approve or reject).
|
||||||
// When approving, assignRole overrides the applicant's requested role if set; otherwise uses request.RequestedRole or viewer.
|
// On approve the targeted tenant gets the assigned role; reviewerTenantID is
|
||||||
func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error {
|
// only used for audit (the gate is the route-level Admin guard).
|
||||||
|
func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, reviewerTenantID uint64, message string, assignRole *types.OrgMemberRole) error {
|
||||||
request, err := s.orgRepo.GetJoinRequestByID(ctx, requestID)
|
request, err := s.orgRepo.GetJoinRequestByID(ctx, requestID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ErrJoinRequestNotFound
|
return ErrJoinRequestNotFound
|
||||||
@@ -655,7 +691,6 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin
|
|||||||
if approved {
|
if approved {
|
||||||
status = types.JoinRequestStatusApproved
|
status = types.JoinRequestStatusApproved
|
||||||
|
|
||||||
// Role to assign: admin override > applicant's requested role > viewer
|
|
||||||
role := types.OrgRoleViewer
|
role := types.OrgRoleViewer
|
||||||
if assignRole != nil && assignRole.IsValid() {
|
if assignRole != nil && assignRole.IsValid() {
|
||||||
role = *assignRole
|
role = *assignRole
|
||||||
@@ -663,21 +698,18 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin
|
|||||||
role = request.RequestedRole
|
role = request.RequestedRole
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle based on request type
|
|
||||||
if request.RequestType == types.JoinRequestTypeUpgrade {
|
if request.RequestType == types.JoinRequestTypeUpgrade {
|
||||||
// Upgrade: update existing member's role
|
if err := s.orgRepo.UpdateTenantMemberRole(ctx, request.OrganizationID, request.TenantID, role); err != nil {
|
||||||
if err := s.orgRepo.UpdateMemberRole(ctx, request.OrganizationID, request.UserID, role); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
logger.Infof(ctx, "Upgrade request %s approved, user %s role updated to %s in organization %s", requestID, request.UserID, role, request.OrganizationID)
|
logger.Infof(ctx, "Upgrade request %s approved, tenant %d role updated to %s in organization %s", requestID, request.TenantID, role, request.OrganizationID)
|
||||||
} else {
|
} else {
|
||||||
// Join: check member limit then add new member
|
|
||||||
org, errOrg := s.orgRepo.GetByID(ctx, request.OrganizationID)
|
org, errOrg := s.orgRepo.GetByID(ctx, request.OrganizationID)
|
||||||
if errOrg != nil {
|
if errOrg != nil {
|
||||||
return errOrg
|
return errOrg
|
||||||
}
|
}
|
||||||
if org.MemberLimit > 0 {
|
if org.MemberLimit > 0 {
|
||||||
count, errCount := s.orgRepo.CountMembers(ctx, request.OrganizationID)
|
count, errCount := s.orgRepo.CountTenantMembers(ctx, request.OrganizationID)
|
||||||
if errCount != nil {
|
if errCount != nil {
|
||||||
return errCount
|
return errCount
|
||||||
}
|
}
|
||||||
@@ -685,58 +717,56 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin
|
|||||||
return ErrOrgMemberLimitReached
|
return ErrOrgMemberLimitReached
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
member := &types.OrganizationMember{
|
now := time.Now()
|
||||||
ID: uuid.New().String(),
|
member := &types.OrganizationTenantMember{
|
||||||
OrganizationID: request.OrganizationID,
|
ID: uuid.New().String(),
|
||||||
UserID: request.UserID,
|
OrganizationID: request.OrganizationID,
|
||||||
TenantID: request.TenantID,
|
TenantID: request.TenantID,
|
||||||
Role: role,
|
Role: role,
|
||||||
CreatedAt: time.Now(),
|
RepresentativeUserID: request.UserID,
|
||||||
UpdatedAt: time.Now(),
|
JoinedAt: &now,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
}
|
}
|
||||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
if err := s.orgRepo.AddTenantMember(ctx, member); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
logger.Infof(ctx, "Join request %s approved, user %s added to organization %s with role %s", requestID, request.UserID, request.OrganizationID, role)
|
logger.Infof(ctx, "Join request %s approved, tenant %d added to organization %s with role %s", requestID, request.TenantID, request.OrganizationID, role)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
status = types.JoinRequestStatusRejected
|
status = types.JoinRequestStatusRejected
|
||||||
logger.Infof(ctx, "Request %s rejected for user %s", requestID, request.UserID)
|
logger.Infof(ctx, "Request %s rejected for tenant %d", requestID, request.TenantID)
|
||||||
}
|
}
|
||||||
|
_ = reviewerTenantID
|
||||||
|
|
||||||
return s.orgRepo.UpdateJoinRequestStatus(ctx, requestID, status, reviewerID, message)
|
return s.orgRepo.UpdateJoinRequestStatus(ctx, requestID, status, reviewerID, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RequestRoleUpgrade submits a request to upgrade role in an organization
|
// RequestRoleUpgrade submits a request to upgrade the caller's tenant's role.
|
||||||
func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) {
|
func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) {
|
||||||
logger.Infof(ctx, "User %s submitting role upgrade request for organization %s to role %s", userID, orgID, requestedRole)
|
logger.Infof(ctx, "Tenant %d (rep user %s) requesting role upgrade for organization %s to role %s", tenantID, userID, orgID, requestedRole)
|
||||||
|
|
||||||
// Check if user is a member
|
member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID)
|
||||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||||
return nil, ErrUserNotInOrg
|
return nil, ErrTenantNotInOrg
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate the requested role
|
|
||||||
if !requestedRole.IsValid() {
|
if !requestedRole.IsValid() {
|
||||||
return nil, ErrInvalidRole
|
return nil, ErrInvalidRole
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if already admin
|
|
||||||
if member.Role == types.OrgRoleAdmin {
|
if member.Role == types.OrgRoleAdmin {
|
||||||
return nil, ErrAlreadyAdmin
|
return nil, ErrAlreadyAdmin
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if requested role is higher than current role
|
|
||||||
if !requestedRole.HasPermission(member.Role) || requestedRole == member.Role {
|
if !requestedRole.HasPermission(member.Role) || requestedRole == member.Role {
|
||||||
return nil, ErrCannotUpgradeToSameRole
|
return nil, ErrCannotUpgradeToSameRole
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if there's already a pending upgrade request
|
existing, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeUpgrade)
|
||||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
|
||||||
if err == nil && existing != nil {
|
if err == nil && existing != nil {
|
||||||
return nil, ErrPendingRequestExists
|
return nil, ErrPendingRequestExists
|
||||||
}
|
}
|
||||||
@@ -759,13 +789,13 @@ func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID stri
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "Role upgrade request %s created for organization %s by user %s (from %s to %s)", request.ID, orgID, userID, member.Role, requestedRole)
|
logger.Infof(ctx, "Role upgrade request %s created for organization %s by tenant %d (from %s to %s)", request.ID, orgID, tenantID, member.Role, requestedRole)
|
||||||
return request, nil
|
return request, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPendingUpgradeRequest gets a pending upgrade request for a user in an organization
|
// GetPendingUpgradeRequest gets a pending upgrade request for a tenant in an organization
|
||||||
func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) {
|
||||||
request, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
request, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeUpgrade)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, repository.ErrJoinRequestNotFound) {
|
if errors.Is(err, repository.ErrJoinRequestNotFound) {
|
||||||
return nil, ErrJoinRequestNotFound
|
return nil, ErrJoinRequestNotFound
|
||||||
|
|||||||
@@ -389,7 +389,8 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
|||||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||||
if userIDVal != nil {
|
if userIDVal != nil {
|
||||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||||
} else {
|
} else {
|
||||||
@@ -455,6 +456,7 @@ func (s *sessionService) buildSearchTargets(
|
|||||||
fullKBSet := make(map[string]bool)
|
fullKBSet := make(map[string]bool)
|
||||||
|
|
||||||
// First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller)
|
// First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller)
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
if len(knowledgeBaseIDs) > 0 {
|
if len(knowledgeBaseIDs) > 0 {
|
||||||
kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs)
|
kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs)
|
||||||
kbByID := make(map[string]*types.KnowledgeBase, len(kbs))
|
kbByID := make(map[string]*types.KnowledgeBase, len(kbs))
|
||||||
@@ -472,7 +474,7 @@ func (s *sessionService) buildSearchTargets(
|
|||||||
} else if kb.TenantID == tenantID {
|
} else if kb.TenantID == tenantID {
|
||||||
kbTenantMap[kbID] = tenantID
|
kbTenantMap[kbID] = tenantID
|
||||||
} else if s.kbShareService != nil && userID != "" {
|
} else if s.kbShareService != nil && userID != "" {
|
||||||
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
hasAccess, _ := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if hasAccess {
|
if hasAccess {
|
||||||
kbTenantMap[kbID] = kb.TenantID
|
kbTenantMap[kbID] = kb.TenantID
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -84,10 +84,11 @@ func (s *knowledgeTagService) ListTags(
|
|||||||
if userIDVal == nil {
|
if userIDVal == nil {
|
||||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||||
}
|
}
|
||||||
userID := userIDVal.(string)
|
_ = userIDVal.(string)
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
// Check if user has at least viewer permission through organization sharing
|
// Check whether the caller's tenant has at least viewer permission via org sharing.
|
||||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||||
if err != nil || !hasPermission {
|
if err != nil || !hasPermission {
|
||||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri
|
|||||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||||
}
|
}
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -46,7 +47,7 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri
|
|||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||||
}
|
}
|
||||||
if h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, knowledge.KnowledgeBaseID, tenantID, callerTenantRole)
|
||||||
if permErr == nil && isShared {
|
if permErr == nil && isShared {
|
||||||
if !permission.HasPermission(requiredPermission) {
|
if !permission.HasPermission(requiredPermission) {
|
||||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||||
@@ -56,11 +57,12 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri
|
|||||||
}
|
}
|
||||||
if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
|
if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
|
||||||
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kbRef)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-7
@@ -47,6 +47,7 @@ func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPerm
|
|||||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||||
}
|
}
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
kbID = secutils.SanitizeForLog(kbID)
|
kbID = secutils.SanitizeForLog(kbID)
|
||||||
if kbID == "" {
|
if kbID == "" {
|
||||||
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||||
@@ -67,24 +68,26 @@ func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPerm
|
|||||||
if kb.TenantID == tenantID {
|
if kb.TenantID == tenantID {
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||||
}
|
}
|
||||||
if userExists && h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole)
|
||||||
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
|
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
|
||||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||||
if srcErr == nil {
|
if srcErr == nil {
|
||||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d",
|
||||||
userID.(string), kbID, permission, sourceTenantID)
|
tenantID, kbID, permission, sourceTenantID)
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if requiredPermission == types.OrgRoleViewer && userExists && h.agentShareService != nil {
|
if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID)
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
_ = userExists
|
||||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k
|
|||||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||||
}
|
}
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
kbID = secutils.SanitizeForLog(kbID)
|
kbID = secutils.SanitizeForLog(kbID)
|
||||||
if kbID == "" {
|
if kbID == "" {
|
||||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||||
@@ -89,24 +90,26 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k
|
|||||||
if kb.TenantID == tenantID {
|
if kb.TenantID == tenantID {
|
||||||
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
||||||
}
|
}
|
||||||
if userExists && h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole)
|
||||||
if permErr == nil && isShared {
|
if permErr == nil && isShared {
|
||||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||||
if srcErr == nil {
|
if srcErr == nil {
|
||||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d",
|
||||||
userID.(string), kbID, permission, sourceTenantID)
|
tenantID, kbID, permission, sourceTenantID)
|
||||||
return kb, kbID, sourceTenantID, permission, nil
|
return kb, kbID, sourceTenantID, permission, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if userExists && h.agentShareService != nil {
|
if h.agentShareService != nil {
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID)
|
||||||
return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
|
return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
_ = userExists
|
||||||
logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID)
|
logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID)
|
||||||
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||||
}
|
}
|
||||||
@@ -120,6 +123,7 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
|||||||
return nil, ctx, errors.NewUnauthorizedError("Unauthorized")
|
return nil, ctx, errors.NewUnauthorizedError("Unauthorized")
|
||||||
}
|
}
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -132,18 +136,18 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Shared KB: check organization permission
|
// Shared KB: check organization permission
|
||||||
if userExists && h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, knowledge.KnowledgeBaseID, tenantID, callerTenantRole)
|
||||||
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
|
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
|
||||||
effectiveTenantID := knowledge.TenantID
|
effectiveTenantID := knowledge.TenantID
|
||||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
|
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Shared agent: request passes agent_id, or user has any shared agent that can access this KB
|
// Shared agent: request passes agent_id, or user has any shared agent that can access this KB
|
||||||
if userExists && h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
|
if h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
|
||||||
agentID := c.Query("agent_id")
|
agentID := c.Query("agent_id")
|
||||||
if agentID != "" {
|
if agentID != "" {
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), tenantID, agentID)
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, tenantID, callerTenantRole, agentID)
|
||||||
if err == nil && agent != nil {
|
if err == nil && agent != nil {
|
||||||
if knowledge.TenantID != agent.TenantID {
|
if knowledge.TenantID != agent.TenantID {
|
||||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||||
@@ -166,12 +170,14 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kbRef)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
_ = userExists
|
||||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1083,12 +1089,14 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
|
||||||
if err != nil || agent == nil {
|
if err != nil || agent == nil {
|
||||||
logger.Warnf(ctx, "GetKnowledgeBatch: invalid or inaccessible shared agent %s: %v", agentID, err)
|
logger.Warnf(ctx, "GetKnowledgeBatch: invalid or inaccessible shared agent %s: %v", agentID, err)
|
||||||
c.Error(errors.NewForbiddenError("Invalid or inaccessible shared agent").WithDetails(err.Error()))
|
c.Error(errors.NewForbiddenError("Invalid or inaccessible shared agent").WithDetails(err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
effectiveTenantID = agent.TenantID
|
effectiveTenantID = agent.TenantID
|
||||||
agentAllowedKBIDs = resolveAgentAllowedKBIDs(agent)
|
agentAllowedKBIDs = resolveAgentAllowedKBIDs(agent)
|
||||||
|
|
||||||
@@ -1509,13 +1517,14 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
|||||||
c.Error(errors.NewUnauthorizedError("user ID not found"))
|
c.Error(errors.NewUnauthorizedError("user ID not found"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
userID, _ := userIDVal.(string)
|
_ = userIDVal
|
||||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
if currentTenantID == 0 {
|
if currentTenantID == 0 {
|
||||||
c.Error(errors.NewUnauthorizedError("tenant ID not found"))
|
c.Error(errors.NewUnauthorizedError("tenant ID not found"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if goerrors.Is(err, service.ErrAgentShareNotFound) || goerrors.Is(err, service.ErrAgentSharePermission) || goerrors.Is(err, service.ErrAgentNotFoundForShare) {
|
if goerrors.Is(err, service.ErrAgentShareNotFound) || goerrors.Is(err, service.ErrAgentSharePermission) || goerrors.Is(err, service.ErrAgentNotFoundForShare) {
|
||||||
c.Error(errors.NewForbiddenError("no permission for this shared agent"))
|
c.Error(errors.NewForbiddenError("no permission for this shared agent"))
|
||||||
|
|||||||
@@ -270,6 +270,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||||||
|
|
||||||
// Get user ID from context (needed for shared KB permission check)
|
// Get user ID from context (needed for shared KB permission check)
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
// Get knowledge base ID from URL parameter
|
// Get knowledge base ID from URL parameter
|
||||||
id := secutils.SanitizeForLog(c.Param("id"))
|
id := secutils.SanitizeForLog(c.Param("id"))
|
||||||
@@ -299,26 +300,26 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check 2: If not owner, check organization shared access
|
// Check 2: If not owner, check organization shared access
|
||||||
if userExists && h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
// Check if user has shared access through organization
|
// Check if caller's tenant has shared access through organization
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, id, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, id, tenantID.(uint64), callerTenantRole)
|
||||||
if permErr == nil && isShared {
|
if permErr == nil && isShared {
|
||||||
// User has shared access, get the source tenant ID for embedding queries
|
// Tenant has shared access, get the source tenant ID for embedding queries
|
||||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, id)
|
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, id)
|
||||||
if srcErr == nil {
|
if srcErr == nil {
|
||||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d",
|
||||||
userID.(string), id, permission, sourceTenantID)
|
tenantID.(uint64), id, permission, sourceTenantID)
|
||||||
return kb, id, sourceTenantID, permission, nil
|
return kb, id, sourceTenantID, permission, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id)
|
// Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR caller's tenant has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id)
|
||||||
if userExists && h.agentShareService != nil {
|
if h.agentShareService != nil {
|
||||||
currentTenantID := tenantID.(uint64)
|
currentTenantID := tenantID.(uint64)
|
||||||
agentID := c.Query("agent_id")
|
agentID := c.Query("agent_id")
|
||||||
if agentID != "" {
|
if agentID != "" {
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
|
||||||
if err == nil && agent != nil {
|
if err == nil && agent != nil {
|
||||||
if kb.TenantID != agent.TenantID {
|
if kb.TenantID != agent.TenantID {
|
||||||
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
|
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
|
||||||
@@ -327,12 +328,12 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||||||
if mode == "none" {
|
if mode == "none" {
|
||||||
// no-op, fall through
|
// no-op, fall through
|
||||||
} else if mode == "all" {
|
} else if mode == "all" {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via shared agent %s (mode=all)", currentTenantID, id, agentID)
|
||||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||||
} else if mode == "selected" {
|
} else if mode == "selected" {
|
||||||
for _, allowedID := range agent.Config.KnowledgeBases {
|
for _, allowedID := range agent.Config.KnowledgeBases {
|
||||||
if allowedID == id {
|
if allowedID == id {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via shared agent %s (mode=selected)", currentTenantID, id, agentID)
|
||||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -340,14 +341,16 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// No agent_id in query: allow if user has any shared agent that can access this KB (e.g. from space list "通过智能体可见")
|
// No agent_id in query: allow if caller's tenant has any shared agent that can access this KB (e.g. from space list "通过智能体可见")
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), currentTenantID, kb)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, currentTenantID, callerTenantRole, kb)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent (no agent_id in query)", userID.(string), id)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent (no agent_id in query)", currentTenantID, id)
|
||||||
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
_ = userExists
|
||||||
|
|
||||||
// No permission: not owner and no shared access
|
// No permission: not owner and no shared access
|
||||||
logger.Warnf(
|
logger.Warnf(
|
||||||
@@ -416,13 +419,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
|||||||
c.Error(apperrors.NewUnauthorizedError("user ID not found"))
|
c.Error(apperrors.NewUnauthorizedError("user ID not found"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
userID, _ := userIDVal.(string)
|
_ = userIDVal
|
||||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
if currentTenantID == 0 {
|
if currentTenantID == 0 {
|
||||||
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
|
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if stderrors.Is(err, service.ErrAgentShareNotFound) || stderrors.Is(err, service.ErrAgentSharePermission) || stderrors.Is(err, service.ErrAgentNotFoundForShare) {
|
if stderrors.Is(err, service.ErrAgentShareNotFound) || stderrors.Is(err, service.ErrAgentSharePermission) || stderrors.Is(err, service.ErrAgentNotFoundForShare) {
|
||||||
c.Error(apperrors.NewForbiddenError("no permission for this shared agent"))
|
c.Error(apperrors.NewForbiddenError("no permission for this shared agent"))
|
||||||
|
|||||||
@@ -122,10 +122,10 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMyOrganizations lists organizations that the current user belongs to.
|
// ListMyOrganizations lists organizations that the current tenant belongs to.
|
||||||
// Response includes resource_counts (per-org KB/agent counts) for list sidebar so frontend does not need a separate GET /me/resource-counts.
|
// Response includes resource_counts (per-org KB/agent counts) for list sidebar so frontend does not need a separate GET /me/resource-counts.
|
||||||
// @Summary 获取我的组织列表
|
// @Summary 获取我的组织列表
|
||||||
// @Description 获取当前用户所属的所有组织,并附带各空间内知识库/智能体数量
|
// @Description 获取当前租户所属的所有组织,并附带各空间内知识库/智能体数量
|
||||||
// @Tags 组织管理
|
// @Tags 组织管理
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Success 200 {object} types.ListOrganizationsResponse
|
// @Success 200 {object} types.ListOrganizationsResponse
|
||||||
@@ -136,7 +136,7 @@ func (h *OrganizationHandler) ListMyOrganizations(c *gin.Context) {
|
|||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
orgs, err := h.orgService.ListUserOrganizations(ctx, userID)
|
orgs, err := h.orgService.ListTenantOrganizations(ctx, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to list organizations: %v", err)
|
logger.Errorf(ctx, "Failed to list organizations: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to list organizations").WithDetails(err.Error()))
|
c.Error(apperrors.NewInternalServerError("Failed to list organizations").WithDetails(err.Error()))
|
||||||
@@ -184,16 +184,18 @@ func (h *OrganizationHandler) buildResourceCountsByOrg(ctx context.Context, orgs
|
|||||||
logger.Warnf(ctx, "buildResourceCountsByOrg CountByOrganizations: %v", err)
|
logger.Warnf(ctx, "buildResourceCountsByOrg CountByOrganizations: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
directKBIDsByOrg, err := h.shareService.ListSharedKnowledgeBaseIDsByOrganizations(ctx, orgIDs, userID)
|
directKBIDsByOrg, err := h.shareService.ListSharedKnowledgeBaseIDsByOrganizations(ctx, orgIDs, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedKnowledgeBaseIDsByOrganizations: %v", err)
|
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedKnowledgeBaseIDsByOrganizations: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
agentListByOrg, err := h.agentShareService.ListSharedAgentsInOrganizations(ctx, orgIDs, userID, tenantID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
agentListByOrg, err := h.agentShareService.ListSharedAgentsInOrganizations(ctx, orgIDs, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedAgentsInOrganizations: %v", err)
|
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedAgentsInOrganizations: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
byOrgKB := make(map[string]int)
|
byOrgKB := make(map[string]int)
|
||||||
tenantKBCache := make(map[uint64][]string) // cache ListKnowledgeBasesByTenantID by tenantID
|
tenantKBCache := make(map[uint64][]string) // cache ListKnowledgeBasesByTenantID by tenantID
|
||||||
for _, o := range orgs {
|
for _, o := range orgs {
|
||||||
@@ -286,6 +288,7 @@ func (h *OrganizationHandler) UpdateOrganization(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
var req types.UpdateOrganizationRequest
|
var req types.UpdateOrganizationRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -293,7 +296,7 @@ func (h *OrganizationHandler) UpdateOrganization(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
org, err := h.orgService.UpdateOrganization(ctx, orgID, userID, &req)
|
org, err := h.orgService.UpdateOrganization(ctx, orgID, userID, tenantID, &req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to update organization: %v", err)
|
logger.Errorf(ctx, "Failed to update organization: %v", err)
|
||||||
if errors.Is(err, service.ErrInvalidValidityDays) {
|
if errors.Is(err, service.ErrInvalidValidityDays) {
|
||||||
@@ -328,8 +331,9 @@ func (h *OrganizationHandler) DeleteOrganization(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
if err := h.orgService.DeleteOrganization(ctx, orgID, userID); err != nil {
|
if err := h.orgService.DeleteOrganization(ctx, orgID, userID, tenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to delete organization: %v", err)
|
logger.Errorf(ctx, "Failed to delete organization: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied or organization not found"))
|
c.Error(apperrors.NewForbiddenError("Permission denied or organization not found"))
|
||||||
return
|
return
|
||||||
@@ -341,9 +345,9 @@ func (h *OrganizationHandler) DeleteOrganization(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListMembers lists all members of an organization
|
// ListMembers lists all tenant-members of an organization
|
||||||
// @Summary 获取组织成员列表
|
// @Summary 获取组织成员列表
|
||||||
// @Description 获取组织的所有成员
|
// @Description 获取组织的所有成员(按租户)
|
||||||
// @Tags 组织管理
|
// @Tags 组织管理
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param id path string true "组织ID"
|
// @Param id path string true "组织ID"
|
||||||
@@ -355,7 +359,7 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
|
|
||||||
members, err := h.orgService.ListMembers(ctx, orgID)
|
members, err := h.orgService.ListTenantMembers(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to list members: %v", err)
|
logger.Errorf(ctx, "Failed to list members: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to list members").WithDetails(err.Error()))
|
c.Error(apperrors.NewInternalServerError("Failed to list members").WithDetails(err.Error()))
|
||||||
@@ -366,15 +370,15 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
|
|||||||
for _, m := range members {
|
for _, m := range members {
|
||||||
resp := types.OrganizationMemberResponse{
|
resp := types.OrganizationMemberResponse{
|
||||||
ID: m.ID,
|
ID: m.ID,
|
||||||
UserID: m.UserID,
|
UserID: m.RepresentativeUserID,
|
||||||
Role: string(m.Role),
|
Role: string(m.Role),
|
||||||
TenantID: m.TenantID,
|
TenantID: m.TenantID,
|
||||||
JoinedAt: m.CreatedAt,
|
JoinedAt: m.CreatedAt,
|
||||||
}
|
}
|
||||||
if m.User != nil {
|
if m.RepresentativeUser != nil {
|
||||||
resp.Username = m.User.Username
|
resp.Username = m.RepresentativeUser.Username
|
||||||
resp.Email = m.User.Email
|
resp.Email = m.RepresentativeUser.Email
|
||||||
resp.Avatar = m.User.Avatar
|
resp.Avatar = m.RepresentativeUser.Avatar
|
||||||
}
|
}
|
||||||
response = append(response, resp)
|
response = append(response, resp)
|
||||||
}
|
}
|
||||||
@@ -388,25 +392,31 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateMemberRole updates a member's role
|
// UpdateMemberRole updates a tenant-member's role
|
||||||
// @Summary 更新成员角色
|
// @Summary 更新成员角色
|
||||||
// @Description 更新组织成员的角色(需要管理员权限)
|
// @Description 更新组织成员(租户)的角色(需要管理员权限)
|
||||||
// @Tags 组织管理
|
// @Tags 组织管理
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param id path string true "组织ID"
|
// @Param id path string true "组织ID"
|
||||||
// @Param user_id path string true "用户ID"
|
// @Param tenant_id path string true "成员租户ID"
|
||||||
// @Param request body types.UpdateMemberRoleRequest true "角色信息"
|
// @Param request body types.UpdateMemberRoleRequest true "角色信息"
|
||||||
// @Success 200 {object} map[string]interface{}
|
// @Success 200 {object} map[string]interface{}
|
||||||
// @Failure 403 {object} apperrors.AppError
|
// @Failure 403 {object} apperrors.AppError
|
||||||
// @Security Bearer
|
// @Security Bearer
|
||||||
// @Router /organizations/{id}/members/{user_id} [put]
|
// @Router /organizations/{id}/members/{tenant_id} [put]
|
||||||
func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
|
func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
memberUserID := c.Param("user_id")
|
memberTenantIDStr := c.Param("tenant_id")
|
||||||
|
memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(apperrors.NewValidationError("Invalid tenant ID"))
|
||||||
|
return
|
||||||
|
}
|
||||||
operatorUserID := c.GetString(types.UserIDContextKey.String())
|
operatorUserID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
operatorTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
var req types.UpdateMemberRoleRequest
|
var req types.UpdateMemberRoleRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -414,7 +424,7 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.orgService.UpdateMemberRole(ctx, orgID, memberUserID, req.Role, operatorUserID); err != nil {
|
if err := h.orgService.UpdateTenantMemberRole(ctx, orgID, memberTenantID, req.Role, operatorUserID, operatorTenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to update member role: %v", err)
|
logger.Errorf(ctx, "Failed to update member role: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
|
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
|
||||||
return
|
return
|
||||||
@@ -426,24 +436,30 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveMember removes a member from an organization
|
// RemoveMember removes a tenant-member from an organization
|
||||||
// @Summary 移除成员
|
// @Summary 移除成员
|
||||||
// @Description 从组织中移除成员(需要管理员权限)
|
// @Description 从组织中移除成员租户(需要管理员权限)
|
||||||
// @Tags 组织管理
|
// @Tags 组织管理
|
||||||
// @Param id path string true "组织ID"
|
// @Param id path string true "组织ID"
|
||||||
// @Param user_id path string true "用户ID"
|
// @Param tenant_id path string true "成员租户ID"
|
||||||
// @Success 200 {object} map[string]interface{}
|
// @Success 200 {object} map[string]interface{}
|
||||||
// @Failure 403 {object} apperrors.AppError
|
// @Failure 403 {object} apperrors.AppError
|
||||||
// @Security Bearer
|
// @Security Bearer
|
||||||
// @Router /organizations/{id}/members/{user_id} [delete]
|
// @Router /organizations/{id}/members/{tenant_id} [delete]
|
||||||
func (h *OrganizationHandler) RemoveMember(c *gin.Context) {
|
func (h *OrganizationHandler) RemoveMember(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
memberUserID := c.Param("user_id")
|
memberTenantIDStr := c.Param("tenant_id")
|
||||||
|
memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(apperrors.NewValidationError("Invalid tenant ID"))
|
||||||
|
return
|
||||||
|
}
|
||||||
operatorUserID := c.GetString(types.UserIDContextKey.String())
|
operatorUserID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
operatorTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
if err := h.orgService.RemoveMember(ctx, orgID, memberUserID, operatorUserID); err != nil {
|
if err := h.orgService.RemoveTenantMember(ctx, orgID, memberTenantID, operatorUserID, operatorTenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to remove member: %v", err)
|
logger.Errorf(ctx, "Failed to remove member: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
|
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
|
||||||
return
|
return
|
||||||
@@ -470,8 +486,9 @@ func (h *OrganizationHandler) GenerateInviteCode(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
code, err := h.orgService.GenerateInviteCode(ctx, orgID, userID)
|
code, err := h.orgService.GenerateInviteCode(ctx, orgID, userID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to generate invite code: %v", err)
|
logger.Errorf(ctx, "Failed to generate invite code: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
||||||
@@ -498,7 +515,7 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
inviteCode := c.Param("code")
|
inviteCode := c.Param("code")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Get organization by invite code
|
// Get organization by invite code
|
||||||
org, err := h.orgService.GetOrganizationByInviteCode(ctx, inviteCode)
|
org, err := h.orgService.GetOrganizationByInviteCode(ctx, inviteCode)
|
||||||
@@ -508,7 +525,7 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get member count
|
// Get member count
|
||||||
members, _ := h.orgService.ListMembers(ctx, org.ID)
|
members, _ := h.orgService.ListTenantMembers(ctx, org.ID)
|
||||||
memberCount := len(members)
|
memberCount := len(members)
|
||||||
|
|
||||||
// Get shared knowledge bases count
|
// Get shared knowledge bases count
|
||||||
@@ -518,8 +535,8 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) {
|
|||||||
agentShares, _ := h.agentShareService.ListSharesByOrganization(ctx, org.ID)
|
agentShares, _ := h.agentShareService.ListSharesByOrganization(ctx, org.ID)
|
||||||
agentShareCount := len(agentShares)
|
agentShareCount := len(agentShares)
|
||||||
|
|
||||||
// Check if user is already a member
|
// Check if caller's tenant is already a member
|
||||||
_, memberErr := h.orgService.GetMember(ctx, org.ID, userID)
|
_, memberErr := h.orgService.GetTenantMember(ctx, org.ID, tenantID)
|
||||||
isAlreadyMember := memberErr == nil
|
isAlreadyMember := memberErr == nil
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
@@ -616,10 +633,10 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user is already a member
|
// Check if caller's tenant is already a member
|
||||||
_, memberErr := h.orgService.GetMember(ctx, org.ID, userID)
|
_, memberErr := h.orgService.GetTenantMember(ctx, org.ID, tenantID)
|
||||||
if memberErr == nil {
|
if memberErr == nil {
|
||||||
c.Error(apperrors.NewValidationError("You are already a member of this organization"))
|
c.Error(apperrors.NewValidationError("Your tenant is already a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -665,7 +682,7 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) {
|
|||||||
// @Router /organizations/search [get]
|
// @Router /organizations/search [get]
|
||||||
func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) {
|
func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
query := c.Query("q")
|
query := c.Query("q")
|
||||||
limit := 20
|
limit := 20
|
||||||
if l := c.Query("limit"); l != "" {
|
if l := c.Query("limit"); l != "" {
|
||||||
@@ -673,7 +690,7 @@ func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) {
|
|||||||
limit = n
|
limit = n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
resp, err := h.orgService.SearchSearchableOrganizations(ctx, userID, query, limit)
|
resp, err := h.orgService.SearchSearchableOrganizations(ctx, tenantID, query, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to search organizations: %v", err)
|
logger.Errorf(ctx, "Failed to search organizations: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to search organizations"))
|
c.Error(apperrors.NewInternalServerError("Failed to search organizations"))
|
||||||
@@ -816,6 +833,7 @@ func (h *OrganizationHandler) LeaveOrganization(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check if user is the owner
|
// Check if user is the owner
|
||||||
org, err := h.orgService.GetOrganization(ctx, orgID)
|
org, err := h.orgService.GetOrganization(ctx, orgID)
|
||||||
@@ -829,8 +847,8 @@ func (h *OrganizationHandler) LeaveOrganization(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove the user from the organization
|
// Remove the caller's tenant from the organization (self-leave)
|
||||||
if err := h.orgService.RemoveMember(ctx, orgID, userID, userID); err != nil {
|
if err := h.orgService.RemoveTenantMember(ctx, orgID, tenantID, userID, tenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to leave organization: %v", err)
|
logger.Errorf(ctx, "Failed to leave organization: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to leave organization"))
|
c.Error(apperrors.NewInternalServerError("Failed to leave organization"))
|
||||||
return
|
return
|
||||||
@@ -856,10 +874,10 @@ func (h *OrganizationHandler) ListJoinRequests(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check admin
|
// Check admin: caller's tenant must be admin in the org
|
||||||
isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID)
|
isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID)
|
||||||
if err != nil || !isAdmin {
|
if err != nil || !isAdmin {
|
||||||
c.Error(apperrors.NewForbiddenError("Only organization admins can view join requests"))
|
c.Error(apperrors.NewForbiddenError("Only organization admins can view join requests"))
|
||||||
return
|
return
|
||||||
@@ -928,9 +946,10 @@ func (h *OrganizationHandler) ReviewJoinRequest(c *gin.Context) {
|
|||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
requestID := c.Param("request_id")
|
requestID := c.Param("request_id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check admin
|
// Check admin: caller's tenant must be admin in the org
|
||||||
isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID)
|
isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID)
|
||||||
if err != nil || !isAdmin {
|
if err != nil || !isAdmin {
|
||||||
c.Error(apperrors.NewForbiddenError("Only organization admins can review join requests"))
|
c.Error(apperrors.NewForbiddenError("Only organization admins can review join requests"))
|
||||||
return
|
return
|
||||||
@@ -950,7 +969,7 @@ func (h *OrganizationHandler) ReviewJoinRequest(c *gin.Context) {
|
|||||||
assignRole = &req.Role
|
assignRole = &req.Role
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.orgService.ReviewJoinRequest(ctx, orgID, requestID, req.Approved, userID, req.Message, assignRole); err != nil {
|
if err := h.orgService.ReviewJoinRequest(ctx, orgID, requestID, req.Approved, userID, tenantID, req.Message, assignRole); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to review join request: %v", err)
|
logger.Errorf(ctx, "Failed to review join request: %v", err)
|
||||||
if errors.Is(err, service.ErrOrgMemberLimitReached) {
|
if errors.Is(err, service.ErrOrgMemberLimitReached) {
|
||||||
c.Error(apperrors.NewValidationError("空间成员已满,无法通过该加入申请"))
|
c.Error(apperrors.NewValidationError("空间成员已满,无法通过该加入申请"))
|
||||||
@@ -1090,6 +1109,7 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) {
|
|||||||
|
|
||||||
shareID := c.Param("share_id")
|
shareID := c.Param("share_id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
var req types.UpdateSharePermissionRequest
|
var req types.UpdateSharePermissionRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -1097,7 +1117,7 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.shareService.UpdateSharePermission(ctx, shareID, req.Permission, userID); err != nil {
|
if err := h.shareService.UpdateSharePermission(ctx, shareID, req.Permission, userID, tenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to update share permission: %v", err)
|
logger.Errorf(ctx, "Failed to update share permission: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
||||||
return
|
return
|
||||||
@@ -1124,8 +1144,9 @@ func (h *OrganizationHandler) RemoveShare(c *gin.Context) {
|
|||||||
|
|
||||||
shareID := c.Param("share_id")
|
shareID := c.Param("share_id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
if err := h.shareService.RemoveShare(ctx, shareID, userID); err != nil {
|
if err := h.shareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to remove share: %v", err)
|
logger.Errorf(ctx, "Failed to remove share: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
||||||
return
|
return
|
||||||
@@ -1150,12 +1171,12 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check if user is a member and get their role for effective-permission calculation
|
// Check if caller's tenant is a member and get its role for effective-permission calculation
|
||||||
member, err := h.orgService.GetMember(ctx, orgID, userID)
|
member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
myRoleInOrg := member.Role
|
myRoleInOrg := member.Role
|
||||||
@@ -1224,10 +1245,10 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) {
|
|||||||
func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) {
|
func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
|
||||||
tenantID := types.MustTenantIDFromContext(ctx)
|
tenantID := types.MustTenantIDFromContext(ctx)
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
sharedKBs, err := h.shareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
sharedKBs, err := h.shareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to list shared knowledge bases: %v", err)
|
logger.Errorf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases"))
|
c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases"))
|
||||||
@@ -1314,7 +1335,8 @@ func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
shareID := c.Param("share_id")
|
shareID := c.Param("share_id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
if err := h.agentShareService.RemoveShare(ctx, shareID, userID); err != nil {
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
if err := h.agentShareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to remove agent share: %v", err)
|
logger.Errorf(ctx, "Failed to remove agent share: %v", err)
|
||||||
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
c.Error(apperrors.NewForbiddenError("Permission denied"))
|
||||||
return
|
return
|
||||||
@@ -1338,10 +1360,10 @@ func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) {
|
|||||||
func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
member, err := h.orgService.GetMember(ctx, orgID, userID)
|
member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
myRoleInOrg := member.Role
|
myRoleInOrg := member.Role
|
||||||
@@ -1409,9 +1431,9 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
|||||||
// @Router /shared-agents [get]
|
// @Router /shared-agents [get]
|
||||||
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
|
||||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
list, err := h.agentShareService.ListSharedAgents(ctx, userID, tenantID)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
list, err := h.agentShareService.ListSharedAgents(ctx, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to list shared agents: %v", err)
|
logger.Errorf(ctx, "Failed to list shared agents: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to list shared agents"))
|
c.Error(apperrors.NewInternalServerError("Failed to list shared agents"))
|
||||||
@@ -1421,8 +1443,8 @@ func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// listSpaceKnowledgeBasesInOrganization returns merged list of direct shared KBs and agent-carried KBs in the org (for list and count).
|
// listSpaceKnowledgeBasesInOrganization returns merged list of direct shared KBs and agent-carried KBs in the org (for list and count).
|
||||||
func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, tenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
|
||||||
directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
|
directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1434,7 +1456,7 @@ func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
|
agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return directList, nil
|
return directList, nil
|
||||||
}
|
}
|
||||||
@@ -1552,13 +1574,13 @@ func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.
|
|||||||
func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Context) {
|
func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
|
||||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
|
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, service.ErrUserNotInOrg) {
|
if errors.Is(err, service.ErrTenantNotInOrg) {
|
||||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err)
|
logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err)
|
||||||
@@ -1580,13 +1602,13 @@ func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Contex
|
|||||||
func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) {
|
func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
|
||||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
|
|
||||||
list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
|
list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, tenantID, callerTenantRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, service.ErrUserNotInOrg) {
|
if errors.Is(err, service.ErrTenantNotInOrg) {
|
||||||
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
|
c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
logger.Errorf(ctx, "Failed to list organization shared agents: %v", err)
|
logger.Errorf(ctx, "Failed to list organization shared agents: %v", err)
|
||||||
@@ -1621,13 +1643,14 @@ func (h *OrganizationHandler) SetSharedAgentDisabledByMe(c *gin.Context) {
|
|||||||
if err == nil && agent != nil && agent.TenantID == tid {
|
if err == nil && agent != nil && agent.TenantID == tid {
|
||||||
sourceTenantID = tid
|
sourceTenantID = tid
|
||||||
} else {
|
} else {
|
||||||
share, err := h.agentShareService.GetShareByAgentIDForUser(ctx, uid, req.AgentID, tid)
|
share, err := h.agentShareService.GetShareByAgentIDForTenant(ctx, tid, req.AgentID, tid)
|
||||||
if err != nil || share == nil {
|
if err != nil || share == nil {
|
||||||
c.Error(apperrors.NewForbiddenError("No access to this agent"))
|
c.Error(apperrors.NewForbiddenError("No access to this agent"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
sourceTenantID = share.SourceTenantID
|
sourceTenantID = share.SourceTenantID
|
||||||
}
|
}
|
||||||
|
_ = uid
|
||||||
if err := h.agentShareService.SetSharedAgentDisabledByMe(ctx, tid, req.AgentID, sourceTenantID, req.Disabled); err != nil {
|
if err := h.agentShareService.SetSharedAgentDisabledByMe(ctx, tid, req.AgentID, sourceTenantID, req.Disabled); err != nil {
|
||||||
logger.Errorf(ctx, "SetSharedAgentDisabledByMe failed: %v", err)
|
logger.Errorf(ctx, "SetSharedAgentDisabledByMe failed: %v", err)
|
||||||
c.Error(apperrors.NewInternalServerError("Failed to update preference"))
|
c.Error(apperrors.NewInternalServerError("Failed to update preference"))
|
||||||
@@ -1638,6 +1661,7 @@ func (h *OrganizationHandler) SetSharedAgentDisabledByMe(c *gin.Context) {
|
|||||||
|
|
||||||
// toOrgResponse converts an organization to response format
|
// toOrgResponse converts an organization to response format
|
||||||
func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Organization, currentUserID string) types.OrganizationResponse {
|
func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Organization, currentUserID string) types.OrganizationResponse {
|
||||||
|
currentTenantID := types.MustTenantIDFromContext(ctx)
|
||||||
resp := types.OrganizationResponse{
|
resp := types.OrganizationResponse{
|
||||||
ID: org.ID,
|
ID: org.ID,
|
||||||
Name: org.Name,
|
Name: org.Name,
|
||||||
@@ -1653,8 +1677,8 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
|
|||||||
UpdatedAt: org.UpdatedAt,
|
UpdatedAt: org.UpdatedAt,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get member count
|
// Get member count (per-tenant)
|
||||||
if members, err := h.orgService.ListMembers(ctx, org.ID); err == nil {
|
if members, err := h.orgService.ListTenantMembers(ctx, org.ID); err == nil {
|
||||||
resp.MemberCount = len(members)
|
resp.MemberCount = len(members)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1667,9 +1691,9 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
|
|||||||
resp.AgentShareCount = len(agentShares)
|
resp.AgentShareCount = len(agentShares)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get current user's role in this organization
|
// Get current tenant's role in this organization
|
||||||
isAdmin := false
|
isAdmin := false
|
||||||
if role, err := h.orgService.GetUserRoleInOrg(ctx, org.ID, currentUserID); err == nil {
|
if role, err := h.orgService.GetTenantRoleInOrg(ctx, org.ID, currentTenantID); err == nil {
|
||||||
resp.MyRole = string(role)
|
resp.MyRole = string(role)
|
||||||
isAdmin = (role == types.OrgRoleAdmin)
|
isAdmin = (role == types.OrgRoleAdmin)
|
||||||
}
|
}
|
||||||
@@ -1681,8 +1705,8 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if current user has pending upgrade request
|
// Check if current tenant has pending upgrade request
|
||||||
if _, err := h.orgService.GetPendingUpgradeRequest(ctx, org.ID, currentUserID); err == nil {
|
if _, err := h.orgService.GetPendingUpgradeRequest(ctx, org.ID, currentTenantID); err == nil {
|
||||||
resp.HasPendingUpgrade = true
|
resp.HasPendingUpgrade = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1706,10 +1730,10 @@ func (h *OrganizationHandler) SearchUsersForInvite(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
query := c.Query("q")
|
query := c.Query("q")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check admin permission
|
// Check admin permission: caller's tenant must be org admin
|
||||||
isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID)
|
isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID)
|
||||||
if err != nil || !isAdmin {
|
if err != nil || !isAdmin {
|
||||||
c.Error(apperrors.NewForbiddenError("Only organization admins can invite members"))
|
c.Error(apperrors.NewForbiddenError("Only organization admins can invite members"))
|
||||||
return
|
return
|
||||||
@@ -1739,17 +1763,17 @@ func (h *OrganizationHandler) SearchUsersForInvite(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get existing members
|
// Get existing tenant members; exclude users whose tenant is already a member
|
||||||
existingMembers, _ := h.orgService.ListMembers(ctx, orgID)
|
existingMembers, _ := h.orgService.ListTenantMembers(ctx, orgID)
|
||||||
existingMemberIDs := make(map[string]bool)
|
existingTenantIDs := make(map[uint64]bool)
|
||||||
for _, m := range existingMembers {
|
for _, m := range existingMembers {
|
||||||
existingMemberIDs[m.UserID] = true
|
existingTenantIDs[m.TenantID] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter out existing members and build response
|
// Filter out users whose tenant is already a member
|
||||||
var result []gin.H
|
var result []gin.H
|
||||||
for _, u := range users {
|
for _, u := range users {
|
||||||
if existingMemberIDs[u.ID] {
|
if existingTenantIDs[u.TenantID] {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
result = append(result, gin.H{
|
result = append(result, gin.H{
|
||||||
@@ -1787,9 +1811,10 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) {
|
|||||||
|
|
||||||
orgID := c.Param("id")
|
orgID := c.Param("id")
|
||||||
userID := c.GetString(types.UserIDContextKey.String())
|
userID := c.GetString(types.UserIDContextKey.String())
|
||||||
|
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
|
||||||
// Check admin permission
|
// Check admin permission: caller's tenant must be org admin
|
||||||
isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID)
|
isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID)
|
||||||
if err != nil || !isAdmin {
|
if err != nil || !isAdmin {
|
||||||
c.Error(apperrors.NewForbiddenError("Only organization admins can invite members"))
|
c.Error(apperrors.NewForbiddenError("Only organization admins can invite members"))
|
||||||
return
|
return
|
||||||
@@ -1814,15 +1839,15 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if already a member
|
// Check if invitee's tenant is already a member of this org
|
||||||
_, memberErr := h.orgService.GetMember(ctx, orgID, req.UserID)
|
_, memberErr := h.orgService.GetTenantMember(ctx, orgID, invitedUser.TenantID)
|
||||||
if memberErr == nil {
|
if memberErr == nil {
|
||||||
c.Error(apperrors.NewValidationError("User is already a member of this organization"))
|
c.Error(apperrors.NewValidationError("User's tenant is already a member of this organization"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add member
|
// Add tenant member with the invited user as representative
|
||||||
if err := h.orgService.AddMember(ctx, orgID, req.UserID, invitedUser.TenantID, req.Role); err != nil {
|
if err := h.orgService.AddTenantMember(ctx, orgID, invitedUser.TenantID, req.UserID, req.Role); err != nil {
|
||||||
logger.Errorf(ctx, "Failed to add member: %v", err)
|
logger.Errorf(ctx, "Failed to add member: %v", err)
|
||||||
if errors.Is(err, service.ErrOrgMemberLimitReached) {
|
if errors.Is(err, service.ErrOrgMemberLimitReached) {
|
||||||
c.Error(apperrors.NewValidationError("该空间成员已满,无法添加新成员"))
|
c.Error(apperrors.NewValidationError("该空间成员已满,无法添加新成员"))
|
||||||
|
|||||||
@@ -250,8 +250,8 @@ func (h *Handler) resolveAgent(ctx context.Context, c *gin.Context, agentID stri
|
|||||||
userIDVal, _ := c.Get(types.UserIDContextKey.String())
|
userIDVal, _ := c.Get(types.UserIDContextKey.String())
|
||||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
|
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
|
||||||
userID, _ := userIDVal.(string)
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
|
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID)
|
||||||
if err == nil && agent != nil {
|
if err == nil && agent != nil {
|
||||||
effectiveTenantID = agent.TenantID
|
effectiveTenantID = agent.TenantID
|
||||||
customAgent = agent
|
customAgent = agent
|
||||||
|
|||||||
+10
-7
@@ -51,6 +51,7 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con
|
|||||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||||
}
|
}
|
||||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||||
|
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||||
kbID = secutils.SanitizeForLog(kbID)
|
kbID = secutils.SanitizeForLog(kbID)
|
||||||
if kbID == "" {
|
if kbID == "" {
|
||||||
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||||
@@ -69,24 +70,26 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con
|
|||||||
if kb.TenantID == tenantID {
|
if kb.TenantID == tenantID {
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||||
}
|
}
|
||||||
if userExists && h.kbShareService != nil {
|
if h.kbShareService != nil {
|
||||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole)
|
||||||
if permErr == nil && isShared {
|
if permErr == nil && isShared {
|
||||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||||
if srcErr == nil {
|
if srcErr == nil {
|
||||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d",
|
||||||
userID.(string), kbID, permission, sourceTenantID)
|
tenantID, kbID, permission, sourceTenantID)
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if userExists && h.agentShareService != nil {
|
if h.agentShareService != nil {
|
||||||
can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
|
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb)
|
||||||
if err == nil && can {
|
if err == nil && can {
|
||||||
logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
|
logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID)
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ = userID
|
||||||
|
_ = userExists
|
||||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-14
@@ -801,28 +801,28 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
// Organization routes
|
// Organization routes
|
||||||
orgs := r.Group("/organizations")
|
orgs := r.Group("/organizations")
|
||||||
{
|
{
|
||||||
// Create organization
|
// Create organization (Admin+ in caller's tenant only)
|
||||||
orgs.POST("", orgHandler.CreateOrganization)
|
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
|
||||||
// List my organizations
|
// List my organizations
|
||||||
orgs.GET("", orgHandler.ListMyOrganizations)
|
orgs.GET("", orgHandler.ListMyOrganizations)
|
||||||
// Preview organization by invite code (without joining)
|
// Preview organization by invite code (without joining)
|
||||||
orgs.GET("/preview/:code", orgHandler.PreviewByInviteCode)
|
orgs.GET("/preview/:code", orgHandler.PreviewByInviteCode)
|
||||||
// Join organization by invite code
|
// Join organization by invite code (Admin+ in caller's tenant only)
|
||||||
orgs.POST("/join", orgHandler.JoinByInviteCode)
|
orgs.POST("/join", g.Admin(), orgHandler.JoinByInviteCode)
|
||||||
// Submit join request (for organizations that require approval)
|
// Submit join request (for organizations that require approval) (Admin+)
|
||||||
orgs.POST("/join-request", orgHandler.SubmitJoinRequest)
|
orgs.POST("/join-request", g.Admin(), orgHandler.SubmitJoinRequest)
|
||||||
// Search searchable (discoverable) organizations
|
// Search searchable (discoverable) organizations
|
||||||
orgs.GET("/search", orgHandler.SearchOrganizations)
|
orgs.GET("/search", orgHandler.SearchOrganizations)
|
||||||
// Join searchable organization by ID (no invite code)
|
// Join searchable organization by ID (no invite code) (Admin+)
|
||||||
orgs.POST("/join-by-id", orgHandler.JoinByOrganizationID)
|
orgs.POST("/join-by-id", g.Admin(), orgHandler.JoinByOrganizationID)
|
||||||
// Get organization by ID
|
// Get organization by ID
|
||||||
orgs.GET("/:id", orgHandler.GetOrganization)
|
orgs.GET("/:id", orgHandler.GetOrganization)
|
||||||
// Update organization
|
// Update organization
|
||||||
orgs.PUT("/:id", orgHandler.UpdateOrganization)
|
orgs.PUT("/:id", orgHandler.UpdateOrganization)
|
||||||
// Delete organization
|
// Delete organization
|
||||||
orgs.DELETE("/:id", orgHandler.DeleteOrganization)
|
orgs.DELETE("/:id", orgHandler.DeleteOrganization)
|
||||||
// Leave organization
|
// Leave organization (Admin+ in caller's tenant only)
|
||||||
orgs.POST("/:id/leave", orgHandler.LeaveOrganization)
|
orgs.POST("/:id/leave", g.Admin(), orgHandler.LeaveOrganization)
|
||||||
// Request role upgrade (for existing members)
|
// Request role upgrade (for existing members)
|
||||||
orgs.POST("/:id/request-upgrade", orgHandler.RequestRoleUpgrade)
|
orgs.POST("/:id/request-upgrade", orgHandler.RequestRoleUpgrade)
|
||||||
// Generate invite code
|
// Generate invite code
|
||||||
@@ -833,10 +833,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
orgs.POST("/:id/invite", orgHandler.InviteMember)
|
orgs.POST("/:id/invite", orgHandler.InviteMember)
|
||||||
// List members
|
// List members
|
||||||
orgs.GET("/:id/members", orgHandler.ListMembers)
|
orgs.GET("/:id/members", orgHandler.ListMembers)
|
||||||
// Update member role
|
// Update member role (path parameter is the member tenant_id)
|
||||||
orgs.PUT("/:id/members/:user_id", orgHandler.UpdateMemberRole)
|
orgs.PUT("/:id/members/:tenant_id", orgHandler.UpdateMemberRole)
|
||||||
// Remove member
|
// Remove member (path parameter is the member tenant_id)
|
||||||
orgs.DELETE("/:id/members/:user_id", orgHandler.RemoveMember)
|
orgs.DELETE("/:id/members/:tenant_id", orgHandler.RemoveMember)
|
||||||
// List join requests (admin only)
|
// List join requests (admin only)
|
||||||
orgs.GET("/:id/join-requests", orgHandler.ListJoinRequests)
|
orgs.GET("/:id/join-requests", orgHandler.ListJoinRequests)
|
||||||
// Review join request (admin only)
|
// Review join request (admin only)
|
||||||
|
|||||||
@@ -7,99 +7,126 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/internal/types"
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OrganizationService defines the organization service interface
|
// OrganizationService defines the organization service interface.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: organization membership is per-tenant, not per-user.
|
||||||
|
// Adding/removing/updating "members" therefore takes a tenant_id, and
|
||||||
|
// permission checks key on (org, tenant). RepresentativeUserID is
|
||||||
|
// informational and not load-bearing.
|
||||||
type OrganizationService interface {
|
type OrganizationService interface {
|
||||||
// Organization CRUD
|
// Organization CRUD
|
||||||
CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error)
|
CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error)
|
||||||
GetOrganization(ctx context.Context, id string) (*types.Organization, error)
|
GetOrganization(ctx context.Context, id string) (*types.Organization, error)
|
||||||
GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||||
ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error)
|
ListTenantOrganizations(ctx context.Context, tenantID uint64) ([]*types.Organization, error)
|
||||||
UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error)
|
UpdateOrganization(ctx context.Context, id string, userID string, tenantID uint64, req *types.UpdateOrganizationRequest) (*types.Organization, error)
|
||||||
DeleteOrganization(ctx context.Context, id string, userID string) error
|
DeleteOrganization(ctx context.Context, id string, userID string, tenantID uint64) error
|
||||||
|
|
||||||
// Member Management
|
// Member Management (Plan 3: members are tenants)
|
||||||
AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error
|
// AddTenantMember adds a tenant to the org with the given role; representativeUserID
|
||||||
RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error
|
// is only used for display labelling.
|
||||||
UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error
|
AddTenantMember(ctx context.Context, orgID string, tenantID uint64, representativeUserID string, role types.OrgMemberRole) error
|
||||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
RemoveTenantMember(ctx context.Context, orgID string, memberTenantID uint64, operatorUserID string, operatorTenantID uint64) error
|
||||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
UpdateTenantMemberRole(ctx context.Context, orgID string, memberTenantID uint64, role types.OrgMemberRole, operatorUserID string, operatorTenantID uint64) error
|
||||||
|
ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error)
|
||||||
|
GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error)
|
||||||
|
|
||||||
// Invite Code
|
// Invite Code
|
||||||
GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error)
|
GenerateInviteCode(ctx context.Context, orgID string, userID string, tenantID uint64) (string, error)
|
||||||
JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error)
|
JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error)
|
||||||
// Searchable organizations (discovery)
|
// Searchable organizations (discovery)
|
||||||
SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error)
|
SearchSearchableOrganizations(ctx context.Context, tenantID uint64, query string, limit int) (*types.ListSearchableOrganizationsResponse, error)
|
||||||
JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error)
|
JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error)
|
||||||
|
|
||||||
// Join Requests (for organizations that require approval)
|
// Join Requests (for organizations that require approval)
|
||||||
SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error)
|
SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error)
|
||||||
ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error)
|
ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error)
|
||||||
CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error)
|
CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error)
|
||||||
ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error
|
ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, reviewerTenantID uint64, message string, assignRole *types.OrgMemberRole) error
|
||||||
|
|
||||||
// Role Upgrade Requests (for existing members to request higher permissions)
|
// Role Upgrade Requests (for existing tenants to request higher permissions)
|
||||||
RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error)
|
RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error)
|
||||||
GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
GetPendingUpgradeRequest(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error)
|
||||||
|
|
||||||
// Permission Check
|
// Permission Check (drive purely off the requesting tenant)
|
||||||
IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error)
|
IsTenantOrgAdmin(ctx context.Context, orgID string, tenantID uint64) (bool, error)
|
||||||
GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error)
|
GetTenantRoleInOrg(ctx context.Context, orgID string, tenantID uint64) (types.OrgMemberRole, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// OrganizationRepository defines the organization repository interface
|
// OrganizationRepository defines the organization repository interface.
|
||||||
|
//
|
||||||
|
// Members are stored per-tenant in `organization_tenant_members`.
|
||||||
type OrganizationRepository interface {
|
type OrganizationRepository interface {
|
||||||
// Organization CRUD
|
// Organization CRUD
|
||||||
Create(ctx context.Context, org *types.Organization) error
|
Create(ctx context.Context, org *types.Organization) error
|
||||||
GetByID(ctx context.Context, id string) (*types.Organization, error)
|
GetByID(ctx context.Context, id string) (*types.Organization, error)
|
||||||
GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||||
ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error)
|
ListByTenantID(ctx context.Context, tenantID uint64) ([]*types.Organization, error)
|
||||||
ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error)
|
ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error)
|
||||||
Update(ctx context.Context, org *types.Organization) error
|
Update(ctx context.Context, org *types.Organization) error
|
||||||
Delete(ctx context.Context, id string) error
|
Delete(ctx context.Context, id string) error
|
||||||
|
|
||||||
// Member operations
|
// Tenant member operations
|
||||||
AddMember(ctx context.Context, member *types.OrganizationMember) error
|
AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember) error
|
||||||
RemoveMember(ctx context.Context, orgID string, userID string) error
|
RemoveTenantMember(ctx context.Context, orgID string, tenantID uint64) error
|
||||||
UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error
|
UpdateTenantMemberRole(ctx context.Context, orgID string, tenantID uint64, role types.OrgMemberRole) error
|
||||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error)
|
||||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error)
|
||||||
ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error)
|
ListTenantMembersByTenantForOrgs(ctx context.Context, tenantID uint64, orgIDs []string) (map[string]*types.OrganizationTenantMember, error)
|
||||||
CountMembers(ctx context.Context, orgID string) (int64, error)
|
CountTenantMembers(ctx context.Context, orgID string) (int64, error)
|
||||||
|
|
||||||
// Invite code
|
// Invite code
|
||||||
UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error
|
UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error
|
||||||
|
|
||||||
// Join requests
|
// Join requests (still keyed on the *requesting* user, but a single
|
||||||
|
// pending request per (org, tenant) since the approve action grants
|
||||||
|
// the whole tenant access).
|
||||||
CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error
|
CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error
|
||||||
GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error)
|
GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error)
|
||||||
GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
GetPendingJoinRequestByTenant(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error)
|
||||||
GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error)
|
GetPendingRequestByTenantAndType(ctx context.Context, orgID string, tenantID uint64, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error)
|
||||||
ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error)
|
ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error)
|
||||||
CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error)
|
CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error)
|
||||||
UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error
|
UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// KBShareService defines the knowledge base sharing service interface
|
// KBShareService defines the knowledge base sharing service interface.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: permission resolution keys on the caller's tenant
|
||||||
|
// (not user). The 3-dimension cap is applied inside CheckTenantKBPermission
|
||||||
|
// and is the canonical permission gate for shared KBs:
|
||||||
|
//
|
||||||
|
// effective = min(share.Permission, tenant_org_role, tenant_role_cap)
|
||||||
|
//
|
||||||
|
// where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless
|
||||||
|
// of the org-level grant — Viewer in your own tenant must always be
|
||||||
|
// read-only on shared resources.
|
||||||
type KBShareService interface {
|
type KBShareService interface {
|
||||||
// Share Management
|
// Share Management
|
||||||
ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error)
|
ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error)
|
||||||
UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error
|
UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string, tenantID uint64) error
|
||||||
RemoveShare(ctx context.Context, shareID string, userID string) error
|
RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error
|
||||||
|
|
||||||
// Query
|
// Query
|
||||||
// ListSharesByKnowledgeBase lists shares for a KB; tenantID must own the KB (authz check).
|
// ListSharesByKnowledgeBase lists shares for a KB; tenantID must own the KB (authz check).
|
||||||
ListSharesByKnowledgeBase(ctx context.Context, kbID string, tenantID uint64) ([]*types.KnowledgeBaseShare, error)
|
ListSharesByKnowledgeBase(ctx context.Context, kbID string, tenantID uint64) ([]*types.KnowledgeBaseShare, error)
|
||||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||||
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
|
ListSharedKnowledgeBases(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error)
|
||||||
ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error)
|
ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error)
|
||||||
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch, for sidebar count).
|
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch, for sidebar count).
|
||||||
ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error)
|
ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, tenantID uint64) (map[string][]string, error)
|
||||||
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
||||||
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||||
|
|
||||||
// Permission Check
|
// Permission Check (Plan 3: tenant-keyed). Returns the effective
|
||||||
CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error)
|
// OrgMemberRole the caller can use against the shared KB after the
|
||||||
HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error)
|
// 3-D cap, plus a bool indicating whether *any* share matches the
|
||||||
|
// caller's tenant. callerTenantRole is the caller's tenant-RBAC
|
||||||
|
// role and is used to apply the Viewer cap.
|
||||||
|
CheckTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole) (types.OrgMemberRole, bool, error)
|
||||||
|
// HasTenantKBPermission is a thin "do I have at least N" wrapper over
|
||||||
|
// CheckTenantKBPermission.
|
||||||
|
HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error)
|
||||||
|
|
||||||
// Get source tenant for cross-tenant embedding
|
// Get source tenant for cross-tenant embedding
|
||||||
GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error)
|
GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error)
|
||||||
@@ -129,34 +156,38 @@ type KBShareRepository interface {
|
|||||||
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error)
|
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error)
|
||||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||||
|
|
||||||
// Query for user's accessible shared knowledge bases
|
// Query for tenant's accessible shared knowledge bases
|
||||||
ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error)
|
ListSharedKBsForTenant(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBaseShare, error)
|
||||||
|
|
||||||
// Count shares
|
// Count shares
|
||||||
CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error)
|
CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error)
|
||||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AgentShareService defines the agent sharing service interface
|
// AgentShareService defines the agent sharing service interface.
|
||||||
|
//
|
||||||
|
// Plan 3 of #1303: visibility and access checks key on the caller's
|
||||||
|
// tenant. callerTenantRole flows through so the 3-D cap (tenant Viewer
|
||||||
|
// → at most OrgRoleViewer) can be applied consistently.
|
||||||
type AgentShareService interface {
|
type AgentShareService interface {
|
||||||
ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error)
|
ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error)
|
||||||
RemoveShare(ctx context.Context, shareID string, userID string) error
|
RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error
|
||||||
ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
||||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||||
ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error)
|
ListSharedAgents(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedAgentInfo, error)
|
||||||
ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error)
|
ListSharedAgentsInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedAgentItem, error)
|
||||||
// ListSharedAgentsInOrganizations returns per-org agent list (batch, for sidebar count merge).
|
// ListSharedAgentsInOrganizations returns per-org agent list (batch, for sidebar count merge).
|
||||||
ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error)
|
ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, tenantID uint64, callerTenantRole types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error)
|
||||||
// SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-user preference).
|
// SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-tenant preference; will be revisited in a follow-up PR).
|
||||||
SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error
|
SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error
|
||||||
// GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention.
|
// GetSharedAgentForTenant returns the shared agent by agentID if the caller's tenant has access; used to resolve KB scope for @ mention.
|
||||||
GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error)
|
GetSharedAgentForTenant(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, agentID string) (*types.CustomAgent, error)
|
||||||
// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id).
|
// TenantCanAccessKBViaSomeSharedAgent returns true if the caller's tenant has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id).
|
||||||
UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error)
|
TenantCanAccessKBViaSomeSharedAgent(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, kb *types.KnowledgeBase) (bool, error)
|
||||||
GetShare(ctx context.Context, shareID string) (*types.AgentShare, error)
|
GetShare(ctx context.Context, shareID string) (*types.AgentShare, error)
|
||||||
GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
|
GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
|
||||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access, excluding source_tenant_id == excludeTenantID (e.g. current tenant to get shared-from-other only).
|
// GetShareByAgentIDForTenant returns one share for the given agentID that the tenant can access, excluding source_tenant_id == excludeTenantID (e.g. caller's own tenant to get shared-from-other only).
|
||||||
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
||||||
// CountByOrganizations returns share counts per organization (for sidebar); excludes deleted agents
|
// CountByOrganizations returns share counts per organization (for sidebar); excludes deleted agents
|
||||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||||
}
|
}
|
||||||
@@ -173,10 +204,10 @@ type AgentShareRepository interface {
|
|||||||
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
||||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||||
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error)
|
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error)
|
||||||
ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error)
|
ListSharedAgentsForTenant(ctx context.Context, tenantID uint64) ([]*types.AgentShare, error)
|
||||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
|
// GetShareByAgentIDForTenant returns one share for the given agentID that the tenant can access (tenant in org), excluding source_tenant_id == excludeTenantID.
|
||||||
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TenantDisabledSharedAgentRepository stores per-tenant "disabled" agents (hidden from conversation dropdown; own and shared)
|
// TenantDisabledSharedAgentRepository stores per-tenant "disabled" agents (hidden from conversation dropdown; own and shared)
|
||||||
|
|||||||
@@ -38,6 +38,25 @@ func (r OrgMemberRole) HasPermission(required OrgMemberRole) bool {
|
|||||||
return roleLevel[r] >= roleLevel[required]
|
return roleLevel[r] >= roleLevel[required]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MinOrgRole returns whichever of a / b is the lower role on the
|
||||||
|
// admin > editor > viewer ladder. Used to apply caps when combining
|
||||||
|
// (a) the share's grant, (b) the tenant's role inside the org, and
|
||||||
|
// (c) the caller's tenant-RBAC ceiling. A zero/empty role is treated
|
||||||
|
// as "less than viewer" so it short-circuits to whatever the other
|
||||||
|
// argument is.
|
||||||
|
func MinOrgRole(a, b OrgMemberRole) OrgMemberRole {
|
||||||
|
if a == "" {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
if b == "" {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
if a.HasPermission(b) {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
// Organization represents a collaboration organization for cross-tenant sharing
|
// Organization represents a collaboration organization for cross-tenant sharing
|
||||||
type Organization struct {
|
type Organization struct {
|
||||||
// Unique identifier of the organization
|
// Unique identifier of the organization
|
||||||
@@ -70,9 +89,9 @@ type Organization struct {
|
|||||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||||
|
|
||||||
// Associations (not stored in database)
|
// Associations (not stored in database)
|
||||||
Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"`
|
Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"`
|
||||||
Members []OrganizationMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"`
|
Members []OrganizationTenantMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||||
Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"`
|
Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TableName returns the table name for GORM
|
// TableName returns the table name for GORM
|
||||||
@@ -80,31 +99,29 @@ func (Organization) TableName() string {
|
|||||||
return "organizations"
|
return "organizations"
|
||||||
}
|
}
|
||||||
|
|
||||||
// OrganizationMember represents a member of an organization
|
// OrganizationTenantMember represents a tenant participating in an
|
||||||
type OrganizationMember struct {
|
// organization. Plan 3 of #1303 lifts the "Org member" abstraction from
|
||||||
// Unique identifier
|
// per-user (`organization_members`) to per-tenant (this table). The
|
||||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
// representative_user_id is informational only — the user who first
|
||||||
// Organization ID
|
// brought this tenant into the org — and is used purely for UI/audit
|
||||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
// labels. Permission checks are driven exclusively by (org, tenant, role).
|
||||||
// User ID of the member
|
type OrganizationTenantMember struct {
|
||||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
|
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||||
// Tenant ID that the member belongs to
|
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||||
// Role in the organization (admin/editor/viewer)
|
Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||||
Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
RepresentativeUserID string `json:"representative_user_id" gorm:"type:varchar(36);default:''"`
|
||||||
// Creation time
|
JoinedAt *time.Time `json:"joined_at"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
// Last updated time
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
|
||||||
|
|
||||||
// Associations (not stored in database)
|
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
RepresentativeUser *User `json:"representative_user,omitempty" gorm:"foreignKey:RepresentativeUserID"`
|
||||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TableName returns the table name for GORM
|
// TableName returns the table name for GORM
|
||||||
func (OrganizationMember) TableName() string {
|
func (OrganizationTenantMember) TableName() string {
|
||||||
return "organization_members"
|
return "organization_tenant_members"
|
||||||
}
|
}
|
||||||
|
|
||||||
// JoinRequestStatus represents the status of a join request
|
// JoinRequestStatus represents the status of a join request
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ DROP TABLE IF EXISTS tenant_disabled_shared_agents;
|
|||||||
DROP TABLE IF EXISTS agent_shares;
|
DROP TABLE IF EXISTS agent_shares;
|
||||||
DROP TABLE IF EXISTS organization_join_requests;
|
DROP TABLE IF EXISTS organization_join_requests;
|
||||||
DROP TABLE IF EXISTS kb_shares;
|
DROP TABLE IF EXISTS kb_shares;
|
||||||
DROP TABLE IF EXISTS organization_members;
|
DROP TABLE IF EXISTS organization_tenant_members;
|
||||||
DROP TABLE IF EXISTS organizations;
|
DROP TABLE IF EXISTS organizations;
|
||||||
DROP TABLE IF EXISTS custom_agents;
|
DROP TABLE IF EXISTS custom_agents;
|
||||||
DROP TABLE IF EXISTS mcp_tool_approvals;
|
DROP TABLE IF EXISTS mcp_tool_approvals;
|
||||||
|
|||||||
@@ -392,20 +392,20 @@ CREATE TABLE IF NOT EXISTS organizations (
|
|||||||
CREATE INDEX IF NOT EXISTS idx_organizations_owner_id ON organizations(owner_id);
|
CREATE INDEX IF NOT EXISTS idx_organizations_owner_id ON organizations(owner_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_organizations_deleted_at ON organizations(deleted_at);
|
CREATE INDEX IF NOT EXISTS idx_organizations_deleted_at ON organizations(deleted_at);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS organization_members (
|
CREATE TABLE IF NOT EXISTS organization_tenant_members (
|
||||||
id VARCHAR(36) PRIMARY KEY,
|
id VARCHAR(36) PRIMARY KEY,
|
||||||
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||||
user_id VARCHAR(36) NOT NULL,
|
|
||||||
tenant_id INTEGER NOT NULL,
|
tenant_id INTEGER NOT NULL,
|
||||||
role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||||
|
representative_user_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||||
|
joined_at DATETIME,
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_members_org_user ON organization_members(organization_id, user_id);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_tenant_members_unique ON organization_tenant_members(organization_id, tenant_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_org_members_user_id ON organization_members(user_id);
|
CREATE INDEX IF NOT EXISTS idx_org_tenant_members_by_tenant ON organization_tenant_members(tenant_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_org_members_tenant_id ON organization_members(tenant_id);
|
CREATE INDEX IF NOT EXISTS idx_org_tenant_members_role ON organization_tenant_members(organization_id, role);
|
||||||
CREATE INDEX IF NOT EXISTS idx_org_members_role ON organization_members(role);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS kb_shares (
|
CREATE TABLE IF NOT EXISTS kb_shares (
|
||||||
id VARCHAR(36) PRIMARY KEY,
|
id VARCHAR(36) PRIMARY KEY,
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
-- Reverse migration for 000045_org_tenant_members.
|
||||||
|
--
|
||||||
|
-- Restore organization_members from the parked _pre_plan3 table and drop
|
||||||
|
-- the new tenant-scoped table. Because we only RENAMEd the original on
|
||||||
|
-- the way up, no data is lost on rollback — the legacy rows are still
|
||||||
|
-- intact under the renamed table.
|
||||||
|
--
|
||||||
|
-- If the parked table no longer exists (e.g. a later destructive
|
||||||
|
-- migration already dropped it), this script falls through gracefully:
|
||||||
|
-- the IF EXISTS guards leave the database in whatever state it was in.
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Reverting Plan 3'; END $$;
|
||||||
|
|
||||||
|
-- Move legacy table back into place.
|
||||||
|
ALTER TABLE IF EXISTS organization_members_pre_plan3 RENAME TO organization_members;
|
||||||
|
|
||||||
|
-- Restore index names so the application code can find them by their
|
||||||
|
-- documented identifiers.
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_org_user_pre_plan3 RENAME TO idx_org_members_org_user;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_user_id_pre_plan3 RENAME TO idx_org_members_user_id;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_tenant_id_pre_plan3 RENAME TO idx_org_members_tenant_id;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_role_pre_plan3 RENAME TO idx_org_members_role;
|
||||||
|
|
||||||
|
-- Drop the new table. The unique/secondary indexes go with it.
|
||||||
|
DROP TABLE IF EXISTS organization_tenant_members;
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Plan 3 reverted'; END $$;
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
-- Migration: 000045_org_tenant_members
|
||||||
|
--
|
||||||
|
-- Plan 3 of issue #1303: lift "organization membership" from per-user to
|
||||||
|
-- per-tenant. Today `organization_members` is keyed on (org_id, user_id) —
|
||||||
|
-- if Alice (tenant T) joins Org X, her tenant-mate Bob has no visibility
|
||||||
|
-- into anything shared into Org X. That breaks the company-level
|
||||||
|
-- collaboration mental model ("our company is in this org") and creates
|
||||||
|
-- inconsistency with `tenant_disabled_shared_agents`, which is already
|
||||||
|
-- tenant-scoped.
|
||||||
|
--
|
||||||
|
-- The new table `organization_tenant_members` is keyed on (org_id,
|
||||||
|
-- tenant_id). One row says "tenant T participates in Org O at role R,
|
||||||
|
-- represented by user U". `representative_user_id` is purely for UI/audit
|
||||||
|
-- ("who from this tenant brought us here"); permission checks use only
|
||||||
|
-- (org_id, tenant_id, role).
|
||||||
|
--
|
||||||
|
-- Backfill policy: collapse all `organization_members` rows for the same
|
||||||
|
-- (org, tenant) into a single new row. Role = the highest role observed
|
||||||
|
-- across the group (admin > editor > viewer). representative_user_id =
|
||||||
|
-- the earliest joiner. `RAISE NOTICE` flags any (org, tenant) that had
|
||||||
|
-- conflicting roles so operators can audit the resolved choice.
|
||||||
|
--
|
||||||
|
-- The old `organization_members` table is RENAMEd to
|
||||||
|
-- `organization_members_pre_plan3` so a `down.sql` rollback can restore
|
||||||
|
-- it. A future destructive migration (gated on
|
||||||
|
-- `weknora.allow_destructive_migration`) will DROP it once the new model
|
||||||
|
-- is settled.
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Starting Plan 3: org members → org tenant members'; END $$;
|
||||||
|
|
||||||
|
-- 1. New table.
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Creating table: organization_tenant_members'; END $$;
|
||||||
|
CREATE TABLE IF NOT EXISTS organization_tenant_members (
|
||||||
|
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||||
|
tenant_id INTEGER NOT NULL,
|
||||||
|
role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||||
|
representative_user_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||||
|
joined_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_tenant_members_unique
|
||||||
|
ON organization_tenant_members (organization_id, tenant_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_org_tenant_members_by_tenant
|
||||||
|
ON organization_tenant_members (tenant_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_org_tenant_members_role
|
||||||
|
ON organization_tenant_members (organization_id, role);
|
||||||
|
|
||||||
|
COMMENT ON TABLE organization_tenant_members IS 'Plan 3: Tenants (not users) are organization members.';
|
||||||
|
COMMENT ON COLUMN organization_tenant_members.role IS 'Tenant role inside the org: admin | editor | viewer.';
|
||||||
|
COMMENT ON COLUMN organization_tenant_members.representative_user_id IS 'Display-only: the user who first brought this tenant into the org.';
|
||||||
|
|
||||||
|
-- 2. Surface conflicting roles before backfilling so operators see them
|
||||||
|
-- in the migration log. The collapse strategy is "max role wins"
|
||||||
|
-- (admin > editor > viewer); this is a permission *promotion* for
|
||||||
|
-- any user who was at a lower role inside their tenant, so we shout
|
||||||
|
-- loudly when it happens.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
rec RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR rec IN
|
||||||
|
SELECT organization_id, tenant_id,
|
||||||
|
COUNT(*) AS user_count,
|
||||||
|
ARRAY_AGG(DISTINCT role) AS observed_roles,
|
||||||
|
CASE
|
||||||
|
WHEN BOOL_OR(role = 'admin') THEN 'admin'
|
||||||
|
WHEN BOOL_OR(role = 'editor') THEN 'editor'
|
||||||
|
ELSE 'viewer'
|
||||||
|
END AS resolved_role
|
||||||
|
FROM organization_members
|
||||||
|
GROUP BY organization_id, tenant_id
|
||||||
|
LOOP
|
||||||
|
IF rec.user_count > 1 AND ARRAY_LENGTH(rec.observed_roles, 1) > 1 THEN
|
||||||
|
RAISE NOTICE '[Migration 000045] dedup org=% tenant=% chose role=% from observed=%, user_count=%',
|
||||||
|
rec.organization_id, rec.tenant_id, rec.resolved_role, rec.observed_roles, rec.user_count;
|
||||||
|
END IF;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 3. Backfill the new table from the old one.
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Backfilling organization_tenant_members from organization_members'; END $$;
|
||||||
|
INSERT INTO organization_tenant_members (
|
||||||
|
organization_id, tenant_id, role, representative_user_id, joined_at, created_at, updated_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
om.organization_id,
|
||||||
|
om.tenant_id,
|
||||||
|
CASE
|
||||||
|
WHEN BOOL_OR(om.role = 'admin') THEN 'admin'
|
||||||
|
WHEN BOOL_OR(om.role = 'editor') THEN 'editor'
|
||||||
|
ELSE 'viewer'
|
||||||
|
END AS role,
|
||||||
|
-- Representative: earliest joiner in the group, fallback to lowest user_id
|
||||||
|
-- so the choice is deterministic across re-runs.
|
||||||
|
(SELECT om2.user_id
|
||||||
|
FROM organization_members om2
|
||||||
|
WHERE om2.organization_id = om.organization_id
|
||||||
|
AND om2.tenant_id = om.tenant_id
|
||||||
|
ORDER BY om2.created_at ASC, om2.user_id ASC
|
||||||
|
LIMIT 1) AS representative_user_id,
|
||||||
|
MIN(om.created_at) AS joined_at,
|
||||||
|
CURRENT_TIMESTAMP,
|
||||||
|
CURRENT_TIMESTAMP
|
||||||
|
FROM organization_members om
|
||||||
|
GROUP BY om.organization_id, om.tenant_id
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
-- 4. Park the old table so `down.sql` can restore it. We do NOT drop it
|
||||||
|
-- here so a botched rollout can be reversed without re-creating data.
|
||||||
|
-- A follow-up destructive migration removes it in a later release.
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Renaming organization_members → organization_members_pre_plan3'; END $$;
|
||||||
|
ALTER TABLE organization_members RENAME TO organization_members_pre_plan3;
|
||||||
|
|
||||||
|
-- The unique-index name must move with the table; renaming the table does
|
||||||
|
-- not rename the indices in older PG versions, so do it explicitly.
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_org_user RENAME TO idx_org_members_org_user_pre_plan3;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_user_id RENAME TO idx_org_members_user_id_pre_plan3;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_tenant_id RENAME TO idx_org_members_tenant_id_pre_plan3;
|
||||||
|
ALTER INDEX IF EXISTS idx_org_members_role RENAME TO idx_org_members_role_pre_plan3;
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Plan 3 setup ready'; END $$;
|
||||||
Reference in New Issue
Block a user