Skip to content
Merged
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
20 changes: 20 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,26 @@ The payload of a `PostgresChangesMessage` is a `PostgresChangesPayload` model wi
- `sign_out("others")` raises `AuthSessionMissingError` when there is no session, instead of returning.
- An invalid scope raises `ValueError`.

## Auth admin `list_users()` returns a page

`admin.list_users()` returns a `UserList` instead of a `list[User]`. The users are in `users`, next to the `next_page`, `last_page` and `total` the auth service sends.

| Before | After |
| ---------------------------------- | ------------------------------------------ |
| `users = admin.list_users()` | `users = admin.list_users().users` |
| `users = await admin.list_users()` | `users = (await admin.list_users()).users` |

To go through every user, `iter_users()` on the sync client and `aiter_users()` on the async client fetch one page at a time.

```python
from supabase_auth import SyncSupabaseAuthAdmin


def print_emails(admin: SyncSupabaseAuthAdmin) -> None:
for user in admin.iter_users(per_page=100):
print(user.email)
```

## Request timeouts

`AsyncStorageClient` and `SyncStorageClient` no longer take a `timeout` parameter. It was ignored. Pass `request_timeout` as a keyword argument instead.
Expand Down
3 changes: 3 additions & 0 deletions sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,11 @@ features:
status: implemented
symbols:
- SupabaseAuthAdmin.list_users
- SyncSupabaseAuthAdmin.iter_users
- AsyncSupabaseAuthAdmin.aiter_users
supporting_symbols:
- UserList
- Pagination
auth.admin.invite_user:
status: implemented
symbols:
Expand Down
2 changes: 2 additions & 0 deletions src/auth/scripts/run-unasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
additional_replacements={
"AsyncClient": "Client",
"aclose": "close",
"aiter_users": "iter_users",
"anext": "next",
"AsyncHttpSession": "HttpSession",
"AsyncHttpxSession": "HttpxSession",
"async_http_sessions": "sync_http_sessions",
Expand Down
72 changes: 47 additions & 25 deletions src/auth/src/supabase_auth/admin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
_redirect_to_as_query,
_validate_adapter,
_validate_model,
_validate_paginated_model,
parse_link_response,
parse_user_response,
validate_uuid,
Expand All @@ -44,6 +45,7 @@
from .version import __version__

if TYPE_CHECKING:
from collections.abc import AsyncIterator, Iterator
from types import TracebackType

from supabase_utils.http.retry import RetryPolicy
Expand Down Expand Up @@ -128,28 +130,7 @@ def list_clients(
query=query,
)

result = _validate_model(response, OAuthClientListResponse)

# Parse pagination headers
total = response.headers.get("x-total-count")
if total:
result.total = int(total)

links = response.headers.get("link")
if links:
for link in links.split(","):
parts = link.split(";")
if len(parts) >= 2:
page_match = parts[0].split("page=")
if len(page_match) >= 2:
page_num = int(page_match[1].split("&")[0].rstrip(">"))
rel = parts[1].split("=")[1].strip('"')
if rel == "next":
result.next_page = page_num
elif rel == "last":
result.last_page = page_num

return result
return _validate_paginated_model(response, OAuthClientListResponse)

@handle_http_io
def create_client(
Expand Down Expand Up @@ -320,9 +301,13 @@ def create_user(self, attributes: AdminUserAttributes) -> HttpMethod[UserRespons
@handle_http_io
def list_users(
self, page: int | None = None, per_page: int | None = None
) -> HttpMethod[list[User]]:
) -> HttpMethod[UserList]:
"""
Get a list of users.
Get a page of users, together with the next page, the last page and
the total number of users.

Use `iter_users` on the sync client or `aiter_users` on the async
client to go through every user without handling pages.

This function should only be called on a server.
Never expose your `service_role` key in the browser.
Expand All @@ -338,7 +323,7 @@ def list_users(
path=["admin", "users"],
query=query,
)
return _validate_model(response, UserList).users
return _validate_paginated_model(response, UserList)

@handle_http_io
def get_user_by_id(self, user_id: str) -> HttpMethod[UserResponse]:
Expand Down Expand Up @@ -415,6 +400,24 @@ def __init__(
else Headers.empty(),
)

def iter_users(self, per_page: int | None = None) -> Iterator[User]:
"""
Iterate over every user, fetching one page at a time as the iteration
reaches it. Pages are numbered, so users created or deleted while
iterating can shift the pages and be skipped or returned twice.

This function should only be called on a server.
Never expose your `service_role` key in the browser.
"""
page: int | None = 1
while page is not None:
result = self.list_users(page=page, per_page=per_page)
yield from result.users
next_page = result.next_page
page = (
next_page if result.users and next_page and next_page > page else None
)

def __enter__(self) -> Self:
self.executor.session.__enter__()
return self
Expand Down Expand Up @@ -448,6 +451,25 @@ def __init__(
else Headers.empty(),
)

async def aiter_users(self, per_page: int | None = None) -> AsyncIterator[User]:
"""
Iterate over every user, fetching one page at a time as the iteration
reaches it. Pages are numbered, so users created or deleted while
iterating can shift the pages and be skipped or returned twice.

This function should only be called on a server.
Never expose your `service_role` key in the browser.
"""
page: int | None = 1
while page is not None:
result = await self.list_users(page=page, per_page=per_page)
for user in result.users:
yield user
next_page = result.next_page
page = (
next_page if result.users and next_page and next_page > page else None
)

async def __aenter__(self) -> Self:
await self.executor.session.__aenter__()
return self
Expand Down
26 changes: 26 additions & 0 deletions src/auth/src/supabase_auth/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
JWTHeader,
JWTPayload,
LinkIdentityResponse,
Pagination,
Session,
SSOResponse,
User,
Expand Down Expand Up @@ -126,6 +127,31 @@ def _validate_model[Model: BaseModel](response: Response, model: type[Model]) ->
raise _handle_error_response(response)


def _validate_paginated_model[Model: Pagination](
response: Response, model: type[Model]
) -> Model:
result = _validate_model(response, model)
total = (response.headers.get("x-total-count") or "").strip()
if total.isdigit():
result.total = int(total)
for link in (response.headers.get("link") or "").split(","):
target, _, parameters = link.partition(";")
query = dict(parse_qsl(urlsplit(target.strip().strip("<>")).query))
page = query.get("page", "")
if not page.isdigit():
continue
for parameter in parameters.split(";"):
key, _, value = parameter.partition("=")
if key.strip() != "rel":
continue
rel = value.strip().strip('"')
if rel == "next":
result.next_page = int(page)
elif rel == "last":
result.last_page = int(page)
return result


def _validate_adapter[Inner](response: Response, adapter: TypeAdapter[Inner]) -> Inner:
if response.is_success:
return adapter.validate_json(response.content)
Expand Down
32 changes: 17 additions & 15 deletions src/auth/src/supabase_auth/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,23 @@ class IdentitiesResponse(BaseModel):
identities: list[UserIdentity]


class UserList(BaseModel):
class Pagination(BaseModel):
"""
Pagination information for list responses.
"""

next_page: int | None = None
last_page: int = 0
total: int = 0


class UserList(Pagination):
"""
A page of users with the pagination information of the full list.
"""

users: list[User]
aud: str | None = None


class UserResponse(BaseModel):
Expand Down Expand Up @@ -1193,24 +1208,11 @@ class OAuthClientResponse(BaseModel):
client: OAuthClient | None = None


class Pagination(BaseModel):
"""
Pagination information for list responses.
"""

next_page: int | None = None
last_page: int = 0
total: int = 0


class OAuthClientListResponse(BaseModel):
class OAuthClientListResponse(Pagination):
"""
Response type for listing OAuth clients.
Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
"""

clients: list[OAuthClient] = Field(default_factory=list)
aud: str | None = None
next_page: int | None = None
last_page: int = 0
total: int = 0
11 changes: 6 additions & 5 deletions src/auth/tests/_async/test_gotrue_admin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ async def test_list_users_should_return_registered_users(
],
) -> None:
(admin_client, _user, credentials) = admin_client_with_user_and_credentials
users = await admin_client.list_users()
assert users
emails = [user.email for user in users]
response = await admin_client.list_users()
assert response.users
assert response.total >= len(response.users)
emails = [user.email for user in response.users]
assert emails
assert credentials.email in emails

Expand Down Expand Up @@ -203,10 +204,10 @@ async def test_delete_user_should_be_able_delete_an_existing_user(
)
assert response.user.email == credentials.email
users = await secret_key_api_client.list_users()
assert response.user.email in [user.email for user in users]
assert response.user.email in [user.email for user in users.users]
await secret_key_api_client.delete_user(response.user.id)
users = await secret_key_api_client.list_users()
assert response.user.email not in [user.email for user in users]
assert response.user.email not in [user.email for user in users.users]


async def test_generate_link_supports_sign_up_with_generate_confirmation_signup_link(
Expand Down
Loading
Loading