* feat(auth): v9 schema — unified role management foundation (WIP)
Tasks 1-5, 10 of the role-management-complete plan. Foundation only,
follow-up commits add REST API, CLI, UI, and tests.
Schema v9:
- user_role_grants table: direct user → internal_role mapping
(complementary to group_mappings). Drives PAT/headless auth and
persists across sessions. Source field tracks 'direct' vs auto-seed.
- internal_roles.implies (JSON): transitive role hierarchy. core.admin
implies core.km_admin → core.analyst → core.viewer. Resolver does BFS
expand at lookup time.
- internal_roles.is_core (BOOL): distinguishes seeded core.* hierarchy
from module-registered roles. UI renders them differently.
- v8→v9 migration: ADD COLUMN, CREATE TABLE, _seed_core_roles +
_backfill_users_role_to_grants, then NULL legacy users.role values.
DuckDB FK constraint blocks DROP COLUMN — sloupec zůstává jako
deprecated artifact (UserRepository ignoruje), fyzický drop deferred.
Resolver:
- Regex extended to allow dotted namespace (core.admin,
context_engineering.admin), max 64 chars total.
- expand_implies(role_keys, conn): BFS over implies JSON column.
- resolve_internal_roles signature gains optional user_id parameter;
unions group-mapping resolution with user_role_grants direct grants
before implies expansion.
require_internal_role:
- Two-path resolution: session cache (OAuth) → DB grants (PAT/headless
fallback). PAT clients now legitimately satisfy gates without the
OAuth round-trip, fixing the v8 limitation where every PAT-callable
admin endpoint needed require_role(Role.ADMIN) instead of
require_internal_role(...).
Backward-compat:
- require_role(Role.X) and require_admin become thin wrappers over
require_internal_role(f"core.{role}"). Implies hierarchy preserves the
legacy "at least this level" semantics automatically — no per-level
comparison code needed.
- src/rbac.py helpers (is_admin, has_role, get_user_role,
set_user_role, can_access_table, get_accessible_tables) all read from
the resolver via _get_internal_role_keys.
- UserRepository.create() and update() now mirror role changes into
user_role_grants via _grant_core_role helper. Preserves API while
making the new table the source of truth.
- UserRepository.delete() pre-deletes user_role_grants rows
(FK cascade — DuckDB doesn't auto-cascade).
- count_admins() reads user_role_grants ⨝ internal_roles instead of the
now-NULL users.role column.
First consumer:
- app/api/admin.py module-level docstring documents the v9 pattern for
future module authors. Existing require_role(Role.ADMIN) callsites
flow through the wrapper; no behavior change for OAuth callers, and
PAT callers gain access via direct grants.
Tests: full suite green (1396 passed, 6 skipped). Existing tests
exercise the new pathway transparently because UserRepository.create
auto-grants. New test_pat_caller_with_direct_grant_passes pins the
PAT-aware contract.
Schema: v9 (was v8). pyproject.toml + CHANGELOG bump deferred to the
final PR-prep commit.
* feat(auth): role management complete — REST API + CLI + UI + docs (v0.11.4)
Sjednocuje legacy users.role enum s v8 internal-roles foundation pod jeden
model s implies hierarchií, dodává admin UI + REST API + CLI pro správu
group mappings i přímých user grants, a dělá require_internal_role
PAT-aware tak, aby admin endpointy fungovaly uniformly napříč OAuth
i headless callery.
REST API (app/api/role_management.py, +496 LOC):
- 8 endpointů pod /api/admin: internal-roles list, group-mappings CRUD,
users/{id}/role-grants CRUD, users/{id}/effective-roles debug.
- Všechny gated require_internal_role("core.admin"). Audit-log na každé
mutaci (role_mapping.created/deleted, role_grant.created/deleted).
- Last-admin protection: refuse to delete the final core.admin grant
(mirrors users.py:count_admins protection).
- Nový UserRoleGrantsRepository v src/repositories/user_role_grants.py.
CLI (cli/commands/admin.py extension, +258 LOC):
- da admin role list / show <key>
- da admin mapping list / create <group-id> <role-key> / delete <id>
- da admin grant-role <email> <role-key>
- da admin revoke-role <email> <role-key>
- da admin effective-roles <email>
- Všechno přes typer + PAT auth, --json flag, response-shape tolerantní.
UI (admin_role_mapping.html + admin_user_detail.html + nav + user list):
- Nová stránka /admin/role-mapping: internal_roles read-only table +
group_mappings table with create/delete forms.
- Nová stránka /admin/users/{id}: core role single-select + capabilities
multi-checkbox + effective-roles debug (direct + group + expanded).
- Existing user list dostává "Detail" link na novou stránku.
- Nav link na /admin/role-mapping.
Tests: +85 nových testů přes 4 nové soubory:
- test_schema_v9_migration.py (8) — fresh install + v8→v9 backfill +
legacy column NULL semantics + unknown-role fallback + invariants.
- test_api_role_management.py (33) — všech 8 endpointů, happy + error
paths, audit-log assertions, last-admin protection.
- test_cli_admin_role.py (25 + 1 conditional) — typer subcommands,
text + json output, PAT integration smoke.
- test_admin_role_mapping_ui.py (9) + test_admin_user_capabilities_ui.py (10)
— page rendering, auth gating, form contracts, JS hooks.
Full suite: 1482 passed, 6 skipped (was 1396 → +86, žádné regrese).
Docs:
- docs/internal-roles.md kompletní rewrite — odstranil "no UI yet",
přidal hierarchy diagram, dual-path resolution, dotted-namespace
convention, admin workflow přes UI/CLI/REST, refresh semantics
for group mappings vs direct grants, migration notes.
- CLAUDE.md schema v8 → v9.
- CHANGELOG.md [0.11.4] s BREAKING marker pro users.role NULL
semantics + complete Added/Changed/Removed/Internal sekce.
- pyproject.toml: 0.11.3 → 0.11.4.
Sequencing: po mergi tohoto PR Pabu rebasuje pabu/local-dev (PR #72)
na main, jeho schema migrations se posouvají z v9/v10/v11 na v10/v11/v12.
Implementation breakdown:
- Sequential (já): foundation tasks — schema v9, resolver, PAT-aware
require_internal_role, backward-compat wrappers, rbac refactor,
UserRepository auto-grant.
- Parallel sub-agents (3 worktrees, ~10 min): REST API, CLI, UI.
- Sequential (já): integrace, docs/CHANGELOG/version, schema tests,
fullsuite verification.
* fix(auth): address Devin review on PR #73 — three regressions
Three concrete bugs caught in Devin's PR review, all fixed in this commit.
1. **users.role hydration on read** (the big one):
v8→v9 migration NULLs users.role for every existing user, but a long
tail of read sites still inspect user["role"] directly:
- app/web/templates/_app_header.html:15 — admin nav gate
- app/web/templates/_app_header.html:36-37 — role badge in dropdown
- app/web/router.py:319-321 — UserInfo.is_admin/is_analyst/is_privileged
- app/web/router.py:489 — corporate memory is_km_admin
- app/api/catalog.py:54 — admin "see all tables" bypass
- app/api/sync.py:215 — admin "see all sync states" bypass
Without a fix, every existing admin loses the entire admin nav (and
API admin bypasses) immediately after upgrade — a serious regression.
Fix: new helper _hydrate_legacy_role() in app/auth/dependencies.py
maps the highest-level core.* grant back into user["role"] as the
legacy enum string. Called from get_current_user() on both auth paths
(LOCAL_DEV_MODE + JWT/PAT). Idempotent — skips when role is already
populated. Net effect: every pre-v9 callsite keeps working transparently
for both OAuth and PAT callers, with one extra DB round-trip per
authenticated request (same cost as the existing PAT-aware
require_internal_role fallback).
3 regression tests in tests/test_schema_v9_migration.py:
- test_hydration_recovers_role_from_user_role_grants
- test_hydration_returns_highest_grant (multi-grant → highest wins)
- test_hydration_falls_back_to_viewer_when_no_grants (safe fallback)
2. **CLI effective-roles TypeError**:
API returns direct/group as List[Dict] (RoleGrantResponse-shaped),
but the CLI did ', '.join(direct) which raises TypeError on dicts.
Tests masked it because mocks used bare string lists. Replaced
raw .join() with a _names() helper that extracts role_key from
each item, falling back to str() for legacy mock shapes.
3. **UI template field-name mismatch**:
admin_user_detail.html JS reads data.groups but the API serializes
the field as group (singular, per EffectiveRolesResponse pydantic).
Currently benign because the API always returns group:[], but the
field would silently disappear once the group-derived view is wired
up. Added data.group as the primary lookup, kept the legacy aliases
for shape-drift tolerance.
Full suite: 1485 passed (was 1482, +3 hydration tests), 6 skipped, no
regressions.
* fix(auth): Devin review #2 + UX self-service + RBAC docs rename
Three threads landed in one commit because they share the same
auth/role surface and CHANGELOG entry.
Devin review #73 second round (2 actionable findings):
- _hydrate_legacy_role no longer short-circuits on truthy users.role.
The role-management endpoints (POST/DELETE /api/admin/users/{id}/
role-grants + the changeCoreRole UI flow) only mutate
user_role_grants — they don't update the legacy column. The early
return trusted that stale value, so a user downgraded via the new
REST/UI kept role="admin" in their dict on subsequent requests,
which fooled _is_admin_user_dict (src/rbac.py) and the catalog/sync
admin-bypass short-circuits into retaining elevated table access
even though require_internal_role correctly denied the API gates.
Always re-resolves now, making user_role_grants the single source
of truth on every authenticated request. Cost: one DB round-trip
per request — same as the existing PAT-aware fallback. Pinned by
test_hydration_ignores_stale_legacy_role_after_grant_revoke.
- Dev-bypass (app/auth/dependencies.py) and OAuth callback
(app/auth/providers/google.py) now pass user_id to
resolve_internal_roles so direct grants land in
session["internal_roles"] alongside group-mapped roles. Pre-fix,
every admin-gated request fell through to the per-request DB
fallback inside require_internal_role and the dev-bypass log line
read "resolved 0 internal role(s)" for an obviously-admin user.
test_session_internal_roles_populated updated to assert union.
User-visible UX (also addresses local-test feedback):
- HTTP 500 on /admin/users post-v8→v9 migration — UserResponse.role
is required str, but legacy users.role was NULL-ed by the
migration. _to_response in app/api/users.py now routes every dict
through _hydrate_legacy_role; same fix lifts the silent no-op of
last-admin protection in update_user/delete_user (the role-equality
short-circuits would skip the count_admins guard for migrated
admins). Three regression tests under TestAPIUsersPostMigration.
- /profile is now a real self-service detail page for *every*
signed-in user (not just admins). Three new server-side sections:
Effective roles (resolver output as chip cloud), Direct grants
(rows in user_role_grants with source label), Roles via groups
(which Cloud Identity / dev group grants which role for the
current user). Non-admins finally see *why* a feature is or isn't
accessible. Admins additionally see a deep-link to
/admin/users/{id} for editing their own grants.
- /admin/role-mapping group-id picker. New "Known groups" panel
above the create form: clickable chips for the calling admin's
own session.google_groups (tagged "your group") merged with
external_group_ids already used in existing mappings (tagged
"already mapped"). Click a chip → fills the form. Empty-state
copy points operators at LOCAL_DEV_GROUPS / Google sign-in
instead of leaving them to guess Cloud Identity opaque IDs from
memory.
Operational fixes:
- Scheduler log-noise: every cron tick produced a
POST /auth/token 401 because the auto-fetch fallback called the
endpoint with just an email (no password) and silently fell
through. Removed the broken path entirely. Operators set
SCHEDULER_API_TOKEN (long-lived PAT) in production; in
LOCAL_DEV_MODE the dev-bypass auto-authenticates the un-tokenized
request, so jobs continue to work.
Docs:
- docs/internal-roles.md → docs/RBAC.md (git mv preserves history).
Standard industry term, more discoverable for engineers grepping
for RBAC in a new repo. Restructured: Quickstart-by-role
(operator / end-user / module author), step-by-step
Module-author workflow with code examples (register key, gate
endpoint, declare implies, write contract test), naming pitfalls,
refresh semantics. CLAUDE.md gets a new
"Extensibility → RBAC" section pointing contributors at the doc
before they add gated endpoints. Cross-refs in app/api/admin.py
+ tests/test_role_resolver.py updated.
Tests: 293 in the auth/role/scheduler/UI test set passed, 0 regressions.
* fix(auth): Devin review #3 — login flows + RBAC docs
Two new findings on commit 7d1c048, both real and addressed.
Finding 1 (BUG, HTTP 500): every auth login flow loaded users via
UserRepository.get_by_email and passed user["role"] straight to
create_access_token, Pydantic response models, and _set_login_cookie
without going through _hydrate_legacy_role. Post-v9 the legacy column
is NULL for migrated users, and TokenResponse.role is a required str —
so POST /auth/token raised ValidationError → HTTP 500 for any v8-admin
trying to log in via password. Same root cause produced non-crashing
but semantically wrong JWTs (role: null) from Google OAuth, password
web flows, and email magic-link verification.
Fix: hydrate inline in every login flow before reading user["role"]:
- app/auth/router.py — POST /auth/token (the crash site)
- app/auth/providers/google.py — OAuth callback (was just stale JWT)
- app/auth/providers/password.py — 5 flows: JSON login, web login,
JSON setup, web reset confirm, web setup confirm
- app/auth/providers/email.py — centralized in _consume_token,
covers both /verify endpoints
New regression class TestAuthLoginFlowsPostMigration pins both the
no-crash and the correct-role contracts for all four legacy levels
(viewer/analyst/km_admin/admin) on POST /auth/token.
Finding 2 (DOCS): docs/RBAC.md showed register_internal_role() being
called with implies=[...], but the function signature is (key, *,
display_name, description, owner_module). A module author copying the
example would TypeError at import time. The implies field on
internal_roles IS honored at runtime by expand_implies, but the
registry-side write path (register_internal_role + InternalRoleSpec +
sync_registered_roles_to_db) doesn't exist yet — implies is currently
seeded only for the core.* hierarchy via _seed_core_roles in src/db.py.
Rewrote the Implies hierarchy and Module-author workflow sections to
document what's actually supported in 0.11.4 and what a future change
would need to add. The "for cross-module hierarchies, register each
level + grant both" pattern works today.
Tests: 322 in the auth/role/scheduler/UI/password test set passed,
0 regressions.
* fix(db): _seed_core_roles actually runs on every connect (Devin review #4)
Devin flagged that the docstring on `_seed_core_roles` promised per-connect
execution as a safety net for accidental DELETEs and in-code seed changes,
but the only call sites lived inside `if current < SCHEMA_VERSION:` — so
once a DB was on v9 the function never ran again, and the docstring lied.
Picked option (b) from the review (actually call it on every startup) over
option (a) (fix the docstring) because the safety net is genuinely useful:
- recovery from accidental admin DELETE on internal_roles,
- in-code _CORE_ROLES_SEED tweaks (display_name/description/implies)
ship without a manual SQL deploy,
- fresh installs and migrations stop needing their own seed call sites.
Tail call gated by `get_schema_version(conn) <= SCHEMA_VERSION` so the
future-version-is-noop rollback contract still holds — a v9 binary won't
touch a DB that's been upgraded past v9.
Test coverage: new TestSeedCoreRolesSafetyNet class (3 tests) pins the
three contracts — deleted row re-seeds, mutated display_name re-syncs
from in-code seed, applied_at on schema_version doesn't churn on
already-current DBs. Existing TestMigrationSafety::test_future_version_is_noop
still passes (verified against the gating logic).
597 lines
25 KiB
HTML
597 lines
25 KiB
HTML
{% extends "base.html" %}
|
|
{% block title %}Users — {{ config.INSTANCE_NAME }}{% endblock %}
|
|
|
|
{% block content %}
|
|
<style>
|
|
/* Override base.html's 800px .container cap for this wide table. */
|
|
.container:has(.users-page) { max-width: none; padding: 24px 16px; }
|
|
.users-page { max-width: 1400px; margin: 0 auto; padding: 0; }
|
|
.users-toolbar {
|
|
display: flex; justify-content: space-between; align-items: center;
|
|
gap: 16px; margin-bottom: 20px; flex-wrap: wrap;
|
|
}
|
|
.users-title { margin: 0; font-size: 22px; font-weight: 600; }
|
|
.users-search {
|
|
flex: 1; max-width: 360px;
|
|
padding: 8px 12px 8px 36px;
|
|
border: 1px solid var(--border, #e5e7eb);
|
|
border-radius: 8px;
|
|
font-size: 13px;
|
|
background: var(--surface, #fff) url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2'><circle cx='11' cy='11' r='8'/><path d='m21 21-4.35-4.35'/></svg>") no-repeat 12px center;
|
|
}
|
|
.users-search:focus { outline: 2px solid var(--primary, #6366f1); outline-offset: -1px; }
|
|
|
|
.users-table-wrap {
|
|
background: var(--surface, #fff);
|
|
border: 1px solid var(--border, #e5e7eb);
|
|
border-radius: 12px;
|
|
overflow-x: auto;
|
|
}
|
|
.users-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
.users-table thead th {
|
|
text-align: left; padding: 12px 16px;
|
|
background: var(--border-light, #f9fafb);
|
|
border-bottom: 1px solid var(--border, #e5e7eb);
|
|
font-weight: 600; color: var(--text-secondary, #6b7280);
|
|
font-size: 11px; text-transform: uppercase; letter-spacing: 0.4px;
|
|
}
|
|
.users-table tbody td {
|
|
padding: 12px 16px;
|
|
border-bottom: 1px solid var(--border-light, #f3f4f6);
|
|
vertical-align: middle;
|
|
}
|
|
.users-table tbody tr:last-child td { border-bottom: none; }
|
|
.users-table tbody tr.is-deactivated { opacity: 0.55; }
|
|
.users-table tbody tr:hover { background: var(--border-light, #fafafa); }
|
|
|
|
.user-cell { display: flex; align-items: center; gap: 10px; }
|
|
.user-avatar {
|
|
width: 32px; height: 32px; border-radius: 50%;
|
|
display: flex; align-items: center; justify-content: center;
|
|
font-size: 12px; font-weight: 600; color: #fff;
|
|
flex-shrink: 0;
|
|
}
|
|
.user-meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
|
.user-meta .name { font-weight: 500; color: var(--text-primary, #111827); }
|
|
.user-meta .email { font-size: 11px; color: var(--text-secondary, #6b7280); }
|
|
.user-cell.no-name .name { display: none; }
|
|
.user-cell.no-name .email { font-size: 13px; color: var(--text-primary, #111827); font-weight: 500; }
|
|
|
|
.role-pill {
|
|
display: inline-block;
|
|
padding: 3px 10px; border-radius: 999px;
|
|
font-size: 11px; font-weight: 600;
|
|
text-transform: uppercase; letter-spacing: 0.4px;
|
|
cursor: pointer; border: 1px solid transparent;
|
|
}
|
|
.role-pill.role-admin { background: #fee2e2; color: #b91c1c; }
|
|
.role-pill.role-analyst { background: #dbeafe; color: #1e40af; }
|
|
.role-pill.role-km_admin { background: #ede9fe; color: #6d28d9; }
|
|
.role-pill.role-viewer { background: #f3f4f6; color: #4b5563; }
|
|
|
|
/* Toggle switch */
|
|
.toggle { position: relative; display: inline-block; width: 36px; height: 20px; }
|
|
.toggle input { opacity: 0; width: 0; height: 0; }
|
|
.toggle-slider {
|
|
position: absolute; cursor: pointer; inset: 0;
|
|
background: #cbd5e1; border-radius: 999px; transition: 0.2s;
|
|
}
|
|
.toggle-slider::before {
|
|
content: ""; position: absolute; left: 2px; top: 2px;
|
|
width: 16px; height: 16px; background: #fff; border-radius: 50%;
|
|
transition: 0.2s;
|
|
}
|
|
.toggle input:checked + .toggle-slider { background: #10b981; }
|
|
.toggle input:checked + .toggle-slider::before { transform: translateX(16px); }
|
|
.toggle input:focus-visible + .toggle-slider { outline: 2px solid var(--primary, #6366f1); outline-offset: 2px; }
|
|
|
|
.date-cell { color: var(--text-secondary, #6b7280); font-size: 12px; white-space: nowrap; }
|
|
|
|
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
|
|
.icon-btn {
|
|
background: transparent; border: 1px solid var(--border, #e5e7eb); border-radius: 6px;
|
|
padding: 5px 10px; font-size: 12px; cursor: pointer;
|
|
color: var(--text-secondary, #6b7280); transition: all 0.15s;
|
|
text-decoration: none; line-height: 1.4;
|
|
white-space: nowrap;
|
|
}
|
|
.icon-btn:hover { color: var(--text-primary, #111827); border-color: #cbd5e1; background: #f9fafb; }
|
|
.icon-btn.danger:hover { color: #b91c1c; border-color: #fecaca; background: #fef2f2; }
|
|
|
|
.users-empty, .users-loading {
|
|
text-align: center; padding: 48px 16px;
|
|
color: var(--text-secondary, #6b7280); font-size: 13px;
|
|
}
|
|
.users-empty .big { font-size: 15px; color: var(--text-primary, #111827); margin-bottom: 6px; font-weight: 500; }
|
|
|
|
.skeleton-row td { padding: 12px 16px; }
|
|
.skeleton-row .bar {
|
|
background: linear-gradient(90deg, #eef2f7 25%, #e2e8f0 37%, #eef2f7 63%);
|
|
background-size: 400% 100%; animation: skeleton 1.4s ease infinite;
|
|
height: 10px; border-radius: 4px;
|
|
}
|
|
@keyframes skeleton { 0% { background-position: 100% 50% } 100% { background-position: 0 50% } }
|
|
|
|
/* Modal */
|
|
.modal-backdrop {
|
|
position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55);
|
|
display: none; align-items: center; justify-content: center; z-index: 1000;
|
|
padding: 16px;
|
|
}
|
|
.modal-backdrop.is-open { display: flex; }
|
|
.modal-card {
|
|
background: var(--surface, #fff); border-radius: 12px;
|
|
padding: 24px; width: 100%; max-width: 440px;
|
|
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
|
|
}
|
|
.modal-card h3 { margin: 0 0 6px; font-size: 17px; font-weight: 600; }
|
|
.modal-card p.sub { margin: 0 0 18px; font-size: 13px; color: var(--text-secondary, #6b7280); }
|
|
.modal-card label { display: block; font-size: 12px; font-weight: 500; color: var(--text-secondary, #6b7280); margin: 12px 0 6px; }
|
|
.modal-card input[type="text"], .modal-card input[type="email"], .modal-card input[type="password"], .modal-card select {
|
|
width: 100%; padding: 9px 12px; border: 1px solid var(--border, #e5e7eb);
|
|
border-radius: 8px; font-size: 13px; box-sizing: border-box;
|
|
background: var(--surface, #fff); color: var(--text-primary, #111827);
|
|
}
|
|
.modal-card input:focus, .modal-card select:focus { outline: 2px solid var(--primary, #6366f1); outline-offset: -1px; }
|
|
.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 20px; }
|
|
.modal-btn {
|
|
padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 500;
|
|
border: 1px solid var(--border, #e5e7eb); background: var(--surface, #fff);
|
|
cursor: pointer; transition: all 0.15s;
|
|
}
|
|
.modal-btn:hover { background: var(--border-light, #f9fafb); }
|
|
.modal-btn.primary { background: var(--primary, #6366f1); color: #fff; border-color: var(--primary, #6366f1); }
|
|
.modal-btn.primary:hover { filter: brightness(1.05); }
|
|
.modal-btn.danger { background: #dc2626; color: #fff; border-color: #dc2626; }
|
|
.modal-btn.danger:hover { filter: brightness(1.05); }
|
|
|
|
.token-reveal {
|
|
margin: 12px 0;
|
|
padding: 12px; border-radius: 8px;
|
|
background: #fffbeb; border: 1px solid #fcd34d;
|
|
font-family: var(--font-mono, ui-monospace, "SF Mono", Menlo, monospace);
|
|
font-size: 12px; word-break: break-all;
|
|
display: flex; align-items: center; gap: 8px;
|
|
}
|
|
.token-reveal code { flex: 1; }
|
|
.copy-btn {
|
|
background: var(--primary, #6366f1); color: #fff; border: none;
|
|
padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 500;
|
|
cursor: pointer; flex-shrink: 0;
|
|
}
|
|
.copy-btn.copied { background: #10b981; }
|
|
|
|
/* Toast */
|
|
.toast-stack {
|
|
position: fixed; bottom: 24px; right: 24px; z-index: 2000;
|
|
display: flex; flex-direction: column; gap: 8px;
|
|
pointer-events: none;
|
|
}
|
|
.toast {
|
|
background: #111827; color: #fff; padding: 10px 16px;
|
|
border-radius: 8px; font-size: 13px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
|
|
opacity: 0; transform: translateY(8px);
|
|
transition: opacity 0.2s, transform 0.2s;
|
|
pointer-events: auto; max-width: 380px;
|
|
}
|
|
.toast.show { opacity: 1; transform: translateY(0); }
|
|
.toast.success { background: #047857; }
|
|
.toast.error { background: #b91c1c; }
|
|
</style>
|
|
|
|
<div class="users-page">
|
|
<div class="users-toolbar">
|
|
<h2 class="users-title">Users</h2>
|
|
<input id="user-search" type="search" class="users-search" placeholder="Filter by email or name…" autocomplete="off">
|
|
<button class="modal-btn primary" id="open-create-btn">+ Add user</button>
|
|
</div>
|
|
|
|
<div class="users-table-wrap">
|
|
<table class="users-table" id="users-table">
|
|
<thead>
|
|
<tr>
|
|
<th>User</th>
|
|
<th>Role</th>
|
|
<th>Active</th>
|
|
<th>Created</th>
|
|
<th>Deactivated</th>
|
|
<th style="text-align:right">Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="users-tbody"></tbody>
|
|
</table>
|
|
<div id="users-loading" class="users-loading">Loading users…</div>
|
|
<div id="users-empty" class="users-empty" style="display:none;">
|
|
<div class="big">No users yet</div>
|
|
<div>Click <strong>Add user</strong> to invite the first one.</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Create user modal -->
|
|
<div class="modal-backdrop" id="create-modal" role="dialog" aria-modal="true" aria-labelledby="create-modal-title">
|
|
<div class="modal-card">
|
|
<h3 id="create-modal-title">Add user</h3>
|
|
<p class="sub">Invites a new account. When "Send invitation link" is ticked we generate a setup link the user can follow to pick their own password.</p>
|
|
<label for="new-email">Email</label>
|
|
<input id="new-email" type="email" required autocomplete="off">
|
|
<label for="new-name">Name (optional)</label>
|
|
<input id="new-name" type="text" autocomplete="off">
|
|
<label for="new-role">Role</label>
|
|
<select id="new-role">
|
|
<option value="viewer">viewer</option>
|
|
<option value="analyst" selected>analyst</option>
|
|
<option value="km_admin">km_admin</option>
|
|
<option value="admin">admin</option>
|
|
</select>
|
|
<label style="display:flex; align-items:center; gap:8px; margin-top:12px; font-size:13px; color: var(--text-primary, #111827); font-weight:500;">
|
|
<input id="new-send-invite" type="checkbox" checked>
|
|
Send invitation link (generates setup token, emails it if transport is configured)
|
|
</label>
|
|
<div class="modal-actions">
|
|
<button class="modal-btn" data-close-modal="create-modal">Cancel</button>
|
|
<button class="modal-btn primary" id="confirm-create-btn">Create</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Set password modal -->
|
|
<div class="modal-backdrop" id="setpwd-modal" role="dialog" aria-modal="true" aria-labelledby="setpwd-title">
|
|
<div class="modal-card">
|
|
<h3 id="setpwd-title">Set password</h3>
|
|
<p class="sub" id="setpwd-target"></p>
|
|
<label for="setpwd-input">New password (min 8 chars)</label>
|
|
<input id="setpwd-input" type="password" autocomplete="new-password">
|
|
<div class="modal-actions">
|
|
<button class="modal-btn" data-close-modal="setpwd-modal">Cancel</button>
|
|
<button class="modal-btn primary" id="confirm-setpwd-btn">Set password</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Reset URL reveal modal -->
|
|
<div class="modal-backdrop" id="reset-modal" role="dialog" aria-modal="true" aria-labelledby="reset-title">
|
|
<div class="modal-card">
|
|
<h3 id="reset-title">Password reset link</h3>
|
|
<p class="sub" id="reset-target"></p>
|
|
<p class="sub" id="reset-transport-note"></p>
|
|
<div class="token-reveal">
|
|
<code id="reset-token-text"></code>
|
|
<button class="copy-btn" id="reset-copy-btn">Copy</button>
|
|
</div>
|
|
<div class="modal-actions">
|
|
<button class="modal-btn primary" data-close-modal="reset-modal">Done</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Invitation link modal -->
|
|
<div class="modal-backdrop" id="invite-modal" role="dialog" aria-modal="true" aria-labelledby="invite-title">
|
|
<div class="modal-card">
|
|
<h3 id="invite-title">Invitation link</h3>
|
|
<p class="sub" id="invite-target"></p>
|
|
<p class="sub" id="invite-transport-note"></p>
|
|
<div class="token-reveal">
|
|
<code id="invite-url-text"></code>
|
|
<button class="copy-btn" id="invite-copy-btn">Copy</button>
|
|
</div>
|
|
<div class="modal-actions">
|
|
<button class="modal-btn primary" data-close-modal="invite-modal">Done</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Confirm dialog -->
|
|
<div class="modal-backdrop" id="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
|
|
<div class="modal-card">
|
|
<h3 id="confirm-title">Are you sure?</h3>
|
|
<p class="sub" id="confirm-text"></p>
|
|
<div class="modal-actions">
|
|
<button class="modal-btn" data-close-modal="confirm-modal">Cancel</button>
|
|
<button class="modal-btn danger" id="confirm-ok-btn">Confirm</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="toast-stack" id="toast-stack" aria-live="polite"></div>
|
|
|
|
<script>
|
|
const API = "/api/users";
|
|
const ROLES = ["viewer", "analyst", "km_admin", "admin"];
|
|
|
|
function esc(s) {
|
|
const d = document.createElement("div");
|
|
d.textContent = s == null ? "" : String(s);
|
|
return d.innerHTML;
|
|
}
|
|
function fmtDate(s) { return s ? s.slice(0, 16).replace("T", " ") : "—"; }
|
|
function initials(u) {
|
|
const src = (u.name || u.email || "?").trim();
|
|
const parts = src.split(/[\s@.]+/).filter(Boolean);
|
|
return ((parts[0]?.[0] || "?") + (parts[1]?.[0] || "")).toUpperCase();
|
|
}
|
|
function avatarColor(s) {
|
|
// Stable hash → hue
|
|
let h = 0;
|
|
for (const c of s || "") h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
|
return `hsl(${h % 360}, 55%, 50%)`;
|
|
}
|
|
|
|
// ── Toast ──
|
|
function toast(msg, kind = "") {
|
|
const el = document.createElement("div");
|
|
el.className = "toast " + kind;
|
|
el.textContent = msg;
|
|
document.getElementById("toast-stack").appendChild(el);
|
|
requestAnimationFrame(() => el.classList.add("show"));
|
|
setTimeout(() => {
|
|
el.classList.remove("show");
|
|
setTimeout(() => el.remove(), 250);
|
|
}, 3500);
|
|
}
|
|
|
|
// ── Modal helpers ──
|
|
function openModal(id) {
|
|
document.getElementById(id).classList.add("is-open");
|
|
const focusable = document.querySelector(`#${id} input, #${id} select, #${id} button.primary`);
|
|
focusable && focusable.focus();
|
|
}
|
|
function closeModal(id) {
|
|
document.getElementById(id).classList.remove("is-open");
|
|
}
|
|
document.querySelectorAll("[data-close-modal]").forEach(el =>
|
|
el.addEventListener("click", () => closeModal(el.dataset.closeModal)));
|
|
document.querySelectorAll(".modal-backdrop").forEach(el => {
|
|
el.addEventListener("click", e => { if (e.target === el) el.classList.remove("is-open"); });
|
|
});
|
|
document.addEventListener("keydown", e => {
|
|
if (e.key === "Escape") document.querySelectorAll(".modal-backdrop.is-open").forEach(m => m.classList.remove("is-open"));
|
|
});
|
|
|
|
// Generic confirm using the modal — returns a Promise<boolean>
|
|
function confirmModal(text) {
|
|
const modal = document.getElementById("confirm-modal");
|
|
document.getElementById("confirm-text").textContent = text;
|
|
return new Promise(resolve => {
|
|
const okBtn = document.getElementById("confirm-ok-btn");
|
|
const cancel = () => { closeModal("confirm-modal"); cleanup(); resolve(false); };
|
|
const ok = () => { closeModal("confirm-modal"); cleanup(); resolve(true); };
|
|
function cleanup() {
|
|
okBtn.removeEventListener("click", ok);
|
|
modal.removeEventListener("click", backdropCancel);
|
|
}
|
|
function backdropCancel(e) { if (e.target === modal) cancel(); }
|
|
okBtn.addEventListener("click", ok, { once: true });
|
|
modal.addEventListener("click", backdropCancel);
|
|
openModal("confirm-modal");
|
|
});
|
|
}
|
|
|
|
// ── State ──
|
|
let allUsers = [];
|
|
let filterText = "";
|
|
|
|
function renderUsers() {
|
|
const tbody = document.getElementById("users-tbody");
|
|
const loading = document.getElementById("users-loading");
|
|
const empty = document.getElementById("users-empty");
|
|
loading.style.display = "none";
|
|
|
|
const ft = filterText.trim().toLowerCase();
|
|
const filtered = ft
|
|
? allUsers.filter(u => (u.email || "").toLowerCase().includes(ft) || (u.name || "").toLowerCase().includes(ft))
|
|
: allUsers;
|
|
|
|
if (allUsers.length === 0) {
|
|
empty.style.display = "block";
|
|
tbody.innerHTML = "";
|
|
return;
|
|
}
|
|
empty.style.display = "none";
|
|
|
|
if (filtered.length === 0) {
|
|
tbody.innerHTML = `<tr><td colspan="6" class="users-loading">No matches for "${esc(filterText)}"</td></tr>`;
|
|
return;
|
|
}
|
|
|
|
tbody.innerHTML = "";
|
|
for (const u of filtered) {
|
|
const tr = document.createElement("tr");
|
|
if (!u.active) tr.classList.add("is-deactivated");
|
|
const role = u.role || "viewer";
|
|
const hasName = !!(u.name && u.name !== u.email);
|
|
tr.innerHTML = `
|
|
<td>
|
|
<div class="user-cell ${hasName ? "" : "no-name"}">
|
|
<div class="user-avatar" style="background:${avatarColor(u.email || u.id)}">${esc(initials(u))}</div>
|
|
<div class="user-meta">
|
|
<span class="name">${esc(u.name || "")}</span>
|
|
<span class="email">${esc(u.email)}</span>
|
|
</div>
|
|
</div>
|
|
</td>
|
|
<td>
|
|
<span class="role-pill role-${esc(role)}" data-action="edit-role" data-user-id="${esc(u.id)}" title="Click to change role">${esc(role)}</span>
|
|
</td>
|
|
<td>
|
|
<label class="toggle">
|
|
<input type="checkbox" ${u.active ? "checked" : ""} data-action="toggle-active" data-user-id="${esc(u.id)}">
|
|
<span class="toggle-slider"></span>
|
|
</label>
|
|
</td>
|
|
<td class="date-cell">${fmtDate(u.created_at)}</td>
|
|
<td class="date-cell">${u.deactivated_at ? fmtDate(u.deactivated_at) : "—"}</td>
|
|
<td>
|
|
<div class="row-actions">
|
|
<a class="icon-btn" href="/admin/users/${encodeURIComponent(u.id)}" title="Open detail view: roles + capabilities + effective-roles debug">Detail</a>
|
|
<a class="icon-btn" href="/admin/tokens?user=${encodeURIComponent(u.email || "")}" title="View this user's personal access tokens">Tokens</a>
|
|
<button class="icon-btn" data-action="reset-password" data-user-id="${esc(u.id)}" data-user-email="${esc(u.email)}" title="Generate a reset link (user picks their own new password)">Reset</button>
|
|
<button class="icon-btn" data-action="set-password" data-user-id="${esc(u.id)}" data-user-email="${esc(u.email)}" title="Assign a password directly">Set pwd</button>
|
|
<button class="icon-btn danger" data-action="delete-user" data-user-id="${esc(u.id)}" data-user-email="${esc(u.email)}">Delete</button>
|
|
</div>
|
|
</td>`;
|
|
tbody.appendChild(tr);
|
|
}
|
|
|
|
// Wire up actions via delegation-like loop
|
|
tbody.querySelectorAll('[data-action="edit-role"]').forEach(el =>
|
|
el.addEventListener("click", () => editRole(el.dataset.userId)));
|
|
tbody.querySelectorAll('[data-action="toggle-active"]').forEach(el =>
|
|
el.addEventListener("change", () => toggleActive(el.dataset.userId, el.checked)));
|
|
tbody.querySelectorAll('[data-action="reset-password"]').forEach(el =>
|
|
el.addEventListener("click", () => resetPassword(el.dataset.userId, el.dataset.userEmail)));
|
|
tbody.querySelectorAll('[data-action="set-password"]').forEach(el =>
|
|
el.addEventListener("click", () => openSetPassword(el.dataset.userId, el.dataset.userEmail)));
|
|
tbody.querySelectorAll('[data-action="delete-user"]').forEach(el =>
|
|
el.addEventListener("click", () => delUser(el.dataset.userId, el.dataset.userEmail)));
|
|
}
|
|
|
|
async function loadUsers() {
|
|
try {
|
|
const r = await fetch(API, { credentials: "include" });
|
|
if (!r.ok) throw new Error("HTTP " + r.status);
|
|
allUsers = await r.json();
|
|
renderUsers();
|
|
} catch (e) {
|
|
document.getElementById("users-loading").textContent = "Failed to load users: " + e.message;
|
|
toast("Failed to load users", "error");
|
|
}
|
|
}
|
|
|
|
document.getElementById("user-search").addEventListener("input", e => {
|
|
filterText = e.target.value;
|
|
renderUsers();
|
|
});
|
|
|
|
// ── Role editing via cycling pill click ──
|
|
async function editRole(id) {
|
|
const u = allUsers.find(x => x.id === id);
|
|
if (!u) return;
|
|
const next = ROLES[(ROLES.indexOf(u.role || "viewer") + 1) % ROLES.length];
|
|
if (!await confirmModal(`Change role for ${u.email} from "${u.role}" to "${next}"?`)) return;
|
|
await patch(id, { role: next }, `Role changed to ${next}`);
|
|
}
|
|
|
|
async function toggleActive(id, active) {
|
|
const path = active ? "activate" : "deactivate";
|
|
const r = await fetch(`${API}/${id}/${path}`, { method: "POST", credentials: "include" });
|
|
if (!r.ok) {
|
|
toast("Failed: " + (await r.text()), "error");
|
|
loadUsers();
|
|
return;
|
|
}
|
|
toast(active ? "User activated" : "User deactivated", "success");
|
|
loadUsers();
|
|
}
|
|
|
|
async function patch(id, body, successMsg) {
|
|
const r = await fetch(`${API}/${id}`, {
|
|
method: "PATCH", credentials: "include",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
if (!r.ok) { toast("Failed: " + (await r.text()), "error"); return; }
|
|
toast(successMsg, "success");
|
|
loadUsers();
|
|
}
|
|
|
|
// ── Reset password ──
|
|
async function resetPassword(id, email) {
|
|
if (!await confirmModal(`Generate a password-reset link for ${email}?`)) return;
|
|
const r = await fetch(`${API}/${id}/reset-password`, { method: "POST", credentials: "include" });
|
|
const data = await r.json().catch(() => ({}));
|
|
if (!r.ok) { toast("Failed: " + (data.detail || r.status), "error"); return; }
|
|
document.getElementById("reset-target").textContent = `For ${email}`;
|
|
document.getElementById("reset-transport-note").textContent = data.email_sent
|
|
? "Email sent. Copy the link below only if you need to deliver it manually."
|
|
: "Email transport unavailable — send this link to the user directly.";
|
|
document.getElementById("reset-token-text").textContent = data.reset_url;
|
|
const copyBtn = document.getElementById("reset-copy-btn");
|
|
copyBtn.textContent = "Copy"; copyBtn.classList.remove("copied");
|
|
copyBtn.onclick = async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(data.reset_url);
|
|
copyBtn.textContent = "Copied!"; copyBtn.classList.add("copied");
|
|
setTimeout(() => { copyBtn.textContent = "Copy"; copyBtn.classList.remove("copied"); }, 1500);
|
|
} catch { toast("Copy failed — select the text manually", "error"); }
|
|
};
|
|
openModal("reset-modal");
|
|
}
|
|
|
|
// ── Set password ──
|
|
function openSetPassword(id, email) {
|
|
document.getElementById("setpwd-target").textContent = `For ${email}`;
|
|
const input = document.getElementById("setpwd-input");
|
|
input.value = "";
|
|
openModal("setpwd-modal");
|
|
document.getElementById("confirm-setpwd-btn").onclick = async () => {
|
|
const pwd = input.value;
|
|
if (!pwd || pwd.length < 8) { toast("Password must be at least 8 characters", "error"); return; }
|
|
const r = await fetch(`${API}/${id}/set-password`, {
|
|
method: "POST", credentials: "include",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ password: pwd }),
|
|
});
|
|
if (!r.ok) { toast("Failed: " + (await r.text()), "error"); return; }
|
|
closeModal("setpwd-modal");
|
|
toast("Password updated", "success");
|
|
};
|
|
}
|
|
|
|
// ── Delete ──
|
|
async function delUser(id, email) {
|
|
if (!await confirmModal(`Delete ${email}? This cannot be undone.`)) return;
|
|
const r = await fetch(`${API}/${id}`, { method: "DELETE", credentials: "include" });
|
|
if (!r.ok) { toast("Failed: " + (await r.text()), "error"); return; }
|
|
toast("User deleted", "success");
|
|
loadUsers();
|
|
}
|
|
|
|
// ── Create ──
|
|
document.getElementById("open-create-btn").addEventListener("click", () => {
|
|
document.getElementById("new-email").value = "";
|
|
document.getElementById("new-name").value = "";
|
|
document.getElementById("new-role").value = "analyst";
|
|
document.getElementById("new-send-invite").checked = true;
|
|
openModal("create-modal");
|
|
});
|
|
document.getElementById("confirm-create-btn").addEventListener("click", async () => {
|
|
const email = document.getElementById("new-email").value.trim();
|
|
const name = document.getElementById("new-name").value.trim();
|
|
const role = document.getElementById("new-role").value;
|
|
const sendInvite = document.getElementById("new-send-invite").checked;
|
|
if (!email) { toast("Email is required", "error"); return; }
|
|
const r = await fetch(API, {
|
|
method: "POST", credentials: "include",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ email, name: name || email.split("@")[0], role, send_invite: sendInvite }),
|
|
});
|
|
if (!r.ok) { toast("Failed: " + (await r.text()), "error"); return; }
|
|
const data = await r.json().catch(() => ({}));
|
|
closeModal("create-modal");
|
|
toast("User created", "success");
|
|
loadUsers();
|
|
if (data.invite_url) showInviteLink(email, data.invite_url, data.invite_email_sent);
|
|
});
|
|
|
|
function showInviteLink(email, url, emailSent) {
|
|
document.getElementById("invite-target").textContent = `For ${email}`;
|
|
document.getElementById("invite-transport-note").textContent = emailSent
|
|
? "Invitation email sent. Copy the link below only if you need to deliver it manually."
|
|
: "Email transport unavailable — send this link to the user directly.";
|
|
document.getElementById("invite-url-text").textContent = url;
|
|
const copyBtn = document.getElementById("invite-copy-btn");
|
|
copyBtn.textContent = "Copy"; copyBtn.classList.remove("copied");
|
|
copyBtn.onclick = async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(url);
|
|
copyBtn.textContent = "Copied!"; copyBtn.classList.add("copied");
|
|
setTimeout(() => { copyBtn.textContent = "Copy"; copyBtn.classList.remove("copied"); }, 1500);
|
|
} catch { toast("Copy failed — select the text manually", "error"); }
|
|
};
|
|
openModal("invite-modal");
|
|
}
|
|
|
|
loadUsers();
|
|
</script>
|
|
{% endblock %}
|