Skip to content

Commit

Permalink
Add superuser endpoint to get user emails with org info (#2211)
Browse files Browse the repository at this point in the history
Fixes #2203

---------

Co-authored-by: Ilya Kreymer <[email protected]>
  • Loading branch information
tw4l and ikreymer authored Dec 10, 2024
1 parent b041baf commit b7604ee
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 1 deletion.
15 changes: 15 additions & 0 deletions backend/btrixcloud/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ class UserOut(BaseModel):
orgs: List[UserOrgInfoOut]


# ============================================================================
class UserEmailWithOrgInfo(BaseModel):
"""Output model for getting user email list with org info for each"""

email: EmailStr
orgs: List[UserOrgInfoOut]


# ============================================================================

### CRAWL STATES
Expand Down Expand Up @@ -2453,3 +2461,10 @@ class PaginatedCrawlErrorResponse(PaginatedResponse):
"""Response model for crawl errors"""

items: List[CrawlError]


# ============================================================================
class PaginatedUserEmailsResponse(PaginatedResponse):
"""Response model for user emails with org info"""

items: List[UserEmailWithOrgInfo]
45 changes: 44 additions & 1 deletion backend/btrixcloud/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from uuid import UUID, uuid4
import asyncio

from typing import Optional, List, TYPE_CHECKING, cast, Callable
from typing import Optional, List, TYPE_CHECKING, cast, Callable, Tuple

from fastapi import (
Request,
Expand Down Expand Up @@ -34,6 +34,8 @@
FailedLogin,
UpdatedResponse,
SuccessResponse,
UserEmailWithOrgInfo,
PaginatedUserEmailsResponse,
)
from .pagination import DEFAULT_PAGE_SIZE, paginated_format
from .utils import is_bool, dt_now
Expand Down Expand Up @@ -546,6 +548,30 @@ async def get_failed_logins_count(self, email: str) -> int:
return 0
return failed_login.get("count", 0)

async def get_user_emails(
self,
page_size: int = DEFAULT_PAGE_SIZE,
page: int = 1,
) -> Tuple[List[UserEmailWithOrgInfo], int]:
"""Get user emails with org info for each for paginated endpoint"""
# Zero-index page for query
page = page - 1
skip = page_size * page

emails: List[UserEmailWithOrgInfo] = []

total = await self.users.count_documents({"is_superuser": False})
async for res in self.users.find(
{"is_superuser": False}, skip=skip, limit=page_size
):
user = User(**res)
user_out = await self.get_user_info_with_orgs(user)
emails.append(
UserEmailWithOrgInfo(email=user_out.email, orgs=user_out.orgs)
)

return emails, total


# ============================================================================
def init_user_manager(mdb, emailsender, invites):
Expand Down Expand Up @@ -706,4 +732,21 @@ async def get_pending_invites(
)
return paginated_format(pending_invites, total, page, pageSize)

@users_router.get(
"/emails", tags=["users"], response_model=PaginatedUserEmailsResponse
)
async def get_user_emails(
user: User = Depends(current_active_user),
pageSize: int = DEFAULT_PAGE_SIZE,
page: int = 1,
):
"""Get emails of registered users with org information (superuser only)"""
if not user.is_superuser:
raise HTTPException(status_code=403, detail="not_allowed")

emails, total = await user_manager.get_user_emails(
page_size=pageSize, page=page
)
return paginated_format(emails, total, page, pageSize)

return users_router
39 changes: 39 additions & 0 deletions backend/test/test_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,3 +774,42 @@ def test_patch_me_invalid_email_in_use(admin_auth_headers, default_org_id):
)
assert r.status_code == 400
assert r.json()["detail"] == "user_already_exists"


def test_user_emails_endpoint_non_superuser(crawler_auth_headers, default_org_id):
r = requests.get(
f"{API_PREFIX}/users/emails",
headers=crawler_auth_headers,
)
assert r.status_code == 403
assert r.json()["detail"] == "not_allowed"


def test_user_emails_endpoint_superuser(admin_auth_headers, default_org_id):
r = requests.get(
f"{API_PREFIX}/users/emails",
headers=admin_auth_headers,
)
assert r.status_code == 200
data = r.json()

total = data["total"]
user_emails = data["items"]

assert total > 0
assert total == len(user_emails)

for user in user_emails:
assert user["email"]
orgs = user.get("orgs")
if orgs == []:
continue

for org in orgs:
assert org["id"]
assert org["name"]
assert org["slug"]
assert org["default"] in (True, False)
role = org["role"]
assert role
assert isinstance(role, int)
1 change: 1 addition & 0 deletions backend/test_nightly/test_storage_quota.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

storage_quota = None


def run_crawl(org_id, headers):
crawl_data = {
"runNow": True,
Expand Down

0 comments on commit b7604ee

Please sign in to comment.