forked from code/member-dashboard
Member self-serve guest access: invite a friend from the dashboard
New Guest access card (members only — a guest's dashboard keeps its own ended-state view): invite a friend by email with an optional display name, the remaining invitation allowance (one guest per member per rolling 30 days, with the next open date), and the member's own guest trail — who they invited, when, and the honest status (pending approval / not approved / active guest / became a member / ended). Under the trial gate the button says 'Send request' and the hint says the co-op approves before the account is created; the portal's auto_approve flag flips both to 'Send invite' with no deploy. Portal refusals pass through verbatim (429 member-facing text). /api/guests GET+POST are one hop to the portal's /broker/guests endpoints.
This commit is contained in:
1 parent
7430811ddc
commit
84d5389eb6
1 file changed
+203
-1
+203
-1
@@ -109,6 +109,26 @@ async def broker_delete(identity: str, path: str) -> dict:
|
||||
return r.json() if r.content else {}
|
||||
|
||||
|
||||
async def broker_call(identity: str, method: str, path: str, payload: dict | None = None) -> tuple[int, dict]:
|
||||
"""Portal call that returns the portal's OWN status + payload.
|
||||
|
||||
The guest path's 429 refusals are member-facing text ("one guest per
|
||||
member per month") — transport-error wrapping (502) would bury them, so
|
||||
the guest routes surface the portal's status and detail verbatim.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||
r = await client.request(method, f"{PORTAL_BASE}{path}",
|
||||
headers=broker_headers(identity), json=payload)
|
||||
try:
|
||||
data = r.json()
|
||||
except Exception:
|
||||
data = {"error": r.text or "portal returned no body"}
|
||||
if r.status_code == 401:
|
||||
# Broker credentials broken — an app fault, not a member condition.
|
||||
data = {"error": "The portal rejected this dashboard's credentials"}
|
||||
return r.status_code, data
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Routes
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -254,6 +274,48 @@ async def api_cancel_guest(request: Request):
|
||||
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
||||
|
||||
|
||||
@app.get("/api/guests")
|
||||
async def api_guests(request: Request):
|
||||
"""The caller's guest-access view: invitation allowance + their trail.
|
||||
|
||||
One hop to the portal broker's GET /broker/guests: whether this member
|
||||
can send a guest invitation now (the rolling one-per-30-days rule,
|
||||
counting pending and approved requests) and every invitation they have
|
||||
made, with its status. The portal's refusal statuses pass through as-is.
|
||||
"""
|
||||
identity = get_user_identity(request)
|
||||
if not identity:
|
||||
return JSONResponse({"error": "unauthenticated"}, status_code=401)
|
||||
status, data = await broker_call(identity, "GET", "/broker/guests")
|
||||
return JSONResponse(data, status_code=status)
|
||||
|
||||
|
||||
@app.post("/api/guests")
|
||||
async def api_guest_invite(request: Request):
|
||||
"""Invite a guest, from the member dashboard (self-serve guest access).
|
||||
|
||||
Body: {"email": "<recipient>", "name": "<optional display name>"}. One
|
||||
hop to the portal broker, which holds every protection (active-member
|
||||
inviter, one invitation per member per 30 days, recipient never an
|
||||
existing member / prior guest / pending request / manual account) and
|
||||
the trial gate: with approval on, the request waits for the co-op's
|
||||
approve/reject and nothing goes to the recipient until then. The
|
||||
portal's refusals are member-facing text and pass through verbatim.
|
||||
"""
|
||||
identity = get_user_identity(request)
|
||||
if not identity:
|
||||
return JSONResponse({"error": "unauthenticated"}, status_code=401)
|
||||
body = await request.json()
|
||||
payload = {
|
||||
"email": (body.get("email") or "").strip().lower(),
|
||||
"name": (body.get("name") or "").strip(),
|
||||
}
|
||||
if not payload["email"] or "@" not in payload["email"]:
|
||||
return JSONResponse({"error": "Enter their email address"}, status_code=400)
|
||||
status, data = await broker_call(identity, "POST", "/broker/guests", payload)
|
||||
return JSONResponse(data, status_code=status)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OIDC routes — authorization-code flow against Cloudron's OIDC provider.
|
||||
# Active only when the `oidc` addon is configured (CLOUDRON_OIDC_* present).
|
||||
@@ -565,6 +627,24 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
.flash.show { display: block; }
|
||||
.flash.ok { background: #eaf3ea; color: #2f5c30; }
|
||||
.flash.err { background: #f6e9e5; color: var(--danger); }
|
||||
|
||||
/* ---------- Guest access (members inviting a friend) ---------- */
|
||||
.guest-hint { color: var(--muted); font-size: 12px; margin-bottom: 12px; }
|
||||
.new-key .name-input { max-width: 200px; }
|
||||
.guest-trail { margin-top: 6px; }
|
||||
.guest-row {
|
||||
display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
|
||||
padding: 10px 0; border-bottom: 1px solid #f0ede6;
|
||||
}
|
||||
.guest-row:last-child { border-bottom: none; }
|
||||
.guest-who { font-weight: 600; font-size: 13px; }
|
||||
.guest-meta { color: var(--muted); font-size: 12px; margin-top: 2px; }
|
||||
.gpill { display: inline-block; padding: 2px 9px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }
|
||||
.gpill.pending { background: #fdf3e3; color: #a97a2a; }
|
||||
.gpill.ok { background: #eaf3ea; color: #2f5c30; }
|
||||
.gpill.done { background: #f1e8da; color: #a97a4a; }
|
||||
.gpill.bad { background: #f6e9e5; color: var(--danger); }
|
||||
|
||||
footer {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 20px 24px; margin-top: 32px;
|
||||
@@ -759,6 +839,18 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
<div class="hint" id="mxid-status"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="guests-card" style="display:none">
|
||||
<h2>Guest access</h2>
|
||||
<p class="guest-hint" id="guest-hint">Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days.</p>
|
||||
<div class="new-key">
|
||||
<input id="guest-email" type="email" placeholder="their@email.org" maxlength="254" />
|
||||
<input id="guest-name" type="text" class="name-input" placeholder="Their name (optional)" maxlength="80" />
|
||||
<button class="primary" id="guest-btn" onclick="sendGuestInvite()">Send request</button>
|
||||
</div>
|
||||
<div class="hint" id="guest-allowance"></div>
|
||||
<div class="guest-trail" id="guest-trail"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
@@ -847,6 +939,115 @@ function renderGuestEnded(g) {
|
||||
if (kc) kc.style.display = 'none';
|
||||
}
|
||||
|
||||
// --- Member self-serve guest access ----------------------------------------
|
||||
// One invitation per member per rolling 30 days (the portal owns the rule);
|
||||
// under the trial gate a request waits for the co-op's approval before the
|
||||
// friend's account is created. The trail is the member's own history only.
|
||||
|
||||
const GUEST_STATUS_LABELS = {
|
||||
pending: ['pending approval', 'pending'],
|
||||
rejected: ['not approved', 'bad'],
|
||||
active: ['active guest', 'ok'],
|
||||
converted: ['became a member', 'done'],
|
||||
expired: ['ended — time ran out', 'done'],
|
||||
depleted: ['ended — credit spent', 'done'],
|
||||
'cancelled by recipient': ['ended — they cancelled', 'done'],
|
||||
};
|
||||
|
||||
function guestStatusPill(status, kind) {
|
||||
const [label, cls] = GUEST_STATUS_LABELS[status] ||
|
||||
[(status || 'sent').replace(/^./, c => c.toUpperCase()), 'done'];
|
||||
return '<span class="gpill ' + cls + '">' + escapeHtml(label) + '</span>';
|
||||
}
|
||||
|
||||
function fmtDay(s) {
|
||||
if (!s) return '';
|
||||
const d = new Date(String(s).replace(' ', 'T') + (String(s).includes('Z') ? '' : 'Z'));
|
||||
return isNaN(d) ? '' : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
async function loadGuests() {
|
||||
try {
|
||||
const r = await fetch('/api/guests');
|
||||
if (r.status === 401) { location.reload(); return; }
|
||||
const d = await r.json().catch(() => ({}));
|
||||
renderGuests(d);
|
||||
} catch (e) {
|
||||
$('guest-allowance').textContent = '';
|
||||
$('guest-trail').innerHTML = '<div class="empty">Could not load your guest invitations — try again later.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderGuests(d) {
|
||||
if (d.error) {
|
||||
$('guest-allowance').textContent = '';
|
||||
$('guest-trail').innerHTML = '<div class="empty">' + escapeHtml(d.error) + '</div>';
|
||||
return;
|
||||
}
|
||||
// The gate: with auto-approve on the invitation sends directly; under the
|
||||
// trial it waits for the co-op's approval. The button says which.
|
||||
const auto = !!d.auto_approve;
|
||||
$('guest-btn').textContent = auto ? 'Send invite' : 'Send request';
|
||||
if (auto) {
|
||||
$('guest-hint').textContent = "Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days.";
|
||||
} else {
|
||||
$('guest-hint').textContent = "Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days. The co-op approves guest requests before the account is created.";
|
||||
}
|
||||
if (d.eligible) {
|
||||
$('guest-allowance').textContent = 'You can send one guest invitation now.';
|
||||
} else if (d.next_eligible_at) {
|
||||
$('guest-allowance').textContent =
|
||||
'One guest every ' + (d.per_inviter_days || 30) + ' days — your next invitation opens ' + fmtDay(d.next_eligible_at) + '.';
|
||||
} else {
|
||||
$('guest-allowance').textContent =
|
||||
'One guest every ' + (d.per_inviter_days || 30) + ' days.';
|
||||
}
|
||||
const trail = d.trail || [];
|
||||
if (!trail.length) {
|
||||
$('guest-trail').innerHTML = '<div class="empty">No guest invitations yet.</div>';
|
||||
return;
|
||||
}
|
||||
$('guest-trail').innerHTML = trail.map(t => {
|
||||
const who = t.name ? escapeHtml(t.name) + ' · ' + escapeHtml(t.recipient) : escapeHtml(t.recipient);
|
||||
const when = t.decided_at ? 'Decided ' + fmtDay(t.decided_at) : 'Sent ' + fmtDay(t.created_at);
|
||||
return '<div class="guest-row">' +
|
||||
'<div><div class="guest-who">' + who + '</div>' +
|
||||
'<div class="guest-meta">' + when + '</div></div>' +
|
||||
guestStatusPill(t.status, t.kind) +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function sendGuestInvite() {
|
||||
const email = ($('guest-email').value || '').trim();
|
||||
const name = ($('guest-name').value || '').trim();
|
||||
const btn = $('guest-btn');
|
||||
const label = btn.textContent;
|
||||
if (!email || email.indexOf('@') < 1) { flash('Enter their email address', false); return; }
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Sending…';
|
||||
try {
|
||||
const r = await fetch('/api/guests', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ email, name })
|
||||
});
|
||||
const d = await r.json().catch(() => ({}));
|
||||
if (!r.ok || d.error) {
|
||||
flash(d.detail || d.note || d.error || 'Could not send the request', false);
|
||||
return;
|
||||
}
|
||||
$('guest-email').value = '';
|
||||
$('guest-name').value = '';
|
||||
flash(d.note || 'Request sent — waiting for approval.', true);
|
||||
await loadGuests();
|
||||
} catch (e) {
|
||||
flash('Could not send the request: ' + e.message, false);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = label;
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const r = await fetch('/api/usage');
|
||||
@@ -872,6 +1073,7 @@ async function load() {
|
||||
// place of the credit-pack buy path. Everything else stays.
|
||||
const isGuest = !!d.guest;
|
||||
$('matrix-card').style.display = isGuest ? 'none' : '';
|
||||
$('guests-card').style.display = isGuest ? 'none' : '';
|
||||
$('oc-note').style.display = isGuest ? 'none' : '';
|
||||
if (isGuest) {
|
||||
const b = $('buy-btn');
|
||||
@@ -925,7 +1127,7 @@ async function load() {
|
||||
renderModels(d.models || []);
|
||||
renderBoard(d.coop_models || []);
|
||||
renderKeys(d.keys || [], d.key_spend || []);
|
||||
if (!isGuest) loadMxid();
|
||||
if (!isGuest) { loadMxid(); loadGuests(); }
|
||||
} catch (e) {
|
||||
flash('Could not load usage: ' + e.message, false);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user