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 -11
View File
@@ -1,7 +1,6 @@
'use client'
import { useState, useEffect, useCallback, Fragment } from 'react'
import { useSession } from 'next-auth/react'
import { useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
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 { invalidateReference } from '@/lib/reference-data'
import { NotificationsSettings } from '@/components/notifications-settings'
import { ProfileSettings } from '@/components/profile-settings'
import { AutomationsSettings } from '@/components/automations-settings'
import { AiSettings } from '@/components/ai-settings'
import { ApiKeysSettings } from '@/components/api-keys-settings'
@@ -50,7 +50,6 @@ const NAV_GROUPS = [
]
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
const { data: session } = useSession()
// ?tab=<value> deep links (email footer "Email preferences" lands on
// notifications). Unknown values fall back to profile; the Radix tab
// values stay the canonical section ids.
@@ -180,15 +179,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
</Button>
)}
<TabsContent value="profile" className="mt-0 space-y-4">
<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">
{(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>
<ProfileSettings />
</TabsContent>
<TabsContent value="oidc" className="mt-0 space-y-4">
<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.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
},
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>
)
}