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
147 changes: 147 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,153 @@ datasette install datasette-user-profiles

Usage instructions go here.

## Locking fields users can't edit

Every profile field is user-editable by default. When another part of your
stack is the authoritative source for a field — e.g. a GitHub auth plugin that
already puts the user's `email` (and name, avatar, ...) into the actor JSON —
you can stop users from overwriting it from the profile editor.

Set `editable_fields` in plugin config. Each field defaults to `true`
(editable); list only the ones you want to lock:

```yaml
plugins:
datasette-user-profiles:
editable_fields:
email: false
display_name: false
avatar: false # covers the uploaded photo and the generated icon/color
bio: true
```

Locked fields are enforced server-side — the update and photo endpoints ignore
or reject changes to them, not just hide the inputs — and the edit page renders
them disabled.

## Acting as the actor directory

`datasette-user-profiles` is the canonical user directory for this stack. Every
"who are the users?" surface — the share dialog's add-a-collaborator box,
`@mentions`, acl's actor picker, author chips, audit "shared by" lines — draws
from this one indexed, agent-aware directory rather than maintaining its own
ad-hoc list. It exposes three consumer-facing contracts:

### 1. Search / autocomplete endpoint

```
GET /-/profiles/api/search?q=<text>&limit=<n>&email=<0|1>
```

Gated by the `profile_access` permission (the same gate as every other profile
endpoint). Parameters:

- `q` — free-text query. Matched (case-insensitively) against `display_name`,
`email`, and `actor_id`. Empty/absent `q` returns the most-recently-updated
profiles instead.
- `limit` — max results, defaults to `20`, capped at `50` (and floored at `1`).
- `email` — set to `0`/`false`/`no`/`off` to omit emails from results
(defaults to including them).

Display-name prefix matches rank ahead of contains-only matches, then results
are alphabetical by `display_name`. Response shape:

```json
{
"results": [
{
"id": "alice",
"display_name": "Alice Anderson",
"email": "alice@example.com",
"avatar_url": "/-/profile/pic/alice",
"kind": "user"
}
]
}
```

`kind` is always `"user"` — profiles only knows users. Callers that also want
agents (or other identities) query those sources separately and merge
client-side; profiles stays decoupled from the agent directory.

### 2. `resolve_profile_actors()` output shape

`resolve_profile_actors(datasette, actor_ids)` (see "Actor resolution" below)
returns a `{actor_id: {...}}` map containing only the IDs that have a profile.
Known users resolve to:

```json
{
"id": "alice",
"display_name": "Alice Anderson",
"email": "alice@example.com",
"kind": "user",
"avatar_url": "/-/profile/pic/alice"
}
```

IDs without a matching profile are omitted from the map — the caller decides
how to fall back (typically a bare `{"id": <id>}`).

### Consolidation note

This directory replaces three previously-scattered user-listing mechanisms:

| Old mechanism | Now drawn from |
|---|---|
| acl `datasette_acl_valid_actors` (no query, all actors) | the profiles search API (acl admin UI may keep the hook as a fallback) |
| comments `datasette_comments_users` hook + `startswith` filtering | the profiles search API |
| comments' private `from datasette_user_profiles.routes.pages import get_profile` | `resolve_profile_actors(...)` |

The old hooks keep working for one release as a fallback when profiles is not
installed, then they are retired.

As a cheap convenience, when `datasette-acl` is installed this plugin also
implements acl's `datasette_acl_valid_actors` hook, returning every profile as
an `{"id", "display"}` dict so acl's standalone admin pages get nicer displays.
That hookimpl is only registered if `datasette_acl` is importable, so profiles
has no hard dependency on acl.

## Actor resolution (`resolve_profile_actors`)

This plugin **does not** implement Datasette's core `actors_from_ids` hook.
That hook is declared `firstresult=True`, so the first plugin to implement it
wins and every other identity source (agents, service accounts, remote
directories) is locked out. Rather than silently seize that hook just by being
installed, profiles exposes its resolution logic as a plain function you can
opt into:

```python
from datasette_user_profiles import resolve_profile_actors

actors = await resolve_profile_actors(datasette, ["alice", "agent-1"])
# {"alice": {"id": "alice", "display_name": "Alice Anderson",
# "email": "alice@example.com", "kind": "user",
# "avatar_url": "/-/profile/pic/alice"}}
```

It returns a `{actor_id: {...}}` map for the IDs that have a profile, and omits
the rest so you can merge it with other sources and apply your own fallback.

If you want profiles to back Datasette's core `actors_from_ids`, wire it up
from a plugin you control — designating a single owner for the hook and
choosing how to merge other identity sources:

```python
from datasette import hookimpl
from datasette_user_profiles import resolve_profile_actors

@hookimpl
def actors_from_ids(datasette, actor_ids):
async def inner():
actors = await resolve_profile_actors(datasette, actor_ids)
# ...merge in agents / service accounts / other directories here...
for actor_id in actor_ids:
actors.setdefault(str(actor_id), {"id": str(actor_id)})
return actors
return inner
```

## Development

To set up this plugin locally, first checkout the code. You can confirm it is available like this:
Expand Down
115 changes: 115 additions & 0 deletions datasette_user_profiles/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import json

from datasette import hookimpl
from datasette.permissions import Action
from datasette.plugins import pm
Expand All @@ -19,6 +21,119 @@ def register_routes():
return router.routes()


async def resolve_profile_actors(datasette, actor_ids):
"""Resolve actor IDs to profile actor dictionaries.

Returns a ``{actor_id: {...}}`` map for the IDs that have a matching
profile. IDs without a profile are simply omitted, so callers can merge
this result with other identity sources and apply their own fallback for
anything still unresolved. Each known user resolves to::

{
"id": "alice",
"display_name": "Alice Anderson",
"email": "alice@example.com",
"kind": "user",
"avatar_url": "/-/profile/pic/alice",
}

This plugin deliberately does **not** implement Datasette's core
``actors_from_ids`` plugin hook. That hook is ``firstresult=True``, so any
plugin implementing it locks out every other identity source. Instead, opt
in from your own plugin if you want profiles to back actor resolution::

from datasette import hookimpl
from datasette_user_profiles import resolve_profile_actors

@hookimpl
def actors_from_ids(datasette, actor_ids):
async def inner():
actors = await resolve_profile_actors(datasette, actor_ids)
# merge in your other identity sources here, then default the rest
for actor_id in actor_ids:
actors.setdefault(str(actor_id), {"id": str(actor_id)})
return actors
return inner
"""
ids = [str(a) for a in actor_ids]
if not ids:
return {}

internal_db = datasette.get_internal_database()
rows = (
await internal_db.execute(
"select actor_id, display_name, email"
" from datasette_user_profiles"
" where actor_id in (select value from json_each(:ids))",
{"ids": json.dumps(ids)},
)
).rows
result = {}
for r in rows:
actor_id = r["actor_id"]
result[actor_id] = {
"id": actor_id,
"display_name": r["display_name"],
"email": r["email"],
"kind": "user",
"avatar_url": datasette.urls.path(f"/-/profile/pic/{actor_id}"),
}
return result


def _datasette_acl_installed():
"""True if datasette-acl is importable in this environment."""
try:
import datasette_acl # noqa: F401
except ImportError:
return False
return True


def _valid_actors_impl(datasette):
"""Return every known profile as an acl ``{"id", "display"}`` actor dict.

Shared logic for the optional ``datasette_acl_valid_actors`` hookimpl.
Kept as a standalone function so it can be exercised independently of
whether ``datasette_acl`` is importable.
"""

async def inner():
internal_db = datasette.get_internal_database()
rows = (
await internal_db.execute(
"select actor_id, display_name"
" from datasette_user_profiles"
" order by display_name"
)
).rows
return [
{"id": r["actor_id"], "display": r["display_name"] or r["actor_id"]}
for r in rows
]

return inner


if _datasette_acl_installed():

@hookimpl
def datasette_acl_valid_actors(datasette):
"""Optional: feed acl's actor autocomplete from the profiles directory.

acl's admin UI (group/permission editors) calls
``datasette_acl_valid_actors`` to populate its actor picker. We return
every known profile as an ``{"id", "display"}`` dict so acl's standalone
admin pages get nicer displays without needing the richer search API.

This hookimpl is only registered when ``datasette_acl`` is importable,
so profiles imposes no hard dependency on acl. The share dialog uses the
richer ``/-/profiles/api/search`` endpoint instead of this hook.
"""

return _valid_actors_impl(datasette)


@hookimpl
def extra_template_vars(datasette):
entry = vite_entry(
Expand Down
24 changes: 24 additions & 0 deletions datasette_user_profiles/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Plugin configuration helpers."""

# Profile fields whose user-editability can be toggled via plugin config.
# "avatar" covers both the generated icon/color and an uploaded photo.
EDITABLE_FIELD_NAMES = ("display_name", "bio", "email", "avatar")


def editable_fields(datasette) -> dict[str, bool]:
"""Return a ``{field: bool}`` map of which profile fields users may edit.

Controlled by plugin config. Every field defaults to ``True`` (editable),
so a field is only locked when explicitly turned off. This lets a
deployment whose actor JSON already carries authoritative values (e.g. a
GitHub auth plugin that sets ``email``) stop users from overwriting them::

plugins:
datasette-user-profiles:
editable_fields:
email: false
avatar: false
"""
config = datasette.plugin_config("datasette-user-profiles") or {}
overrides = config.get("editable_fields") or {}
return {name: bool(overrides.get(name, True)) for name in EDITABLE_FIELD_NAMES}
12 changes: 12 additions & 0 deletions datasette_user_profiles/internal_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,15 @@ def m002_avatar_icon_color(db: Database):
ALTER TABLE datasette_user_profiles ADD COLUMN avatar_icon TEXT;
ALTER TABLE datasette_user_profiles ADD COLUMN avatar_color TEXT;
""")


@internal_migrations()
def m003_search_indexes(db: Database):
# Indexes backing the /-/profiles/api/search endpoint so LIKE
# prefix/contains queries stay fast as the directory grows.
db.executescript("""
CREATE INDEX IF NOT EXISTS idx_profiles_display_name
ON datasette_user_profiles(display_name);
CREATE INDEX IF NOT EXISTS idx_profiles_email
ON datasette_user_profiles(email);
""")
17 changes: 17 additions & 0 deletions datasette_user_profiles/page_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class EditProfilePageData(BaseModel):
avatar_icon_choices: list[str] = []
avatar_color_choices: dict[str, str] = {}
avatar_icon_svgs: dict[str, str] = {}
# Which fields the current deployment lets users edit (default all True).
editable: dict[str, bool] = {}


# /-/profiles/ — list all profiles
Expand All @@ -49,6 +51,7 @@ class ProfilesPageData(BaseModel):

# API models


class UpdateProfileRequest(BaseModel):
display_name: str | None = None
bio: str | None = None
Expand Down Expand Up @@ -77,6 +80,20 @@ class DeletePhotoResponse(BaseModel):
error: str | None = None


class SearchResult(BaseModel):
model_config = ConfigDict(coerce_numbers_to_str=True)

id: str
display_name: str | None = None
email: str | None = None
avatar_url: str
kind: str = "user"


class SearchResponse(BaseModel):
results: list[SearchResult] = []


__exports__ = [
ProfilePageData,
EditProfilePageData,
Expand Down
Loading
Loading