Settings → Profile: editable particulars (name, bio, location, occupation, organization, website)

The Profile tab was a read-only avatar/name/email stub. It is now a real
form, modeled on the profile surfaces of GitHub/Slack/Nextcloud and scoped
to what a knowledge tool uses: display name, bio (280 chars with counter),
location, occupation, organization and website; email stays read-only
(sign-in identity). Copy explains where the name appears (shares) and
that public bookmark links never reveal identity.

Schema: migration 024_user_profile.sql + schema.sql add five nullable
text columns to User (db-converge green, fresh and upgraded paths).
models.User, userFromObject and the auth identity projection carry them,
so GET /api/me serves the stored truth (Go re-reads identity per request).

PATCH /api/me applies partial allowlisted edits: empty string clears to
NULL, rune-based caps (120/280/120/120/120), website <=2048 and http(s)
with a host; the answer is the fresh identity projection. User has no
version column (identity, not a collaborative collection), so this follows
the settings-save shape rather than the 409 contract; view-as writes stay
blocked by the middleware.

Session propagation: the auth.ts jwt callback gains an "update" trigger
that re-syncs name/email/image from Go via the same assertion the data
proxy signs (fail-quiet when Go is unreachable). The component calls
useSession().update({}) after a save — the {} argument is load-bearing:
in next-auth v5 a bare update() only re-fetches the session, it does not
fire the trigger (caught by the new browser regression). The top bar name
refreshes without a re-login.

Verified: full Go integration suite green incl. new TestProfileUpdate
(partial edits, clearing, rune caps, URL validation, auth gate);
db-converge green; web lint/SSR-lint/build 0 errors; full browser
regressions pass incl. the new profile round-trip (save → toast → top-bar
refresh → form values intact → Save re-disables on a clean baseline).
This commit is contained in:
Andrew S Erwin
2026-11-20 17:09:32 -06:00
parent 7a7e77e039
commit f6158f58b5
13 changed files with 447 additions and 17 deletions
+2 -1
View File
@@ -24,7 +24,8 @@ capped (100 per bookmark/tag/collection share, 200 per shared date).
| POST | `/api/password/reset` | `{ok:true}` — body `{token,password}`; consumes the token, sets the new password and bumps `tokenVersion` (revokes all prior sessions). **400** on invalid/expired/used tokens or policy-violating passwords; **403** in oidc mode | | POST | `/api/password/reset` | `{ok:true}` — body `{token,password}`; consumes the token, sets the new password and bumps `tokenVersion` (revokes all prior sessions). **400** on invalid/expired/used tokens or policy-violating passwords; **403** in oidc mode |
| GET | `/api/auth/session` | `{user}` or `null` for no valid cookie | | GET | `/api/auth/session` | `{user}` or `null` for no valid cookie |
| POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present | | POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present |
| GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1: every user belongs to the implicit default tenant) | | GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1) and the profile particulars `bio,location,occupation,organization,website` (nullable) |
| PATCH | `/api/me` | Settings → Profile: partial `{name?,bio?,location?,occupation?,organization?,website?}` (allowlist; empty string clears to null; rune caps 120/280/120/120/120, website ≤2048 and http(s) with a host) → the fresh user projection. No version column on User (identity, not a collaborative collection); view-as writes are blocked by the middleware |
| GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL | | GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL |
| POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking | | POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking |
| GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub | | GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub |
+12
View File
@@ -0,0 +1,12 @@
-- 024_user_profile.sql — Settings → Profile: editable particulars.
--
-- Additive and idempotent; schema.sql carries the identical columns, so this
-- is a structural no-op on a fresh database (db-converge proves both paths
-- land the same). All nullable free text; the API validates lengths and the
-- website URL shape (internal/handlers/profile.go).
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS bio text;
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS location text;
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS occupation text;
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS organization text;
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS website text;
+6 -1
View File
@@ -40,7 +40,12 @@ CREATE TABLE "User" (
"tokenVersion" integer NOT NULL DEFAULT 1, "tokenVersion" integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(), "createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(), "updatedAt" timestamptz NOT NULL DEFAULT now(),
"tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL "tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL,
bio text,
location text,
occupation text,
organization text,
website text
); );
-- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1). -- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1).
+2 -1
View File
@@ -31,7 +31,8 @@ type SessionUser struct {
} }
func identity(u *models.User) map[string]any { func identity(u *models.User) map[string]any {
return map[string]any{"id": u.ID, "name": u.Name, "email": u.Email, "image": u.Image, "role": u.Role, "tenantId": u.TenantID} return map[string]any{"id": u.ID, "name": u.Name, "email": u.Email, "image": u.Image, "role": u.Role, "tenantId": u.TenantID,
"bio": u.Bio, "location": u.Location, "occupation": u.Occupation, "organization": u.Organization, "website": u.Website}
} }
func AuthMiddleware(next http.Handler) http.Handler { func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+6 -1
View File
@@ -36,11 +36,16 @@ func userFromObject(o Object) (*models.User, error) {
Role string `json:"role"` Role string `json:"role"`
TokenVersion int `json:"tokenVersion"` TokenVersion int `json:"tokenVersion"`
TenantID *string `json:"tenantId"` TenantID *string `json:"tenantId"`
Bio *string `json:"bio"`
Location *string `json:"location"`
Occupation *string `json:"occupation"`
Organization *string `json:"organization"`
Website *string `json:"website"`
} }
if err = json.Unmarshal(raw, &row); err != nil { if err = json.Unmarshal(raw, &row); err != nil {
return nil, err return nil, err
} }
return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID}, nil return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID, Bio: row.Bio, Location: row.Location, Occupation: row.Occupation, Organization: row.Organization, Website: row.Website}, nil
} }
func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) { func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) {
+116
View File
@@ -0,0 +1,116 @@
package handlers
// Settings → Profile: the account's particulars (display name, bio,
// location, occupation, organization, website). PATCH /api/me updates an
// allowlist of free-text fields; an empty string clears the field (NULL).
// The User row is identity, not a collaborative collection — it has no
// version column, so this follows the settings-save shape rather than the
// 409 mutation contract. View-as impersonation is already blocked for
// writes by the auth middleware.
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"github.com/andrew/superbrain/internal/db"
)
// profileTextFields maps the allowlisted column names to their rune caps.
// Keys are server-owned; values are always bind parameters.
var profileTextFields = map[string]int{
"name": 120,
"bio": 280,
"location": 120,
"occupation": 120,
"organization": 120,
}
const maxWebsiteLen = 2048
// HandleProfileUpdate applies a partial profile edit and answers the fresh
// identity projection (the same shape GET /api/me returns under "user").
//
// PATCH /api/me
func HandleProfileUpdate(w http.ResponseWriter, r *http.Request) {
b, ok := read(w, r)
if !ok {
return
}
updates := object{}
for field, maxLen := range profileTextFields {
v, present := b[field]
if !present {
continue
}
s, isStr := v.(string)
if !isStr {
respond(w, 0, nil, bad(field+" must be a string"))
return
}
s = strings.TrimSpace(s)
if len([]rune(s)) > maxLen {
respond(w, 0, nil, bad(fmt.Sprintf("%s must be at most %d characters", field, maxLen)))
return
}
if s == "" {
updates[field] = nil
} else {
updates[field] = s
}
}
if v, present := b["website"]; present {
s, isStr := v.(string)
if !isStr {
respond(w, 0, nil, bad("website must be a string"))
return
}
s = strings.TrimSpace(s)
if s == "" {
updates["website"] = nil
} else {
u, e := url.Parse(s)
if len(s) > maxWebsiteLen || e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
respond(w, 0, nil, bad("website must be an http(s) URL"))
return
}
updates["website"] = s
}
}
if len(updates) == 0 {
respond(w, 0, nil, bad("Nothing to update"))
return
}
keys := make([]string, 0, len(updates))
for k := range updates {
keys = append(keys, k)
}
sort.Strings(keys)
sets := make([]string, 0, len(keys))
args := make([]any, 0, len(keys)+1)
for i, k := range keys {
sets = append(sets, db.Quote(k)+fmt.Sprintf("=$%d", i+1))
args = append(args, updates[k])
}
args = append(args, user(r))
row, e := db.One(r.Context(), database(r),
`UPDATE "User" SET `+strings.Join(sets, ",")+`, "updatedAt"=now() WHERE id=$`+fmt.Sprint(len(args))+` RETURNING to_jsonb("User")`, args...)
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, profileProjection(row), nil)
}
// profileProjection mirrors auth.identity (the GET /api/me "user" shape)
// so the client can refresh its state from the save response alone.
func profileProjection(row object) object {
return object{
"id": row["id"], "name": row["name"], "email": row["email"], "image": row["image"],
"role": row["role"], "tenantId": row["tenantId"],
"bio": row["bio"], "location": row["location"], "occupation": row["occupation"],
"organization": row["organization"], "website": row["website"],
}
}
+76
View File
@@ -0,0 +1,76 @@
package http
import (
"net/http"
"net/http/cookiejar"
"strings"
"testing"
)
// Settings → Profile: the identity projection carries the particulars,
// PATCH /api/me applies partial allowlisted edits (empty string clears),
// validation is rune-based, and the endpoint is session-gated.
func TestProfileUpdate(t *testing.T) {
srv, _ := testServerDB(t)
jar, _ := cookiejar.New(nil)
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
fields := []string{"bio", "location", "occupation", "organization", "website"}
user := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
for _, f := range fields {
if v, present := user[f]; !present || v != nil {
t.Fatalf("fresh profile field %s = %v (present=%v), want null", f, v, present)
}
}
saved := alice.request("PATCH", "/api/me", map[string]any{
"name": "Alice Example", "bio": "Knowledge worker", "location": "Berlin, Germany",
"occupation": "Engineer", "organization": "Acme", "website": "https://alice.example.com",
}, 200)
if saved["name"] != "Alice Example" || saved["bio"] != "Knowledge worker" ||
saved["location"] != "Berlin, Germany" || saved["occupation"] != "Engineer" ||
saved["organization"] != "Acme" || saved["website"] != "https://alice.example.com" {
t.Fatalf("save response wrong: %v", saved)
}
// The session identity is reloaded per request: GET /api/me reflects it.
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
if user["name"] != "Alice Example" || user["occupation"] != "Engineer" {
t.Fatalf("GET /api/me did not reflect the save: %v", user)
}
// Partial edit: only the submitted field moves.
alice.request("PATCH", "/api/me", map[string]any{"bio": "Updated bio"}, 200)
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
if user["bio"] != "Updated bio" || user["location"] != "Berlin, Germany" || user["name"] != "Alice Example" {
t.Fatalf("partial edit clobbered other fields: %v", user)
}
// Empty string clears to null; whitespace-only is empty too.
alice.request("PATCH", "/api/me", map[string]any{"bio": " ", "website": ""}, 200)
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
if user["bio"] != nil || user["website"] != nil {
t.Fatalf("clear did not null the fields: %v", user)
}
// Rune-based caps: 280 multi-byte runes fit, 281 do not.
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 280)}, 200)
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 281)}, 400)
alice.request("PATCH", "/api/me", map[string]any{"name": strings.Repeat("x", 121)}, 400)
// Website shape: http(s) with a host only.
for _, badURL := range []string{"javascript:alert(1)", "ftp://x.test", "not a url", "https://", "/relative"} {
alice.request("PATCH", "/api/me", map[string]any{"website": badURL}, 400)
}
alice.request("PATCH", "/api/me", map[string]any{"website": "http://alice.example.com/path"}, 200)
// Type and emptiness guards.
alice.request("PATCH", "/api/me", map[string]any{"bio": 42}, 400)
alice.request("PATCH", "/api/me", map[string]any{"unknown": "x"}, 400)
alice.request("PATCH", "/api/me", map[string]any{}, 400)
// Session-gated like every data endpoint.
anon := apiClient{t, &http.Client{}, srv.URL}
anon.request("PATCH", "/api/me", map[string]any{"bio": "intruder"}, 401)
}
+1
View File
@@ -48,6 +48,7 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
mux.HandleFunc("POST /api/auth/", auth.HandleAuth) mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
mux.HandleFunc("GET /api/me", authed(auth.HandleMe)) mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
mux.HandleFunc("PATCH /api/me", authed(handlers.HandleProfileUpdate))
// Authelia OIDC (stub-aware; the client drives the flow via NextAuth) // Authelia OIDC (stub-aware; the client drives the flow via NextAuth)
mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus) mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus)
+6
View File
@@ -24,6 +24,12 @@ type User struct {
TenantID *string TenantID *string
CreatedAt string CreatedAt string
UpdatedAt string UpdatedAt string
// Profile particulars (Settings → Profile, migration 024).
Bio *string
Location *string
Occupation *string
Organization *string
Website *string
} }
// Account, Session, VerificationToken are auth-library tables. Porting guide 2.3. // Account, Session, VerificationToken are auth-library tables. Porting guide 2.3.
+48 -2
View File
@@ -70,6 +70,12 @@ const carddavConnections = [{
lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z', lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z',
}] }]
const carddavSuggestions = [{ kind: 'nextcloud', name: 'Nextcloud contacts', url: 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/' }] const carddavSuggestions = [{ kind: 'nextcloud', name: 'Nextcloud contacts', url: 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/' }]
// The identity is mutable: Settings → Profile PATCHes it, and the NextAuth
// jwt "update" trigger re-reads it from /api/me (session name refresh).
const fixtureUser = {
id: 'fixture-user', name: 'Fixture', email: 'fixture@superbrain.test', role: 'USER', image: null,
bio: null, location: null, occupation: null, organization: null, website: null,
}
const api = http.createServer(async (req, res) => { const api = http.createServer(async (req, res) => {
try { try {
let raw = '' let raw = ''
@@ -86,13 +92,24 @@ const api = http.createServer(async (req, res) => {
const body = raw ? JSON.parse(raw) : {} const body = raw ? JSON.parse(raw) : {}
const url = new URL(req.url, 'http://fixture') const url = new URL(req.url, 'http://fixture')
let result = [] let result = []
if (url.pathname === '/api/auth/login') result = { user: { id: 'fixture-user', name: 'Fixture', email: body.email, role: 'USER' }, tokenVersion: 1 } if (url.pathname === '/api/auth/login') result = { user: { ...fixtureUser, email: body.email }, tokenVersion: 1 }
else if (url.pathname === '/api/auth/signout' && req.method === 'POST') { else if (url.pathname === '/api/auth/signout' && req.method === 'POST') {
signouts.push(req.headers.authorization || '') signouts.push(req.headers.authorization || '')
if (failSignout) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":"Fixture revocation failed"}'); return } if (failSignout) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":"Fixture revocation failed"}'); return }
result = { ok: true } result = { ok: true }
} }
else if (url.pathname === '/api/me') result = { user: { id: 'fixture-user' }, effectiveUser: { id: 'fixture-user' }, isAdmin: false, viewingAs: null } else if (url.pathname === '/api/me') {
if (req.method === 'PATCH') {
// Mirror Go's allowlist + empty-string-clears semantics; the answer
// is the flat user projection (same shape as GET /api/me's "user").
for (const k of ['name', 'bio', 'location', 'occupation', 'organization', 'website']) {
if (k in body) fixtureUser[k] = body[k] === '' ? null : body[k]
}
result = fixtureUser
} else {
result = { user: fixtureUser, effectiveUser: { id: fixtureUser.id, name: fixtureUser.name, email: fixtureUser.email, role: fixtureUser.role }, isAdmin: false, viewingAs: null }
}
}
// The list endpoint is a metadata projection: content bodies stay out (PERF-01). // The list endpoint is a metadata projection: content bodies stay out (PERF-01).
else if (url.pathname === '/api/pages') { else if (url.pathname === '/api/pages') {
if (req.method === 'PUT') { if (req.method === 'PUT') {
@@ -680,6 +697,35 @@ try {
await eventually(() => pages.get('a')?.position === 0 && pages.get('b')?.position === 1, 'Sidebar page drag did not reorder') await eventually(() => pages.get('a')?.position === 0 && pages.get('b')?.position === 1, 'Sidebar page drag did not reorder')
console.log('PASS: sidebar persists drag reordering') console.log('PASS: sidebar persists drag reordering')
// Settings → Profile: particulars load from /api/me, the save PATCHes the
// allowlist, and the NextAuth session re-syncs from Go (jwt update trigger)
// so the top bar shows the new name without a re-login.
await page.goto(`${base}/settings`)
await page.getByRole('tab', { name: 'Profile' }).click()
await page.getByPlaceholder('Your name').waitFor()
assert.equal(await page.getByPlaceholder('Your name').inputValue(), 'Fixture')
await page.getByPlaceholder('Your name').fill('Fixture Person')
await page.getByPlaceholder('A short introduction').fill('Keeper of the second brain')
await page.getByPlaceholder('City, country').fill('Berlin, Germany')
await page.getByPlaceholder('Job title').fill('Knowledge worker')
await page.getByPlaceholder('Company or team').fill('Federated Computer')
await page.getByPlaceholder('https://example.com').fill('https://federatedcomputer.ai')
await page.getByRole('button', { name: 'Save profile' }).click()
await eventually(() => fixtureUser.name === 'Fixture Person' && fixtureUser.website === 'https://federatedcomputer.ai', 'Profile save PATCH did not reach the API')
await page.getByText('Profile saved').waitFor()
// The save response is the flat projection: the form keeps the values.
assert.equal(await page.getByPlaceholder('Your name').inputValue(), 'Fixture Person')
assert.equal(await page.getByPlaceholder('https://example.com').inputValue(), 'https://federatedcomputer.ai')
assert.equal(fixtureUser.bio, 'Keeper of the second brain')
assert.equal(fixtureUser.location, 'Berlin, Germany')
assert.equal(fixtureUser.occupation, 'Knowledge worker')
assert.equal(fixtureUser.organization, 'Federated Computer')
// The top bar (header) reflects the refreshed session identity.
await eventually(() => page.locator('header').getByText('Fixture Person', { exact: true }).isVisible(), 'top bar did not refresh the session name after the profile save')
// Clean baseline: the save button disables again until the next edit.
assert.ok(await page.getByRole('button', { name: 'Save profile' }).isDisabled(), 'Save stayed enabled after a clean save')
console.log('PASS: Settings → Profile saves particulars and refreshes the session identity')
// Settings → WebDAV: masked list rows render; the deployment suggestion // Settings → WebDAV: masked list rows render; the deployment suggestion
// (NEXTCLOUD_URL) prefills the connect form with the username composed into // (NEXTCLOUD_URL) prefills the connect form with the username composed into
// the per-user DAV root; // the per-user DAV root;
+2 -11
View File
@@ -1,7 +1,6 @@
'use client' 'use client'
import { useState, useEffect, useCallback, Fragment } from 'react' import { useState, useEffect, useCallback, Fragment } from 'react'
import { useSession } from 'next-auth/react'
import { useSearchParams } from 'next/navigation' import { useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
@@ -10,6 +9,7 @@ import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZ
import { toast } from 'sonner' import { toast } from 'sonner'
import { invalidateReference } from '@/lib/reference-data' import { invalidateReference } from '@/lib/reference-data'
import { NotificationsSettings } from '@/components/notifications-settings' import { NotificationsSettings } from '@/components/notifications-settings'
import { ProfileSettings } from '@/components/profile-settings'
import { AutomationsSettings } from '@/components/automations-settings' import { AutomationsSettings } from '@/components/automations-settings'
import { AiSettings } from '@/components/ai-settings' import { AiSettings } from '@/components/ai-settings'
import { ApiKeysSettings } from '@/components/api-keys-settings' import { ApiKeysSettings } from '@/components/api-keys-settings'
@@ -50,7 +50,6 @@ const NAV_GROUPS = [
] ]
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) { export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
const { data: session } = useSession()
// ?tab=<value> deep links (email footer "Email preferences" lands on // ?tab=<value> deep links (email footer "Email preferences" lands on
// notifications). Unknown values fall back to profile; the Radix tab // notifications). Unknown values fall back to profile; the Radix tab
// values stay the canonical section ids. // values stay the canonical section ids.
@@ -180,15 +179,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
</Button> </Button>
)} )}
<TabsContent value="profile" className="mt-0 space-y-4"> <TabsContent value="profile" className="mt-0 space-y-4">
<div className="flex items-center gap-4"> <ProfileSettings />
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
{(session?.user?.name ?? session?.user?.email ?? '?')[0]?.toUpperCase()}
</div>
<div>
<p className="font-medium">{session?.user?.name ?? 'User'}</p>
<p className="text-sm text-muted-foreground" suppressHydrationWarning>{session?.user?.email}</p>
</div>
</div>
</TabsContent> </TabsContent>
<TabsContent value="oidc" className="mt-0 space-y-4"> <TabsContent value="oidc" className="mt-0 space-y-4">
<div className="rounded-lg border p-4 space-y-3"> <div className="rounded-lg border p-4 space-y-3">
+28
View File
@@ -165,6 +165,34 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
token.ver = user.tokenVersion token.ver = user.tokenVersion
token.role = user.role token.role = user.role
} }
if (trigger === 'update' && typeof token.id === 'string' && typeof token.ver === 'number') {
// Profile edits (Settings → Profile) call useSession().update({})
// so the session identity re-syncs from Go — the top bar and
// profile header reflect a new name without a re-login. (A bare
// update() only re-fetches; the data argument is what fires this
// trigger in next-auth v5.) Same assertion the data proxy signs;
// fail-quiet keeps the old values when Go is unreachable (the save
// itself already succeeded or failed loudly).
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
if (secret) {
try {
const assertion = jwt.sign({ uid: token.id, ver: token.ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/me`, {
headers: { Authorization: `Bearer ${assertion}` },
cache: 'no-store',
signal: AbortSignal.timeout(5000),
})
if (response.ok) {
const u = (await response.json())?.user
if (u) {
token.name = u.name ?? null
token.email = u.email ?? null
token.picture = u.image ?? null
}
}
} catch { /* keep the previous identity */ }
}
}
return token return token
}, },
async session({ session, token }) { async session({ session, token }) {
+142
View File
@@ -0,0 +1,142 @@
'use client'
// Settings → Profile: editable particulars (display name, bio, location,
// occupation, organization, website). Values load from GET /api/me — the
// Go identity is re-read per request, so this is always the stored truth,
// not the login-time NextAuth snapshot. After a save, useSession().update()
// re-syncs the session identity (auth.ts jwt "update" trigger) so the top
// bar and this header reflect a new name without a re-login.
import { useEffect, useState } from 'react'
import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { User } from 'lucide-react'
import { toast } from 'sonner'
type Profile = {
name: string
bio: string
location: string
occupation: string
organization: string
website: string
}
const EMPTY: Profile = { name: '', bio: '', location: '', occupation: '', organization: '', website: '' }
function fromUser(u: Record<string, unknown> | null | undefined): Profile {
const s = (v: unknown) => (typeof v === 'string' ? v : '')
return {
name: s(u?.name), bio: s(u?.bio), location: s(u?.location),
occupation: s(u?.occupation), organization: s(u?.organization), website: s(u?.website),
}
}
export function ProfileSettings() {
const { data: session, update } = useSession()
const [profile, setProfile] = useState<Profile>(EMPTY)
const [baseline, setBaseline] = useState<Profile>(EMPTY)
const [loaded, setLoaded] = useState(false)
const [saving, setSaving] = useState(false)
useEffect(() => {
fetch('/api/me')
.then(r => r.json())
.then(data => {
const p = fromUser(data?.user)
setProfile(p)
setBaseline(p)
})
.catch(() => { /* the form stays usable; saving surfaces any outage */ })
.finally(() => setLoaded(true))
}, [])
const dirty = loaded && JSON.stringify(profile) !== JSON.stringify(baseline)
const set = (key: keyof Profile) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
setProfile(p => ({ ...p, [key]: e.target.value }))
const save = async () => {
setSaving(true)
try {
const res = await fetch('/api/me', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(profile),
})
const data = await res.json().catch(() => null)
if (res.ok && data) {
const p = fromUser(data)
setProfile(p)
setBaseline(p)
toast.success('Profile saved')
// Refresh the NextAuth identity so the top bar picks up the name.
// The argument matters: in next-auth v5 a bare update() only
// re-fetches the session; update({}) POSTs and fires the jwt
// callback with trigger="update" (the auth.ts re-sync path).
await update({})
} else {
toast.error(data?.error ?? 'Failed to save')
}
} catch {
toast.error('Failed to save')
} finally {
setSaving(false)
}
}
const displayName = profile.name || session?.user?.name || session?.user?.email || 'User'
return (
<div className="rounded-lg border p-4 space-y-4">
<h3 className="font-medium flex items-center gap-2"><User className="h-4 w-4" /> Profile</h3>
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
{displayName[0]?.toUpperCase() ?? '?'}
</div>
<div className="min-w-0">
<p className="font-medium truncate">{displayName}</p>
<p className="text-sm text-muted-foreground truncate" suppressHydrationWarning>{session?.user?.email}</p>
</div>
</div>
<p className="text-sm text-muted-foreground">
Your name appears when you share bookmarks, tags and collections with others.
Public bookmark links never reveal your identity.
</p>
<div className="grid grid-cols-2 gap-3">
<div className="col-span-2">
<label className="text-xs font-medium text-muted-foreground">Display name</label>
<Input value={profile.name} onChange={set('name')} maxLength={120} placeholder="Your name" />
</div>
<div className="col-span-2">
<label className="text-xs font-medium text-muted-foreground">Bio</label>
<Textarea value={profile.bio} onChange={set('bio')} maxLength={280} rows={3} placeholder="A short introduction" />
<p className="mt-1 text-right text-xs text-muted-foreground">{profile.bio.length}/280</p>
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Location</label>
<Input value={profile.location} onChange={set('location')} maxLength={120} placeholder="City, country" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Occupation</label>
<Input value={profile.occupation} onChange={set('occupation')} maxLength={120} placeholder="Job title" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Organization</label>
<Input value={profile.organization} onChange={set('organization')} maxLength={120} placeholder="Company or team" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Website</label>
<Input value={profile.website} onChange={set('website')} maxLength={2048} type="url" placeholder="https://example.com" />
</div>
<div className="col-span-2">
<label className="text-xs font-medium text-muted-foreground">Email</label>
<Input value={session?.user?.email ?? ''} readOnly disabled className="bg-muted" suppressHydrationWarning />
<p className="mt-1 text-xs text-muted-foreground">Your sign-in identity; it cannot be changed here.</p>
</div>
</div>
<Button onClick={save} loading={saving} disabled={!dirty}>Save profile</Button>
</div>
)
}