Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import { DashboardBody } from '@/components/Layout/DashboardLayout'
import { Modal } from '@/components/Modal'
import { useModal } from '@/components/Modal/useModal'
import { useToast } from '@/components/Toast/use-toast'
import { useAuth } from '@/hooks/auth'
import {
useInviteOrganizationMember,
useListOrganizationMembers,
useRemoveOrganizationMember,
} from '@/hooks/queries/org'
import Add from '@mui/icons-material/Add'
import ClearOutlined from '@mui/icons-material/ClearOutlined'
import { schemas } from '@polar-sh/client'
import Avatar from '@polar-sh/ui/components/atoms/Avatar'
import Button from '@polar-sh/ui/components/atoms/Button'
Expand All @@ -26,6 +29,7 @@ export default function ClientPage({
}: {
organization: schemas['Organization']
}) {
const { currentUser } = useAuth()
const { data: members, isLoading } = useListOrganizationMembers(
organization.id,
)
Expand All @@ -34,6 +38,24 @@ export default function ClientPage({
hide: hideInviteMemberModal,
isShown: isInviteMemberModalShown,
} = useModal()
const {
show: openRemoveMemberModal,
hide: hideRemoveMemberModal,
isShown: isRemoveMemberModalShown,
} = useModal()
const [memberToRemove, setMemberToRemove] =
useState<schemas['OrganizationMember'] | null>(null)

const handleRemoveClick = (member: schemas['OrganizationMember']) => {
setMemberToRemove(member)
openRemoveMemberModal()
}

// Check if the current user is the admin
const currentUserMember = members?.items.find(
(m) => currentUser && m.user_id === currentUser.id,
)
const isCurrentUserAdmin = currentUserMember?.is_admin ?? false

const columns: DataTableColumnDef<schemas['OrganizationMember']>[] = [
{
Expand All @@ -47,7 +69,14 @@ export default function ClientPage({
return (
<div className="flex flex-row items-center gap-2">
<Avatar avatar_url={member.avatar_url} name={member.email} />
<div className="fw-medium">{member.email}</div>
<div className="fw-medium">
{member.email}
{member.is_admin && (
<span className="dark:text-polar-500 ml-2 text-sm text-gray-500">
(Admin)
</span>
)}
</div>
</div>
)
},
Expand All @@ -62,6 +91,29 @@ export default function ClientPage({
return <FormattedDateTime datetime={member.created_at} />
},
},
{
id: 'actions',
cell: ({ row: { original: member } }) => {
// Only show remove button if current user is admin and the member is not an admin
if (!isCurrentUserAdmin || member.is_admin) {
return null
}
return (
<div className="flex justify-end">
<Button
className={
'border-none bg-transparent text-[16px] opacity-50 transition-opacity hover:opacity-100 dark:bg-transparent'
}
size="icon"
variant="secondary"
onClick={() => handleRemoveClick(member)}
>
<ClearOutlined fontSize="inherit" />
</Button>
</div>
)
},
},
]

return (
Expand Down Expand Up @@ -100,6 +152,19 @@ export default function ClientPage({
isShown={isInviteMemberModalShown}
hide={hideInviteMemberModal}
/>

<Modal
className="max-w-(--breakpoint-sm)!"
modalContent={
<RemoveMemberModal
organizationId={organization.id}
member={memberToRemove}
onClose={hideRemoveMemberModal}
/>
}
isShown={isRemoveMemberModalShown}
hide={hideRemoveMemberModal}
/>
</DashboardBody>
)
}
Expand Down Expand Up @@ -170,3 +235,69 @@ function InviteMemberModal({
</div>
)
}

function RemoveMemberModal({
organizationId,
member,
onClose,
}: {
organizationId: string
member: schemas['OrganizationMember'] | null
onClose: () => void
}) {
const { toast } = useToast()
const removeMember = useRemoveOrganizationMember(organizationId)

const handleRemove = async () => {
if (!member) return

try {
const result = await removeMember.mutateAsync(member.user_id)
if (result.error) {
toast({
title: 'Failed to remove member',
description:
result.error.detail || 'Failed to remove member. Please try again.',
variant: 'destructive',
})
} else {
toast({
title: 'Member removed',
description: `${member.email} has been removed from the organization`,
})
onClose()
}
} catch (error) {
toast({
title: 'Failed to remove member',
description: 'An unexpected error occurred. Please try again.',
variant: 'destructive',
})
}
}

if (!member) return null

return (
<div className="flex w-full flex-col gap-y-6 p-8">
<h3 className="text-lg font-medium">Remove Member</h3>
<p className="dark:text-polar-400 text-gray-600">
Are you sure you want to remove <strong>{member.email}</strong> from
this organization? They will lose access to all organization resources.
</p>
<div className="flex gap-2">
<Button
onClick={handleRemove}
disabled={removeMember.isPending}
loading={removeMember.isPending}
variant="destructive"
>
Remove Member
</Button>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
</div>
</div>
)
}
14 changes: 14 additions & 0 deletions clients/apps/web/src/hooks/queries/org.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ export const useInviteOrganizationMember = (id: string) =>
},
})

export const useRemoveOrganizationMember = (id: string) =>
useMutation({
mutationFn: (userId: string) => {
return api.DELETE('/v1/organizations/{id}/members/{user_id}', {
params: { path: { id, user_id: userId } },
})
},
onSuccess: async (_result, _variables, _ctx) => {
queryClient.invalidateQueries({
queryKey: ['organizationMembers', id],
})
},
})

export const useListOrganizations = (
params: operations['organizations:list']['parameters']['query'],
enabled: boolean = true,
Expand Down
80 changes: 79 additions & 1 deletion server/polar/organization/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import cast
from uuid import UUID

from fastapi import Depends, Query, Response, status
from sqlalchemy.orm import joinedload
Expand Down Expand Up @@ -266,15 +267,38 @@ async def members(
session: AsyncReadSession = Depends(get_db_read_session),
) -> ListResource[OrganizationMember]:
"""List members in an organization."""
from polar.organization.repository import OrganizationRepository

organization = await organization_service.get(session, auth_subject, id)

if organization is None:
raise ResourceNotFound()

members = await user_organization_service.list_by_org(session, id)

# Get admin user to mark them in the response
admin_user_id = None
if organization.account_id:
org_repo = OrganizationRepository.from_session(session)
admin_user = await org_repo.get_admin_user(
cast(AsyncSession, session), organization
)
if admin_user:
admin_user_id = admin_user.id

items = []
for m in members:
# Create a dict with all the necessary fields
member_data = {
"user_id": m.user_id,
"created_at": m.created_at,
"user": {"email": m.user.email, "avatar_url": m.user.avatar_url},
"is_admin": m.user_id == admin_user_id,
}
items.append(OrganizationMember.model_validate(member_data))

return ListResource(
items=[OrganizationMember.model_validate(m) for m in members],
items=items,
pagination=Pagination(total_count=len(members), max_page=1),
)

Expand Down Expand Up @@ -344,6 +368,60 @@ async def invite_member(
return OrganizationMember.model_validate(user_org)


@router.delete(
"/{id}/members/{user_id}",
status_code=204,
tags=[APITag.private],
)
async def remove_member(
id: OrganizationID,
user_id: UUID,
auth_subject: auth.OrganizationsWrite,
session: AsyncSession = Depends(get_db_session),
) -> None:
"""Remove a member from an organization.

Only the organization admin can remove members.
Non-admin members cannot be removed by other members.

Raises:
404: Organization not found or user is not a member
403: Only admin can remove members, or cannot remove organization admin
"""
from polar.organization.repository import OrganizationRepository
from polar.user_organization.service import (
CannotRemoveOrganizationAdmin,
OrganizationNotFound,
UserNotMemberOfOrganization,
)

organization = await organization_service.get(session, auth_subject, id)

if organization is None:
raise ResourceNotFound()

# Check if the authenticated user is the organization admin
if not is_user(auth_subject):
raise NotPermitted("Only users can remove members")

org_repo = OrganizationRepository.from_session(session)
admin_user = await org_repo.get_admin_user(session, organization)

if not admin_user or admin_user.id != auth_subject.subject.id:
raise NotPermitted("Only the organization admin can remove members")

try:
await user_organization_service.remove_member_safe(
session, user_id, organization.id
)
except OrganizationNotFound:
raise ResourceNotFound()
except UserNotMemberOfOrganization:
raise ResourceNotFound()
except CannotRemoveOrganizationAdmin:
raise NotPermitted("Cannot remove organization admin")


@router.post(
"/{id}/ai-validation",
response_model=OrganizationReviewStatus,
Expand Down
5 changes: 5 additions & 0 deletions server/polar/user_organization/schemas.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
from datetime import datetime
from uuid import UUID

from pydantic import AliasPath, EmailStr, Field

from polar.kit.schemas import Schema


class OrganizationMember(Schema):
user_id: UUID = Field(description="The user ID of the organization member")
created_at: datetime = Field(
description="The time the OrganizationMember was creatd."
)
email: str = Field(validation_alias=AliasPath("user", "email"))
avatar_url: str | None = Field(validation_alias=AliasPath("user", "avatar_url"))
is_admin: bool = Field(
default=False, description="Whether the member is the organization admin"
)


class OrganizationMemberInvite(Schema):
Expand Down
Loading