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).
366 lines
13 KiB
Go
366 lines
13 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/andrew/superbrain/internal/config"
|
|
"github.com/andrew/superbrain/internal/models"
|
|
)
|
|
|
|
type UserRepo struct{ db *DB }
|
|
|
|
// ErrLinkRequired means an external identity matches an existing local
|
|
// password account but has not been explicitly linked. Callers must return a
|
|
// conflict instead of silently taking over the account.
|
|
var ErrLinkRequired = errors.New("account link required")
|
|
|
|
func NewUserRepo(d *DB) *UserRepo { return &UserRepo{d} }
|
|
|
|
func userFromObject(o Object) (*models.User, error) {
|
|
raw, err := json.Marshal(o)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var row struct {
|
|
ID string `json:"id"`
|
|
Name *string `json:"name"`
|
|
Email *string `json:"email"`
|
|
EmailVerified *string `json:"emailVerified"`
|
|
Image *string `json:"image"`
|
|
Password *string `json:"password"`
|
|
Role string `json:"role"`
|
|
TokenVersion int `json:"tokenVersion"`
|
|
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 {
|
|
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, 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) {
|
|
o, err := One(ctx, q, `SELECT to_jsonb(u) FROM "User" u WHERE `+Quote(field)+`=$1`, value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return userFromObject(o)
|
|
}
|
|
|
|
func (r *UserRepo) find(ctx context.Context, field, value string) (*models.User, error) {
|
|
return findUser(ctx, r.db, field, value)
|
|
}
|
|
func (r *UserRepo) FindByEmail(ctx context.Context, e string) (*models.User, error) {
|
|
return r.find(ctx, "email", e)
|
|
}
|
|
func (r *UserRepo) FindByID(ctx context.Context, id string) (*models.User, error) {
|
|
return r.find(ctx, "id", id)
|
|
}
|
|
func (r *UserRepo) FindByAccount(ctx context.Context, provider, providerAccountID string) (*models.User, error) {
|
|
o, err := One(ctx, r.db, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, provider, providerAccountID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return userFromObject(o)
|
|
}
|
|
func (r *UserRepo) SetRole(ctx context.Context, id, role string) error {
|
|
_, err := r.db.ExecContext(ctx, `UPDATE "User" SET role=$1,"updatedAt"=now() WHERE id=$2`, role, id)
|
|
return err
|
|
}
|
|
|
|
// BumpTokenVersion invalidates every cookie JWT issued for the user so far.
|
|
func (r *UserRepo) BumpTokenVersion(ctx context.Context, id string) error {
|
|
_, err := r.db.ExecContext(ctx, `UPDATE "User" SET "tokenVersion"="tokenVersion"+1,"updatedAt"=now() WHERE id=$1`, id)
|
|
return err
|
|
}
|
|
|
|
// SetPassword replaces the bcrypt hash AND bumps tokenVersion in one
|
|
// transaction: a password change (reset) must invalidate every session
|
|
// minted under the old credentials, the same revocation path as an explicit
|
|
// "sign out everywhere". Missing user reports ErrNotFound.
|
|
func (r *UserRepo) SetPassword(ctx context.Context, id, bcryptHash string) error {
|
|
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
|
|
res, err := tx.ExecContext(ctx, `UPDATE "User" SET password=$1,"tokenVersion"="tokenVersion"+1,"updatedAt"=now() WHERE id=$2`, bcryptHash, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
type NewUserInput struct {
|
|
ID, Name, Email, Password, Role string
|
|
EmailVerified *string
|
|
Image *string
|
|
// External users have no local password. The bootstrap logic still applies
|
|
// to the first external user on a fresh installation.
|
|
External bool
|
|
}
|
|
|
|
// createUserTx performs the shared bootstrap decision and inserts the row.
|
|
// The caller owns the transaction and the advisory lock; keeping this separate
|
|
// lets signup and external provisioning use exactly the same first-admin rules.
|
|
func createUserTx(ctx context.Context, tx *sql.Tx, u *NewUserInput) (string, error) {
|
|
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(927438)`); err != nil {
|
|
return "", err
|
|
}
|
|
var bootstrapDone bool
|
|
if err := tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT value->>'completed' FROM "AppSetting" WHERE key='adminBootstrap'),'false')::boolean`).Scan(&bootstrapDone); err != nil {
|
|
return "", err
|
|
}
|
|
var admins int
|
|
if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM "User" WHERE role='ADMIN' AND COALESCE(email,'') NOT LIKE '%@example.com'`).Scan(&admins); err != nil {
|
|
return "", err
|
|
}
|
|
role := u.Role
|
|
if role == "" {
|
|
role = "USER"
|
|
}
|
|
promote := config.AllowBootstrapSignup() && !bootstrapDone && admins == 0 && len(config.AdminEmails()) == 0 && !isTestEmail(u.Email) && role == "USER"
|
|
if promote {
|
|
role = "ADMIN"
|
|
}
|
|
// Record bootstrap completion as soon as the installation has (or was
|
|
// just given) a real administrator. A test-address signup with no
|
|
// admins present never claims the bootstrap.
|
|
if !bootstrapDone && (role == "ADMIN" || admins > 0) {
|
|
if _, err := tx.ExecContext(ctx, `INSERT INTO "AppSetting"(key,value) VALUES('adminBootstrap',jsonb_build_object('completed',true)) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value,"updatedAt"=now()`); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
var password any
|
|
if u.External {
|
|
password = nil
|
|
} else {
|
|
password = u.Password
|
|
}
|
|
var emailVerified any
|
|
if u.EmailVerified != nil {
|
|
emailVerified = *u.EmailVerified
|
|
}
|
|
var image any
|
|
if u.Image != nil {
|
|
image = *u.Image
|
|
}
|
|
_, err := Insert(ctx, tx, "User", Object{
|
|
"id": u.ID,
|
|
"name": u.Name,
|
|
"email": u.Email,
|
|
"password": password,
|
|
"role": role,
|
|
"emailVerified": emailVerified,
|
|
"image": image,
|
|
})
|
|
if err != nil {
|
|
return u.ID, err
|
|
}
|
|
// Tenancy phase 1: every created user lands in the implicit default
|
|
// tenant with a membership row, atomically with the user insert. This
|
|
// covers signup, OIDC provisioning and the seed CLI alike; real
|
|
// multi-tenant assignment arrives with the billing workstream.
|
|
return u.ID, attachDefaultTenantTx(ctx, tx, u.ID, role)
|
|
}
|
|
|
|
// A transaction-scoped lock serializes first-admin selection with signup.
|
|
//
|
|
// Review AUTH-06: initial provisioning is a one-shot lifecycle event,
|
|
// distinct from administrator recovery. Once bootstrap completion is
|
|
// recorded in AppSetting, the mere absence of a qualifying administrator —
|
|
// e.g. after demoting or removing the last one — never re-opens
|
|
// administrator assignment through signup. Recovery is operator-driven
|
|
// (ADMIN_EMAILS + make seed, or promotion by an existing admin).
|
|
func (r *UserRepo) Create(ctx context.Context, u *NewUserInput) (string, error) {
|
|
err := Transaction(ctx, r.db, func(tx *sql.Tx) error {
|
|
_, e := createUserTx(ctx, tx, u)
|
|
return e
|
|
})
|
|
return u.ID, err
|
|
}
|
|
|
|
// ExternalUserInput is the verified profile returned by the OIDC bridge.
|
|
// ProviderAccountID is the OIDC subject; it is only ever used to find the
|
|
// local account link, never as the local User.id.
|
|
type ExternalUserInput struct {
|
|
Provider string
|
|
ProviderAccountID string
|
|
Email string
|
|
EmailVerified bool
|
|
Name string
|
|
Image string
|
|
}
|
|
|
|
func insertAccountTx(ctx context.Context, tx *sql.Tx, userID string, in ExternalUserInput) error {
|
|
_, err := Insert(ctx, tx, "Account", Object{
|
|
"id": NewID(),
|
|
"userId": userID,
|
|
"type": "oidc",
|
|
"provider": in.Provider,
|
|
"providerAccountId": in.ProviderAccountID,
|
|
})
|
|
return err
|
|
}
|
|
|
|
// ErrAccountLinked means the external subject is already linked to a
|
|
// different local user; an operator must unlink it deliberately first.
|
|
var ErrAccountLinked = errors.New("account already linked")
|
|
|
|
func (r *UserRepo) LinkExternal(ctx context.Context, userID, provider, subject string) error {
|
|
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
|
|
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, provider+":"+subject); err != nil {
|
|
return err
|
|
}
|
|
if _, err := findUser(ctx, tx, "id", userID); err != nil {
|
|
return err
|
|
}
|
|
var existing string
|
|
err := tx.QueryRowContext(ctx, `SELECT "userId" FROM "Account" WHERE provider=$1 AND "providerAccountId"=$2`, provider, subject).Scan(&existing)
|
|
if err == nil {
|
|
if existing == userID {
|
|
return nil
|
|
}
|
|
return ErrAccountLinked
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
_, err = Insert(ctx, tx, "Account", Object{
|
|
"id": NewID(),
|
|
"userId": userID,
|
|
"type": "oidc",
|
|
"provider": provider,
|
|
"providerAccountId": subject,
|
|
})
|
|
return err
|
|
})
|
|
}
|
|
|
|
// ProvisionExternal resolves an OIDC identity to a local user. The advisory
|
|
// lock is keyed by provider+subject so concurrent first logins cannot create
|
|
// duplicate accounts. Linking policy is deliberately conservative:
|
|
//
|
|
// - an existing Account link is authoritative;
|
|
// - a matching local account with no password may be linked only when the
|
|
// IdP asserts a verified email;
|
|
// - a matching local password account returns ErrLinkRequired (409) and must
|
|
// be linked explicitly by an operator; email alone is not proof of identity.
|
|
func (r *UserRepo) ProvisionExternal(ctx context.Context, in ExternalUserInput) (*models.User, error) {
|
|
var out *models.User
|
|
err := Transaction(ctx, r.db, func(tx *sql.Tx) error {
|
|
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, in.Provider+":"+in.ProviderAccountID); err != nil {
|
|
return err
|
|
}
|
|
// 1. Existing provider link is authoritative.
|
|
o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, in.Provider, in.ProviderAccountID)
|
|
if err == nil {
|
|
u, err := userFromObject(o)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if in.EmailVerified && u.EmailVerified == nil {
|
|
if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil {
|
|
return err
|
|
}
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
u.EmailVerified = &now
|
|
}
|
|
out = u
|
|
return nil
|
|
}
|
|
if !errors.Is(err, ErrNotFound) {
|
|
return err
|
|
}
|
|
|
|
// 2. Existing local account with the same email.
|
|
if in.Email != "" {
|
|
o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "User" u WHERE email=$1`, in.Email)
|
|
if err == nil {
|
|
u, err := userFromObject(o)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if u.Password != nil && *u.Password != "" {
|
|
return ErrLinkRequired
|
|
}
|
|
if !in.EmailVerified {
|
|
return ErrLinkRequired
|
|
}
|
|
if err := insertAccountTx(ctx, tx, u.ID, in); err != nil {
|
|
return err
|
|
}
|
|
if u.EmailVerified == nil {
|
|
if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil {
|
|
return err
|
|
}
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
u.EmailVerified = &now
|
|
}
|
|
out = u
|
|
return nil
|
|
}
|
|
if !errors.Is(err, ErrNotFound) {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// 3. New external user. Name falls back to the email local part.
|
|
// Operator-listed addresses (ADMIN_EMAILS) become ADMIN at first SSO
|
|
// login: on AUTH_MODE=oidc deployments this is the only bootstrap
|
|
// path — password login, signup and the seeded-password flow are all
|
|
// unavailable there. Same trust semantics as --seed.
|
|
role := "USER"
|
|
if config.IsAdminEmail(in.Email) {
|
|
role = "ADMIN"
|
|
}
|
|
id := NewID()
|
|
name := strings.TrimSpace(in.Name)
|
|
if name == "" {
|
|
name = strings.SplitN(in.Email, "@", 2)[0]
|
|
}
|
|
var verified *string
|
|
if in.EmailVerified {
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
verified = &now
|
|
}
|
|
var image *string
|
|
if in.Image != "" {
|
|
img := in.Image
|
|
image = &img
|
|
}
|
|
if _, err := createUserTx(ctx, tx, &NewUserInput{
|
|
ID: id,
|
|
Name: name,
|
|
Email: in.Email,
|
|
Role: role,
|
|
EmailVerified: verified,
|
|
Image: image,
|
|
External: true,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if err := insertAccountTx(ctx, tx, id, in); err != nil {
|
|
return err
|
|
}
|
|
u, err := findUser(ctx, tx, "id", id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
out = u
|
|
return nil
|
|
})
|
|
return out, err
|
|
}
|
|
func isTestEmail(e string) bool { return len(e) >= 12 && e[len(e)-12:] == "@example.com" }
|
|
func IsAdminEmail(email string) bool { return config.IsAdminEmail(email) }
|