Compare commits
3 Commits
c54c554374
...
a1a11ff5e5
| Author | SHA1 | Date | |
|---|---|---|---|
| a1a11ff5e5 | |||
| e98a9c3bb7 | |||
| d7e0d7eada |
@@ -12,7 +12,7 @@ export default async function SettingsPage() {
|
||||
|
||||
const dbUser = await db.query.users.findFirst({
|
||||
where: eq(users.id, session.user.id),
|
||||
columns: { bio: true, privateBio: true, isPrivate: true },
|
||||
columns: { bio: true, privateBio: true, isPrivate: true, hasCustomAvatar: true, avatarUrl: true },
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -20,11 +20,12 @@ export default async function SettingsPage() {
|
||||
user={{
|
||||
name: session.user.name,
|
||||
email: session.user.email,
|
||||
image: session.user.image ?? null,
|
||||
image: dbUser?.avatarUrl ?? null,
|
||||
locale: (session.user as { locale?: string }).locale ?? "en",
|
||||
bio: dbUser?.bio ?? null,
|
||||
privateBio: dbUser?.privateBio ?? null,
|
||||
isPrivate: dbUser?.isPrivate ?? false,
|
||||
hasCustomAvatar: dbUser?.hasCustomAvatar ?? false,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export default async function ShoppingListPage({ params }: Params) {
|
||||
</div>
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
|
||||
<GroceryExportButton listId={id} instacartEnabled={instacartEnabled} />
|
||||
{access.role === "owner" && <ShareShoppingListButton listId={id} />}
|
||||
{access.role === "owner" && <ShareShoppingListButton listId={id} initialIsPublic={list.isPublic} />}
|
||||
<Link href={`/print/shopping-list/${id}`} target="_blank" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
|
||||
<Printer className="h-4 w-4" />
|
||||
{m.common.print}
|
||||
|
||||
@@ -26,6 +26,7 @@ export async function GET(_req: NextRequest, { params }: Params) {
|
||||
const PatchSchema = z.object({
|
||||
completed: z.boolean().optional(),
|
||||
name: z.string().min(1).max(100).optional(),
|
||||
isPublic: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: Params) {
|
||||
@@ -45,6 +46,11 @@ export async function PATCH(req: NextRequest, { params }: Params) {
|
||||
await db.update(shoppingLists).set({ name: body.data.name }).where(eq(shoppingLists.id, id));
|
||||
}
|
||||
|
||||
if (body.data.isPublic !== undefined) {
|
||||
if (access.role !== "owner") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
await db.update(shoppingLists).set({ isPublic: body.data.isPublic }).where(eq(shoppingLists.id, id));
|
||||
}
|
||||
|
||||
if (body.data.completed) {
|
||||
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
// Mark all items as checked
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { createPresignedUploadUrl } from "@/lib/storage";
|
||||
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
|
||||
|
||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] as const;
|
||||
type AllowedType = (typeof ALLOWED_TYPES)[number];
|
||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
const Schema = z.object({
|
||||
contentType: z.string().refine((t): t is AllowedType => (ALLOWED_TYPES as readonly string[]).includes(t), {
|
||||
message: "Content type must be jpeg, png, webp, or avif",
|
||||
}),
|
||||
fileSize: z.number().int().positive().max(MAX_FILE_SIZE, "File exceeds 5MB limit"),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const { contentType, fileSize } = parsed.data;
|
||||
|
||||
try {
|
||||
const sizeMb = Math.ceil(fileSize / (1024 * 1024));
|
||||
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "storage", sizeMb);
|
||||
} catch (err) {
|
||||
if (err instanceof TierLimitError) {
|
||||
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const ext = contentType.split("/")[1] ?? "jpg";
|
||||
const key = `user-avatars/${session!.user.id}/${crypto.randomUUID()}.${ext}`;
|
||||
const url = await createPresignedUploadUrl(key, contentType);
|
||||
|
||||
return NextResponse.json({ url, key });
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { z } from "zod";
|
||||
import { gravatarUrl } from "@/lib/gravatar";
|
||||
|
||||
const PatchSchema = z.object({
|
||||
name: z.string().min(1).max(100).optional(),
|
||||
@@ -10,6 +11,8 @@ const PatchSchema = z.object({
|
||||
bio: z.string().max(500).optional().nullable(),
|
||||
privateBio: z.string().max(2000).optional().nullable(),
|
||||
isPrivate: z.boolean().optional(),
|
||||
// A custom-uploaded avatar URL, or null to revert to the Gravatar fallback.
|
||||
avatarUrl: z.string().url().max(2048).optional().nullable(),
|
||||
});
|
||||
|
||||
export async function PATCH(req: Request) {
|
||||
@@ -19,6 +22,18 @@ export async function PATCH(req: Request) {
|
||||
const body = PatchSchema.safeParse(await req.json());
|
||||
if (!body.success) return NextResponse.json({ error: body.error.flatten() }, { status: 400 });
|
||||
|
||||
await db.update(users).set(body.data).where(eq(users.id, session.user.id));
|
||||
return NextResponse.json({ ok: true });
|
||||
const { avatarUrl, ...rest } = body.data;
|
||||
const updates: Partial<typeof users.$inferInsert> = { ...rest };
|
||||
if (avatarUrl !== undefined) {
|
||||
if (avatarUrl === null) {
|
||||
updates.avatarUrl = gravatarUrl(session.user.email);
|
||||
updates.hasCustomAvatar = false;
|
||||
} else {
|
||||
updates.avatarUrl = avatarUrl;
|
||||
updates.hasCustomAvatar = true;
|
||||
}
|
||||
}
|
||||
|
||||
await db.update(users).set(updates).where(eq(users.id, session.user.id));
|
||||
return NextResponse.json({ ok: true, avatarUrl: updates.avatarUrl });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Globe } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, shoppingLists, eq, and } from "@epicure/db";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const list = await db.query.shoppingLists.findFirst({
|
||||
where: and(eq(shoppingLists.id, id), eq(shoppingLists.isPublic, true)),
|
||||
});
|
||||
if (!list) return {};
|
||||
return { title: list.name };
|
||||
}
|
||||
|
||||
export default async function PublicShoppingListPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
|
||||
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
|
||||
const OTHER = m.mealPlan.aisleOther;
|
||||
|
||||
const list = await db.query.shoppingLists.findFirst({
|
||||
where: and(eq(shoppingLists.id, id), eq(shoppingLists.isPublic, true)),
|
||||
with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.sortOrder), asc(t.rawName)] } },
|
||||
});
|
||||
|
||||
if (!list) notFound();
|
||||
|
||||
const byAisle = list.items.reduce<Record<string, typeof list.items>>((acc, item) => {
|
||||
const key = item.aisle ?? OTHER;
|
||||
(acc[key] ??= []).push(item);
|
||||
return acc;
|
||||
}, {});
|
||||
const aisles = Object.keys(byAisle).sort((a, b) => (a === OTHER ? 1 : b === OTHER ? -1 : a.localeCompare(b)));
|
||||
|
||||
return (
|
||||
<div className="container mx-auto max-w-2xl px-4 py-8 space-y-6">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Globe className="h-3.5 w-3.5" />
|
||||
<span>{m.publicShoppingList.sharedList}</span>
|
||||
{!session && (
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>{m.publicRecipe.signUpFree}</Link>
|
||||
<Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>{m.publicRecipe.logIn}</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{list.name}</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{formatMessage(m.shoppingLists.itemsChecked, {
|
||||
checked: list.items.filter((i) => i.checked).length,
|
||||
total: list.items.length,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{aisles.map((aisle) => (
|
||||
<div key={aisle} className="space-y-2">
|
||||
{aisles.length > 1 && (
|
||||
<h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground border-b pb-1">{aisle}</h2>
|
||||
)}
|
||||
<ul className="space-y-1.5">
|
||||
{byAisle[aisle]!.map((item) => (
|
||||
<li key={item.id} className="flex items-baseline gap-2 text-sm">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block h-4 w-4 shrink-0 rounded border translate-y-0.5",
|
||||
item.checked ? "bg-foreground border-foreground" : "border-input"
|
||||
)}
|
||||
/>
|
||||
<span className="text-muted-foreground tabular-nums min-w-[3.5rem]">
|
||||
{[item.quantity, item.unit].filter(Boolean).join(" ")}
|
||||
</span>
|
||||
<span className={cn(item.checked && "line-through text-muted-foreground")}>{item.rawName}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{!session && (
|
||||
<div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
|
||||
<p className="font-semibold">{m.publicShoppingList.wantYourOwn}</p>
|
||||
<p className="text-sm text-muted-foreground">{m.publicRecipe.wantToSaveDescription}</p>
|
||||
<Link href="/signup" className={cn(buttonVariants())}>{m.publicRecipe.getStartedFree}</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Clock, Users, Lock, Globe, Link2 } from "lucide-react";
|
||||
import { Clock, Users, Lock, Globe, Link2, ExternalLink } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
@@ -19,6 +19,7 @@ type Recipe = {
|
||||
visibility: "private" | "unlisted" | "public";
|
||||
updatedAt: Date;
|
||||
photos?: Array<{ storageKey: string; isCover: boolean }>;
|
||||
sourceUrl?: string | null;
|
||||
};
|
||||
|
||||
const VISIBILITY_ICON = {
|
||||
@@ -85,7 +86,10 @@ export function RecipeCard({ recipe }: { recipe: Recipe }) {
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<VisibilityIcon className="h-3 w-3" />
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{recipe.sourceUrl && <ExternalLink className="h-3 w-3" />}
|
||||
<VisibilityIcon className="h-3 w-3" />
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Link>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import Image from "next/image";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus, ChefHat } from "lucide-react";
|
||||
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus, ChefHat, ExternalLink } from "lucide-react";
|
||||
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -47,6 +47,7 @@ type Recipe = {
|
||||
isFavorited?: boolean;
|
||||
isBatchCook?: boolean;
|
||||
dishCount?: number;
|
||||
sourceUrl?: string | null;
|
||||
};
|
||||
|
||||
/** Stops the click from bubbling to the card's own Link/select handler. */
|
||||
@@ -63,6 +64,14 @@ const VIEW_STORAGE_KEY = "epicure-recipes-view";
|
||||
const DIFFICULTY_COLOR = { easy: "default", medium: "secondary", hard: "destructive" } as const;
|
||||
const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe };
|
||||
|
||||
function hostnameOf(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function RecipeThumb({ recipe, selectMode, selected, className }: { recipe: Recipe; selectMode: boolean; selected: boolean; className?: string }) {
|
||||
const cover = recipe.photos?.find((p) => p.isCover) ?? recipe.photos?.[0];
|
||||
return (
|
||||
@@ -152,6 +161,14 @@ function GridCard({ recipe, selected, selectMode }: { recipe: Recipe; selected:
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{recipe.sourceUrl && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={<span className="p-1.5 inline-flex"><ExternalLink className="h-3.5 w-3.5 text-muted-foreground" /></span>} />
|
||||
<TooltipContent>{t("importedFrom", { host: hostnameOf(recipe.sourceUrl) })}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{recipe.isBatchCook && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
@@ -199,6 +216,14 @@ function ListRow({ recipe, selected, selectMode }: { recipe: Recipe; selected: b
|
||||
{recipe.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{recipe.sourceUrl && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={<span className="p-1.5 inline-flex"><ExternalLink className="h-3.5 w-3.5 text-muted-foreground" /></span>} />
|
||||
<TooltipContent>{t("importedFrom", { host: hostnameOf(recipe.sourceUrl) })}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{recipe.isBatchCook && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
@@ -276,6 +301,14 @@ function CompactRow({ recipe, selected, selectMode }: { recipe: Recipe; selected
|
||||
<span className="hidden md:inline text-xs text-muted-foreground shrink-0 w-16 text-right">
|
||||
{recipe.updatedAt.toLocaleDateString(locale, { month: "short", day: "numeric" })}
|
||||
</span>
|
||||
{recipe.sourceUrl && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={<span className="p-1.5 inline-flex shrink-0"><ExternalLink className="h-3.5 w-3.5 text-muted-foreground" /></span>} />
|
||||
<TooltipContent>{t("importedFrom", { host: hostnameOf(recipe.sourceUrl) })}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{recipe.isBatchCook && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { toast } from "sonner";
|
||||
import { Camera, Loader2, X } from "lucide-react";
|
||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function AvatarUploader({
|
||||
name,
|
||||
image,
|
||||
hasCustomAvatar,
|
||||
onChange,
|
||||
}: {
|
||||
name: string;
|
||||
image: string | null;
|
||||
hasCustomAvatar: boolean;
|
||||
onChange: (image: string | null, hasCustomAvatar: boolean) => void;
|
||||
}) {
|
||||
const t = useTranslations("settingsForm");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
async function handleFile(file: File) {
|
||||
setUploading(true);
|
||||
setPreview(URL.createObjectURL(file));
|
||||
try {
|
||||
const presignRes = await fetch("/api/v1/upload/avatar-presign", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ contentType: file.type, fileSize: file.size }),
|
||||
});
|
||||
if (!presignRes.ok) {
|
||||
const err = await presignRes.json() as { error?: string };
|
||||
toast.error(err.error ?? t("avatarUploadFailed"));
|
||||
return;
|
||||
}
|
||||
const { url } = await presignRes.json() as { url: string; key: string };
|
||||
await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
|
||||
|
||||
// The presigned PUT URL is already publicUrl/bucket/key with query-string
|
||||
// signing params appended — strip those to get the plain public GET URL.
|
||||
const saveRes = await fetch("/api/v1/users/me", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ avatarUrl: url.split("?")[0] }),
|
||||
});
|
||||
if (!saveRes.ok) {
|
||||
toast.error(t("avatarUploadFailed"));
|
||||
return;
|
||||
}
|
||||
const saved = await saveRes.json() as { avatarUrl?: string };
|
||||
onChange(saved.avatarUrl ?? url.split("?")[0]!, true);
|
||||
toast.success(t("avatarUploadSuccess"));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemove() {
|
||||
setUploading(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/users/me", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ avatarUrl: null }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(t("avatarUploadFailed"));
|
||||
return;
|
||||
}
|
||||
const saved = await res.json() as { avatarUrl?: string };
|
||||
setPreview(null);
|
||||
onChange(saved.avatarUrl ?? null, false);
|
||||
toast.success(t("avatarRemoved"));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative">
|
||||
<Avatar size="lg" className="size-16">
|
||||
<AvatarImage src={preview ?? image ?? undefined} alt={name} />
|
||||
<AvatarFallback className="text-lg">{name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
{uploading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-white" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/avif"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void handleFile(file);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => inputRef.current?.click()} disabled={uploading}>
|
||||
<Camera className="h-4 w-4" />
|
||||
{t("changePhoto")}
|
||||
</Button>
|
||||
{hasCustomAvatar && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void handleRemove(); }}
|
||||
disabled={uploading}
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
{t("removePhoto")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLocale, SUPPORTED_LOCALES, type Locale } from "@/lib/i18n/provider";
|
||||
import { AvatarUploader } from "./avatar-uploader";
|
||||
|
||||
type UserProps = {
|
||||
name: string;
|
||||
@@ -19,6 +20,7 @@ type UserProps = {
|
||||
bio: string | null;
|
||||
privateBio: string | null;
|
||||
isPrivate: boolean;
|
||||
hasCustomAvatar: boolean;
|
||||
};
|
||||
|
||||
export function SettingsForm({ user }: { user: UserProps }) {
|
||||
@@ -26,6 +28,8 @@ export function SettingsForm({ user }: { user: UserProps }) {
|
||||
const t_common = useTranslations("common");
|
||||
const { setLocale } = useLocale();
|
||||
|
||||
const [avatarImage, setAvatarImage] = useState(user.image);
|
||||
const [hasCustomAvatar, setHasCustomAvatar] = useState(user.hasCustomAvatar);
|
||||
const [name, setName] = useState(user.name);
|
||||
const [bio, setBio] = useState(user.bio ?? "");
|
||||
const [privateBio, setPrivateBio] = useState(user.privateBio ?? "");
|
||||
@@ -96,6 +100,15 @@ export function SettingsForm({ user }: { user: UserProps }) {
|
||||
<div className="space-y-6">
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<h2 className="font-semibold text-lg">{t("profile")}</h2>
|
||||
<AvatarUploader
|
||||
name={user.name}
|
||||
image={avatarImage}
|
||||
hasCustomAvatar={hasCustomAvatar}
|
||||
onChange={(image, custom) => {
|
||||
setAvatarImage(image);
|
||||
setHasCustomAvatar(custom);
|
||||
}}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<Label>{t("displayName")}</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { UserPlus, X } from "lucide-react";
|
||||
import { UserPlus, X, Link2, Copy, Check } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
type Role = "viewer" | "editor";
|
||||
|
||||
@@ -38,9 +40,10 @@ interface Member {
|
||||
|
||||
interface Props {
|
||||
listId: string;
|
||||
initialIsPublic: boolean;
|
||||
}
|
||||
|
||||
export function ShareShoppingListButton({ listId }: Props) {
|
||||
export function ShareShoppingListButton({ listId, initialIsPublic }: Props) {
|
||||
const t = useTranslations("shoppingLists");
|
||||
const ts = useTranslations("shareDialog");
|
||||
const tCommon = useTranslations("common");
|
||||
@@ -50,6 +53,42 @@ export function ShareShoppingListButton({ listId }: Props) {
|
||||
const [members, setMembers] = useState<Member[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [inviting, setInviting] = useState(false);
|
||||
const [isPublic, setIsPublic] = useState(initialIsPublic);
|
||||
const [savingPublic, setSavingPublic] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function togglePublic(checked: boolean) {
|
||||
setSavingPublic(true);
|
||||
const previous = isPublic;
|
||||
setIsPublic(checked);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/shopping-lists/${listId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ isPublic: checked }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setIsPublic(previous);
|
||||
toast.error(ts("publicLinkToggleFailed"));
|
||||
}
|
||||
} catch {
|
||||
setIsPublic(previous);
|
||||
toast.error(ts("publicLinkToggleFailed"));
|
||||
} finally {
|
||||
setSavingPublic(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyLink() {
|
||||
const url = `${window.location.origin}/s/${listId}`;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
toast.error(ts("copyLinkFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchMembers() {
|
||||
setLoading(true);
|
||||
@@ -130,6 +169,25 @@ export function ShareShoppingListButton({ listId }: Props) {
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Link2 className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{ts("publicLinkTitle")}</p>
|
||||
<p className="text-xs text-muted-foreground">{ts("publicLinkDescription")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Switch checked={isPublic} disabled={savingPublic} onCheckedChange={(v) => { void togglePublic(v); }} />
|
||||
</div>
|
||||
{isPublic && (
|
||||
<Button type="button" variant="outline" size="sm" className="w-full" onClick={() => void copyLink()}>
|
||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
{copied ? ts("linkCopied") : ts("copyLink")}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex gap-2 mt-2">
|
||||
<Input
|
||||
type="email"
|
||||
|
||||
@@ -5,6 +5,7 @@ import { db, users, sessions, accounts, verifications, eq, count } from "@epicur
|
||||
import { sendEmail, verifyEmailHtml, resetPasswordHtml, welcomeHtml } from "@/lib/email";
|
||||
import { isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { findValidInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
|
||||
import { gravatarUrl } from "@/lib/gravatar";
|
||||
|
||||
export const auth = betterAuth({
|
||||
trustedOrigins: [process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"],
|
||||
@@ -100,6 +101,13 @@ export const auth = betterAuth({
|
||||
await db.update(users).set({ role: "admin" }).where(eq(users.id, user.id));
|
||||
}
|
||||
|
||||
// Only email/password signups land here without an avatar already
|
||||
// set (OAuth providers set `image` — mapped to avatarUrl — before
|
||||
// this hook runs) — give them a Gravatar-backed default.
|
||||
if (!user.image) {
|
||||
await db.update(users).set({ avatarUrl: gravatarUrl(user.email) }).where(eq(users.id, user.id));
|
||||
}
|
||||
|
||||
// Consume the invite that gated this signup, if any (regardless of
|
||||
// whether signups have since been re-enabled/disabled).
|
||||
const token = context?.getCookie(INVITE_COOKIE);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createHash } from "crypto";
|
||||
|
||||
// Gravatar keys avatars by MD5 of the trimmed, lowercased email — no other
|
||||
// normalization is defined by their API.
|
||||
export function gravatarUrl(email: string, size = 200): string {
|
||||
const hash = createHash("md5").update(email.trim().toLowerCase()).digest("hex");
|
||||
// d=404 makes Gravatar 404 instead of serving a placeholder when no avatar
|
||||
// is registered for the hash, so callers relying on <img onError> fallback
|
||||
// (e.g. the Avatar component's initials fallback) behave correctly.
|
||||
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=404`;
|
||||
}
|
||||
@@ -56,6 +56,7 @@
|
||||
"recipe": {
|
||||
"byAuthor": "by {name}",
|
||||
"source": "Source",
|
||||
"importedFrom": "Imported from {host}",
|
||||
"share": "Share",
|
||||
"shareLinkCopied": "Link copied to clipboard",
|
||||
"shareCopyFailed": "Failed to copy link",
|
||||
@@ -351,6 +352,10 @@
|
||||
"sun": "Sunday"
|
||||
}
|
||||
},
|
||||
"publicShoppingList": {
|
||||
"sharedList": "Shared shopping list",
|
||||
"wantYourOwn": "Want your own shopping lists?"
|
||||
},
|
||||
"publicRecipe": {
|
||||
"publicRecipeBy": "Public recipe by",
|
||||
"viewInLibrary": "View in your library",
|
||||
@@ -960,7 +965,13 @@
|
||||
"loadMembersFailed": "Could not load members",
|
||||
"memberRemoved": "Member removed",
|
||||
"removeMemberFailed": "Could not remove member",
|
||||
"enterEmail": "Enter an email address"
|
||||
"enterEmail": "Enter an email address",
|
||||
"publicLinkTitle": "Public link",
|
||||
"publicLinkDescription": "Anyone with the link can view this list.",
|
||||
"publicLinkToggleFailed": "Could not update the public link",
|
||||
"copyLink": "Copy link",
|
||||
"linkCopied": "Link copied",
|
||||
"copyLinkFailed": "Could not copy link"
|
||||
},
|
||||
"social": {
|
||||
"followed": "Following",
|
||||
@@ -1055,6 +1066,11 @@
|
||||
},
|
||||
"settingsForm": {
|
||||
"profile": "Profile",
|
||||
"changePhoto": "Change photo",
|
||||
"removePhoto": "Remove photo",
|
||||
"avatarUploadSuccess": "Profile photo updated",
|
||||
"avatarUploadFailed": "Failed to update profile photo",
|
||||
"avatarRemoved": "Profile photo removed",
|
||||
"displayName": "Display name",
|
||||
"email": "Email",
|
||||
"emailReadOnly": "Email cannot be changed here.",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"recipe": {
|
||||
"byAuthor": "par {name}",
|
||||
"source": "Source",
|
||||
"importedFrom": "Importée depuis {host}",
|
||||
"share": "Partager",
|
||||
"shareLinkCopied": "Lien copié dans le presse-papiers",
|
||||
"shareCopyFailed": "Échec de la copie du lien",
|
||||
@@ -351,6 +352,10 @@
|
||||
"sun": "Dimanche"
|
||||
}
|
||||
},
|
||||
"publicShoppingList": {
|
||||
"sharedList": "Liste de courses partagée",
|
||||
"wantYourOwn": "Envie de vos propres listes de courses ?"
|
||||
},
|
||||
"publicRecipe": {
|
||||
"publicRecipeBy": "Recette publique par",
|
||||
"viewInLibrary": "Voir dans votre bibliothèque",
|
||||
@@ -948,7 +953,13 @@
|
||||
"loadMembersFailed": "Impossible de charger les membres",
|
||||
"memberRemoved": "Membre retiré",
|
||||
"removeMemberFailed": "Impossible de retirer le membre",
|
||||
"enterEmail": "Saisissez une adresse e-mail"
|
||||
"enterEmail": "Saisissez une adresse e-mail",
|
||||
"publicLinkTitle": "Lien public",
|
||||
"publicLinkDescription": "Toute personne disposant du lien peut voir cette liste.",
|
||||
"publicLinkToggleFailed": "Impossible de mettre à jour le lien public",
|
||||
"copyLink": "Copier le lien",
|
||||
"linkCopied": "Lien copié",
|
||||
"copyLinkFailed": "Impossible de copier le lien"
|
||||
},
|
||||
"social": {
|
||||
"followed": "Abonné",
|
||||
@@ -1043,6 +1054,11 @@
|
||||
},
|
||||
"settingsForm": {
|
||||
"profile": "Profil",
|
||||
"changePhoto": "Changer la photo",
|
||||
"removePhoto": "Supprimer la photo",
|
||||
"avatarUploadSuccess": "Photo de profil mise à jour",
|
||||
"avatarUploadFailed": "Échec de la mise à jour de la photo de profil",
|
||||
"avatarRemoved": "Photo de profil supprimée",
|
||||
"displayName": "Nom d'affichage",
|
||||
"email": "E-mail",
|
||||
"emailReadOnly": "L'e-mail ne peut pas être modifié ici.",
|
||||
|
||||
@@ -35,7 +35,7 @@ const securityHeaders = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval'", // unsafe-eval needed by Next.js dev; tighten in prod
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
`img-src 'self' data: blob: ${storageOrigin}`,
|
||||
`img-src 'self' data: blob: ${storageOrigin} https://www.gravatar.com`,
|
||||
"font-src 'self'",
|
||||
`connect-src 'self' ${storageOrigin}`,
|
||||
"frame-ancestors 'none'",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getSessionCookie } from "better-auth/cookies";
|
||||
|
||||
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"];
|
||||
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/s/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"];
|
||||
const ADMIN_PATHS = ["/admin"];
|
||||
|
||||
export async function proxy(request: NextRequest) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN "has_custom_avatar" boolean DEFAULT false NOT NULL;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "shopping_lists" ADD COLUMN "is_public" boolean DEFAULT false NOT NULL;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -225,6 +225,20 @@
|
||||
"when": 1783841772890,
|
||||
"tag": "0031_brave_arclight",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 32,
|
||||
"version": "7",
|
||||
"when": 1783863921901,
|
||||
"tag": "0032_boring_layla_miller",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 33,
|
||||
"version": "7",
|
||||
"when": 1783864805460,
|
||||
"tag": "0033_graceful_jetstream",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -60,6 +60,7 @@ export const shoppingLists = pgTable("shopping_lists", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
isPublic: boolean("is_public").notNull().default(false),
|
||||
generatedAt: timestamp("generated_at"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ export const users = pgTable("users", {
|
||||
emailVerified: boolean("email_verified").notNull().default(false),
|
||||
name: text("name").notNull(),
|
||||
avatarUrl: text("avatar_url"),
|
||||
hasCustomAvatar: boolean("has_custom_avatar").notNull().default(false),
|
||||
bio: text("bio"),
|
||||
privateBio: text("private_bio"),
|
||||
isPrivate: boolean("is_private").notNull().default(false),
|
||||
|
||||
Reference in New Issue
Block a user