Open source CapCut alternative.
TypeScript
feat(site): give an account its own name and picture
David Le3737274759d3
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prismaindex a59b59c1..e28d30c0 100644--- a/site/prisma/Auth.prisma+++ b/site/prisma/Auth.prisma@@ -1,6 +1,9 @@model User {id String @id+ // The name Google gave us at sign-in. Never edited in the product.name String+ // The name the product shows instead, when the user has set one.+ displayName String?email String @uniqueemailVerified Boolean @default(false)image String?@@ -21,10 +24,21 @@ model User {apiKeys Apikey[]visionApiSubscription VisionApiSubscription?proSubscription ProSubscription?+ avatar UserAvatar?@@map("user")}+// The picture the user uploaded, already cropped and compressed by the client.+// Kept out of `user` so the row every session read touches stays small.+model UserAvatar {+ userId String @id+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ data Bytes+ contentType String+ updatedAt DateTime @updatedAt+}+model Session {id String @idexpiresAt DateTimediff --git a/site/prisma/migrations/20260727074915/migration.sql b/site/prisma/migrations/20260727074915/migration.sqlnew file mode 100644index 00000000..b5b544ed--- /dev/null+++ b/site/prisma/migrations/20260727074915/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "user" ADD COLUMN "displayName" TEXT;diff --git a/site/prisma/migrations/20260727075843/migration.sql b/site/prisma/migrations/20260727075843/migration.sqlnew file mode 100644index 00000000..e905b15c--- /dev/null+++ b/site/prisma/migrations/20260727075843/migration.sql@@ -0,0 +1,12 @@+-- CreateTable+CREATE TABLE "UserAvatar" (+ "userId" TEXT NOT NULL,+ "data" BYTEA NOT NULL,+ "contentType" TEXT NOT NULL,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "UserAvatar_pkey" PRIMARY KEY ("userId")+);++-- AddForeignKey+ALTER TABLE "UserAvatar" ADD CONSTRAINT "UserAvatar_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/site/src/app/api/account/avatar/route.ts b/site/src/app/api/account/avatar/route.tsnew file mode 100644index 00000000..7f9ebbf1--- /dev/null+++ b/site/src/app/api/account/avatar/route.ts@@ -0,0 +1,63 @@+import { NextResponse } from "next/server";++import {+ notFoundResponse,+ withDonkeyAuth,+ type DonkeyAuthenticatedRequest,+} from "@/lib/donkey-api-auth";+import { accountProfile } from "@/lib/account-profile";+import { prisma } from "@/lib/prisma";++export const dynamic = "force-dynamic";++// The client crops to a square and re-encodes before uploading, so anything+// arriving here is already small. The cap is a backstop against a caller that+// skips that path, not a size the UI ever approaches.+const MAX_BYTES = 256 * 1024;+const ALLOWED_TYPES = new Set(["image/webp", "image/jpeg", "image/png"]);++// The signed-in user's own uploaded picture. Callers address it without a user+// id — the session decides whose bytes come back — and the profile hands out a+// URL stamped with `updatedAt`, so the response can be cached hard and a new+// upload lands on a new URL.+export const GET = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const avatar = await prisma.userAvatar.findUnique({+ where: { userId: request.donkey.userId },+ });+ if (!avatar) return notFoundResponse();++ return new NextResponse(new Blob([avatar.data], { type: avatar.contentType }), {+ headers: {+ "Cache-Control": "private, max-age=31536000, immutable",+ "Content-Type": avatar.contentType,+ "X-Content-Type-Options": "nosniff",+ },+ });+});++export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const contentType = request.headers.get("content-type")?.split(";")[0].trim() ?? "";+ if (!ALLOWED_TYPES.has(contentType)) {+ return NextResponse.json({ error: "Unsupported image type." }, { status: 415 });+ }++ const data = new Uint8Array(await request.arrayBuffer());+ if (data.byteLength === 0 || data.byteLength > MAX_BYTES) {+ return NextResponse.json({ error: "Image too large." }, { status: 413 });+ }++ const userId = request.donkey.userId;+ await prisma.userAvatar.upsert({+ create: { contentType, data, userId },+ update: { contentType, data },+ where: { userId },+ });++ return NextResponse.json(await accountProfile(userId));+});++export const DELETE = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const userId = request.donkey.userId;+ await prisma.userAvatar.deleteMany({ where: { userId } });+ return NextResponse.json(await accountProfile(userId));+});diff --git a/site/src/app/api/account/profile/route.ts b/site/src/app/api/account/profile/route.tsnew file mode 100644index 00000000..6289a1b8--- /dev/null+++ b/site/src/app/api/account/profile/route.ts@@ -0,0 +1,40 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import { accountProfile } from "@/lib/account-profile";+import {+ notFoundResponse,+ withDonkeyAuth,+ type DonkeyAuthenticatedRequest,+} from "@/lib/donkey-api-auth";+import { validationErrorResponse } from "@/lib/inference/responses";+import { prisma } from "@/lib/prisma";++export const dynamic = "force-dynamic";++// The visible name is the product's own field. `name` keeps whatever Google+// gave us at sign-in — billing and the provider record depend on it — so a+// user renaming themselves writes `displayName`, and clearing it falls back to+// the Google name rather than blanking the account.+const updateProfileSchema = z.object({+ displayName: z.string().trim().max(60).nullable(),+});++export const GET = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const profile = await accountProfile(request.donkey.userId);+ if (!profile) return notFoundResponse();+ return NextResponse.json(profile);+});++export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {+ const parsed = updateProfileSchema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return validationErrorResponse(parsed.error);++ const userId = request.donkey.userId;+ await prisma.user.update({+ data: { displayName: parsed.data.displayName || null },+ where: { id: userId },+ });++ return NextResponse.json(await accountProfile(userId));+});diff --git a/site/src/lib/account-profile.ts b/site/src/lib/account-profile.tsnew file mode 100644index 00000000..e7ea094b--- /dev/null+++ b/site/src/lib/account-profile.ts@@ -0,0 +1,29 @@+import { prisma } from "@/lib/prisma";++// The account as the product shows it, shared by every route that hands the+// profile back so the name and picture can't drift between them.+//+// `name` stays whatever the identity provider gave us at sign-in; `displayName`+// is the one the user chose. The picture is the uploaded one when there is one,+// addressed by a URL stamped with its `updatedAt` so a new upload busts the+// browser's cache, and the provider's hotlinked image otherwise.+export async function accountProfile(userId: string) {+ const [user, avatar] = await Promise.all([+ prisma.user.findUnique({+ select: { displayName: true, email: true, image: true, name: true },+ where: { id: userId },+ }),+ prisma.userAvatar.findUnique({+ select: { updatedAt: true },+ where: { userId },+ }),+ ]);+ if (!user) return null;++ return {+ displayName: user.displayName,+ email: user.email,+ image: avatar ? `/api/account/avatar?v=${avatar.updatedAt.getTime()}` : user.image,+ name: user.name,+ };+}diff --git a/site/src/queries/accountProfile.ts b/site/src/queries/accountProfile.tsnew file mode 100644index 00000000..26a3f8d7--- /dev/null+++ b/site/src/queries/accountProfile.ts@@ -0,0 +1,74 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import { apiFetch } from "@/queries/apiClient";++export const accountProfileQueryKey = ["account-profile"] as const;++export type AccountProfile = {+ // The name Google gave us at sign-in.+ name: string;+ // The name the user chose for the product, when they've set one.+ displayName: string | null;+ email: string;+ image: string | null;+};++// What the product calls you: your chosen name when you have one, otherwise+// the Google name. Every surface that shows the user's name reads this.+export function visibleName(profile: AccountProfile | undefined, fallback: string) {+ return profile?.displayName || profile?.name || fallback;+}++// `enabled` is for the signed-out case: the sidebar mounts this hook above its+// own session check, and the route answers 401 without a session.+export function useAccountProfile(options?: { enabled?: boolean }) {+ return useQuery({+ enabled: options?.enabled ?? true,+ queryFn: () => apiFetch<AccountProfile>("/api/account/profile"),+ queryKey: accountProfileQueryKey,+ });+}++// The picture arrives already cropped and compressed by the editor dialog, so+// it uploads as raw bytes rather than a base64 payload.+export function useUpdateAvatar() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (image: Blob) =>+ apiFetch<AccountProfile>("/api/account/avatar", {+ body: image,+ headers: { "Content-Type": image.type },+ method: "PUT",+ }),+ onSuccess: (profile) => {+ queryClient.setQueryData(accountProfileQueryKey, profile);+ },+ });+}++export function useRemoveAvatar() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: () =>+ apiFetch<AccountProfile>("/api/account/avatar", { method: "DELETE" }),+ onSuccess: (profile) => {+ queryClient.setQueryData(accountProfileQueryKey, profile);+ },+ });+}++export function useUpdateDisplayName() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (displayName: string | null) =>+ apiFetch<AccountProfile>("/api/account/profile", {+ body: JSON.stringify({ displayName }),+ method: "PUT",+ }),+ onSuccess: (profile) => {+ queryClient.setQueryData(accountProfileQueryKey, profile);+ },+ });+}