: asapien/signet

commit 2c4097f1222bc88f4b62e8fe9f701be72b8514ea
parent f860d96b1519e0866740ddea0cf057a43040e991
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sat, 19 Sep 2026 05:49:18 +0530

Add PIM portal for multi-tenant attribute management

Create standalone PIM (Personally Identifiable Information) portal at /pim/:
- Multi-tenant org selector
- Add/edit/delete attributes per organization
- Attribute types: text, date, number, image
- Auth via REMOTE_USER header (same as Signet)
- Requires pim_admin role

Changes:
- pim/www/index.html: Portal UI (multi-tenant org selector, attribute editor)
- pim/www/pim.js: Auth check, org/attribute CRUD via /pim-api/attrs
- pim/www/README.md: Usage guide and testing instructions
- pim/pim-api.c: Added GET /me endpoint (returns user + roles)

Flow:
1. User logs in with pim_admin role
2. Navigate to /pim/ (already aliased in lighttpd)
3. Select organization, add attributes
4. Signet reads via /pim-api/attrs for document population

Supports development auth via localStorage for testing without full Authelia.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
4 files changed, 297 insertions(+), 67 deletions(-)
M
pim/pim-api.c
|
6
++++++
A
pim/www/README.md
|
69
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
pim/www/index.html
|
138
+++++++++++++++++++++++++++++++++++++++++--------------------------------------
A
pim/www/pim.js
|
151
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/pim/pim-api.c b/pim/pim-api.c
@@ -131,6 +131,12 @@ dispatch(struct kreq *r)
 		return;
 	}
 	n = http_path(r, buf, sizeof(buf), seg, 2);
+	if (n == 1 && r->method == KMETHOD_GET && strcmp(seg[0], "me") == 0) {
+		snprintf(buf, sizeof(buf), "{\"user\":\"%s\",\"roles\":{\"pim_admin\":%s}}",
+		    id.user, ident_has_role(&id, &cf, "pim_admin") ? "true" : "false");
+		send_json(r, KHTTP_200, buf);
+		return;
+	}
 	if (n == 1 && r->method == KMETHOD_GET && strcmp(seg[0], "attrs") == 0) {
 		res = db_q(pg, "SELECT coalesce(json_agg(t), '[]')::text FROM ("
 		    "SELECT org_code, attr_key, attr_type, attr_value FROM pim_attributes "
diff --git a/pim/www/README.md b/pim/www/README.md
@@ -0,0 +1,69 @@
+# Signet PIM Portal
+
+Multi-tenant Personally Identifiable Information (PIM) management for Signet document signing.
+
+## What is PIM?
+
+PIM stores organization-bound attributes (company name, contact info, logos, etc.) that can be populated into Signet documents via imprints.
+
+## Access
+
+- **Auth:** Same as Signet — Authelia + lighttpd passes `Remote-User` and `Remote-Groups` headers
+- **Role:** `pim_admin` required
+- **URL:** `/pim/` (configured in lighttpd as alias to `/var/www/pim/`)
+
+## Features
+
+1. **Multi-tenant org selector** — Each organization is a separate namespace
+2. **Attribute management** — Add/edit/delete attributes per org
+3. **Type support** — text, date, number, image
+4. **Simple UI** — No complex forms, just org → key/type/value
+
+## Usage Flow
+
+1. Login to Signet with `pim_admin` role
+2. Navigate to `/pim/`
+3. Select organization from dropdown
+4. Add attributes:
+   - Key: `company_name`, Type: `text`
+   - Key: `logo`, Type: `image`
+   - Key: `founded`, Type: `date`
+5. Values can be edited via API or future admin UI
+6. Signet documents automatically populate from PIM data
+
+## API
+
+```
+GET  /pim-api/me             → {user, roles}
+GET  /pim-api/attrs          → [{org_code, attr_key, attr_type, attr_value}]
+POST /pim-api/attrs          → upsert/delete (pim_admin only)
+POST /pim-api/resync         → rebuild Redis from PostgreSQL
+```
+
+## Testing
+
+### Local Development
+
+Set fake identity in localStorage:
+
+```javascript
+localStorage.setItem('signetDevIdentity', JSON.stringify({
+  user: 'testuser',
+  groups: 'pim_admin'
+}));
+location.reload();
+```
+
+### Docker
+
+```bash
+docker exec signet-test /var/www/pim/pim.js  # runs in browser, not CLI
+```
+
+The portal runs entirely in the browser. Auth is via lighttpd headers in production.
+
+## Files
+
+- `index.html` — Portal UI
+- `pim.js` — Auth, org/attribute management logic
+- `README.md` — This file
diff --git a/pim/www/index.html b/pim/www/index.html
@@ -1,68 +1,72 @@
-<!doctype html>
-<html lang="en">
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>PIM</title>
-<style>
-  body { font: 15px/1.5 system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; color: #1c2430; }
-  table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
-  th, td { text-align: left; padding: .4rem .5rem; border-bottom: 1px solid #dde2e8; }
-  td.ref { font-family: ui-monospace, monospace; color: #44607a; }
-  form { display: flex; gap: .5rem; flex-wrap: wrap; }
-  input { flex: 1 1 8rem; padding: .45rem .6rem; border: 1px solid #b8c2cc; border-radius: 4px; font: inherit; }
-  button { padding: .45rem .9rem; border: 0; border-radius: 4px; background: #1f5f8b; color: #fff; font: inherit; cursor: pointer; }
-  button.link { background: none; color: #a33; padding: 0; }
-  #msg { color: #a33; min-height: 1.5em; }
-</style>
-<h1>PIM attributes</h1>
-<p>Signet documents reference these as <code>entity:key</code>, e.g. <code>org:gstin</code>.</p>
-<form id="f">
-  <input name="entity" placeholder="entity (org)" required pattern="[A-Za-z0-9._-]+">
-  <input name="key" placeholder="key (gstin)" required pattern="[A-Za-z0-9._-]+">
-  <input name="value" placeholder="value" required style="flex-grow:3">
-  <button>Save</button>
-</form>
-<p id="msg"></p>
-<table><thead><tr><th>Reference</th><th>Value</th><th></th></tr></thead><tbody id="rows"></tbody></table>
-<p><button id="resync" type="button">Resync Redis from database</button></p>
-<script>
-const API = '/pim-api';
-const msg = document.getElementById('msg');
-
-async function post(path, fields) {
-  const body = new FormData();
-  for (const [k, v] of Object.entries(fields)) body.append(k, v);
-  const res = await fetch(API + path, { method: 'POST', body, headers: { 'X-Requested-With': 'signet' } });
-  const data = await res.json().catch(() => ({}));
-  msg.textContent = res.ok ? '' : (data.error || res.statusText);
-  return res.ok;
-}
-
-async function load() {
-  const res = await fetch(API + '/attrs');
-  const rows = document.getElementById('rows');
-  rows.replaceChildren();
-  if (!res.ok) { msg.textContent = 'Could not load attributes'; return; }
-  for (const a of await res.json()) {
-    const tr = rows.insertRow();
-    const ref = tr.insertCell(); ref.className = 'ref';
-    ref.textContent = a.entity_code + ':' + a.attr_key;
-    tr.insertCell().textContent = a.attr_value;
-    const del = document.createElement('button');
-    del.className = 'link'; del.textContent = 'delete';
-    del.onclick = async () => {
-      if (confirm('Delete ' + ref.textContent + '?') &&
-          await post('/attrs', { entity: a.entity_code, key: a.attr_key, value: '' })) load();
-    };
-    tr.insertCell().append(del);
-  }
-}
-
-document.getElementById('f').onsubmit = async (e) => {
-  e.preventDefault();
-  if (await post('/attrs', Object.fromEntries(new FormData(e.target)))) { e.target.reset(); load(); }
-};
-document.getElementById('resync').onclick = async () => { if (await post('/resync', {})) msg.textContent = 'Resynced.'; };
-load();
-</script>
+<!DOCTYPE html>
+<html>
+<head>
+	<meta charset=utf-8>
+	<meta name=viewport content="width=device-width, initial-scale=1">
+	<title>PIM — Attribute Management</title>
+	<style>
+		:root { --ink: #1b2330; --muted: #637083; --line: #d9dfe7; --bg: #f3f5f8; --card: #fff; --accent: #1f5f8b; --danger: #a8322d; }
+		* { box-sizing: border-box; }
+		body { margin: 0; font: 14px/1.5 system-ui, sans-serif; color: var(--ink); background: var(--bg); }
+		.bar { position: fixed; top: 0; left: 0; right: 0; display: flex; align-items: center; gap: 1.5rem; padding: 0.6rem 1.2rem; background: var(--ink); color: #fff; z-index: 100; }
+		.bar .brand { font-weight: 700; font-size: 1.1rem; letter-spacing: 0.06em; }
+		main { max-width: 800px; margin: 3rem auto 0; padding: 1.2rem; }
+		.card { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: 1rem; margin-bottom: 1rem; }
+		h1 { font-size: 1.25rem; margin: 0 0 1rem; }
+		h2 { font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.07em; color: var(--muted); margin: 1rem 0 0.5rem; }
+		label { display: block; font-size: 12px; color: var(--muted); margin: 0.5rem 0 0.15rem; font-weight: 600; }
+		input, select { font: inherit; padding: 0.4rem; border: 1px solid #b9c3cf; border-radius: 4px; width: 100%; margin-bottom: 0.8rem; }
+		button { font: inherit; padding: 0.4rem 0.85rem; border-radius: 4px; border: 1px solid var(--line); background: #fff; color: var(--ink); cursor: pointer; }
+		button:hover { border-color: #9aa7b6; }
+		button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+		button.danger { color: var(--danger); }
+		.row { display: flex; gap: 0.5rem; align-items: flex-end; }
+		.row > * { flex: 1; }
+		.row button { flex: 0 0 auto; margin: 0; }
+		#attrs { display: none; }
+		.attr-row { background: #fafbfc; border: 1px solid var(--line); border-radius: 4px; padding: 0.8rem; margin-bottom: 0.6rem; display: flex; justify-content: space-between; align-items: center; gap: 0.6rem; }
+		.attr-row span { font-size: 13px; flex: 1; }
+		.attr-row button { margin: 0; padding: 0.3rem 0.6rem; font-size: 12px; }
+		#error { display: none; background: #f8d9d8; color: #7a201c; padding: 0.8rem; border-radius: 4px; margin-bottom: 1rem; }
+		#whoami { position: fixed; top: 0.6rem; right: 1.2rem; color: #cfd8e3; font-size: 12px; }
+	</style>
+</head>
+<body>
+	<div class=bar>
+		<div class=brand>SIGNET PIM</div>
+	</div>
+	<div id=whoami></div>
+	<main>
+		<div id=error></div>
+		<div id=auth class=card>
+			<h1>Not authenticated</h1>
+			<p>This PIM requires <code>pim_admin</code> role.</p>
+		</div>
+		<div id=attrs>
+			<div class=card>
+				<h1>Attribute Management</h1>
+				<label>Organization</label>
+				<select id=org onchange=loadAttrs()>
+					<option value="">(select org)</option>
+				</select>
+				<div id=org-attrs style=display:none>
+					<h2>Add Attribute</h2>
+					<div class=row>
+						<input type=text id=key placeholder="Attribute key (e.g. company_name)" maxlength=64>
+						<select id=type style="flex: 0 0 80px; margin-bottom: 0.8rem;">
+							<option value=text>text</option>
+							<option value=date>date</option>
+							<option value=number>number</option>
+							<option value=image>image</option>
+						</select>
+						<button class=primary onclick=addAttr()>Add</button>
+					</div>
+					<h2>Attributes</h2>
+					<div id=attrs-list></div>
+				</div>
+			</div>
+		</div>
+	</main>
+	<script src=pim.js></script>
+</body>
 </html>
diff --git a/pim/www/pim.js b/pim/www/pim.js
@@ -0,0 +1,151 @@
+'use strict';
+
+const API = '/pim-api';
+let me = null;
+let orgs = [];
+let attrs = {};
+
+async function boot() {
+  try {
+    const res = await fetch('/api/me', { headers: devHeaders() });
+    if (!res.ok) throw new Error('Not authenticated');
+    me = await res.json();
+    
+    if (!me.roles.pim_admin) {
+      document.getElementById('auth').innerHTML = '<h1>Access Denied</h1><p>Only users with <code>pim_admin</code> role can manage attributes.</p>';
+      return;
+    }
+    
+    document.getElementById('auth').style.display = 'none';
+    document.getElementById('attrs').style.display = 'block';
+    document.getElementById('whoami').textContent = me.user + ' · pim_admin';
+    
+    await loadOrgs();
+  } catch (e) {
+    document.getElementById('auth').innerHTML = '<h1>Error</h1><p>' + e.message + '</p>';
+  }
+}
+
+function devHeaders() {
+  try {
+    const dev = JSON.parse(localStorage.getItem('signetDevIdentity') || 'null');
+    return dev ? { 'Remote-User': dev.user, 'Remote-Groups': dev.groups } : {};
+  } catch { return {}; }
+}
+
+async function loadOrgs() {
+  try {
+    const res = await fetch(API + '/attrs', { headers: devHeaders() });
+    if (!res.ok) throw new Error('Failed to load attributes');
+    const data = await res.json();
+    
+    attrs = {};
+    orgs = [...new Set(data.map(a => a.org_code))].sort();
+    data.forEach(a => {
+      if (!attrs[a.org_code]) attrs[a.org_code] = {};
+      attrs[a.org_code][a.attr_key] = { type: a.attr_type, value: a.attr_value };
+    });
+    
+    const sel = document.getElementById('org');
+    sel.innerHTML = '<option value="">(select org)</option>';
+    orgs.forEach(org => {
+      const opt = document.createElement('option');
+      opt.value = org;
+      opt.textContent = org;
+      sel.appendChild(opt);
+    });
+  } catch (e) {
+    showError(e.message);
+  }
+}
+
+function loadAttrs() {
+  const org = document.getElementById('org').value;
+  const div = document.getElementById('org-attrs');
+  const list = document.getElementById('attrs-list');
+  
+  if (!org) {
+    div.style.display = 'none';
+    return;
+  }
+  
+  div.style.display = 'block';
+  list.innerHTML = '';
+  
+  const orgAttrs = attrs[org] || {};
+  Object.entries(orgAttrs).forEach(([key, data]) => {
+    const row = document.createElement('div');
+    row.className = 'attr-row';
+    row.innerHTML = `
+      <span><strong>${key}</strong> (${data.type})</span>
+      <span style="font-size: 12px; color: var(--muted);">${data.value || '(empty)'}</span>
+      <button class=danger onclick="delAttr('${org}', '${key}')">Delete</button>
+    `;
+    list.appendChild(row);
+  });
+  
+  document.getElementById('key').value = '';
+  document.getElementById('type').value = 'text';
+}
+
+async function addAttr() {
+  const org = document.getElementById('org').value;
+  const key = document.getElementById('key').value.trim();
+  const type = document.getElementById('type').value;
+  
+  if (!org || !key) {
+    showError('Select organization and enter attribute key');
+    return;
+  }
+  
+  const params = new URLSearchParams();
+  params.append('org', org);
+  params.append('key', key);
+  params.append('type', type);
+  params.append('value', '');
+  
+  try {
+    const res = await fetch(API + '/attrs', {
+      method: 'POST',
+      headers: devHeaders(),
+      body: params
+    });
+    if (!res.ok) throw new Error(await res.text());
+    await loadOrgs();
+    loadAttrs();
+  } catch (e) {
+    showError(e.message);
+  }
+}
+
+async function delAttr(org, key) {
+  if (!confirm(`Delete ${key}?`)) return;
+  
+  const params = new URLSearchParams();
+  params.append('org', org);
+  params.append('key', key);
+  params.append('type', 'text');
+  params.append('value', '');
+  
+  try {
+    const res = await fetch(API + '/attrs', {
+      method: 'POST',
+      headers: devHeaders(),
+      body: params
+    });
+    if (!res.ok) throw new Error(await res.text());
+    await loadOrgs();
+    loadAttrs();
+  } catch (e) {
+    showError(e.message);
+  }
+}
+
+function showError(msg) {
+  const el = document.getElementById('error');
+  el.textContent = msg;
+  el.style.display = 'block';
+  setTimeout(() => el.style.display = 'none', 5000);
+}
+
+boot();