client passwords
Deploy / deploy (push) Successful in 2m57s

This commit is contained in:
twotalesanimation
2026-06-12 12:37:57 +02:00
parent 5bfaf49fa1
commit 23f0ceca3f
13 changed files with 377 additions and 74 deletions
+7 -9
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { ApprovalStatus } from "@prisma/client"; import { ApprovalStatus } from "@prisma/client";
import { recalcShotStatus } from "@/lib/shot-status"; import { recalcShotStatus } from "@/lib/shot-status";
import { validateReviewToken } from "@/lib/review-auth";
async function getOrCreateClientUser(email: string, label?: string | null) { async function getOrCreateClientUser(email: string, label?: string | null) {
const existing = await db.user.findUnique({ where: { email } }); const existing = await db.user.findUnique({ where: { email } });
@@ -16,22 +17,19 @@ async function getOrCreateClientUser(email: string, label?: string | null) {
}); });
} }
async function validateToken(token: string) {
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) return null;
if (session.expiresAt && session.expiresAt < new Date()) return null;
return session;
}
export async function POST( export async function POST(
req: NextRequest, req: NextRequest,
{ params }: { params: Promise<{ token: string }> } { params }: { params: Promise<{ token: string }> }
) { ) {
const { token } = await params; const { token } = await params;
const session = await validateToken(token); const result = await validateReviewToken(token, req);
if (!session) { if (result.type === "requiresPassword") {
return NextResponse.json({ requiresPassword: true }, { status: 401 });
}
if (result.type === "invalid") {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }); return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
} }
const session = result.session;
const body = await req.json(); const body = await req.json();
const { versionId, shotId, action, status, notes } = body; const { versionId, shotId, action, status, notes } = body;
+48
View File
@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import bcrypt from "bcryptjs";
import { makeUnlockCookieValue } from "@/lib/review-auth";
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ token: string }> }
) {
const { token } = await params;
const body = await req.json().catch(() => ({}));
const { password } = body as { password?: string };
if (!password || typeof password !== "string") {
return NextResponse.json({ error: "Password required" }, { status: 400 });
}
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
}
if (session.expiresAt && session.expiresAt < new Date()) {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
}
if (!session.passwordHash) {
return NextResponse.json({ success: true });
}
const valid = await bcrypt.compare(password, session.passwordHash);
if (!valid) {
return NextResponse.json({ error: "Incorrect password" }, { status: 401 });
}
const cookieName = `rsauth_${token}`;
const cookieValue = makeUnlockCookieValue(token);
const res = NextResponse.json({ success: true });
res.cookies.set(cookieName, cookieValue, {
httpOnly: true,
sameSite: "lax",
path: "/",
expires: session.expiresAt,
secure: process.env.NODE_ENV === "production",
});
return res;
}
+7 -9
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { slackNotifyNewFeedback } from "@/lib/slack"; import { slackNotifyNewFeedback } from "@/lib/slack";
import { validateReviewToken } from "@/lib/review-auth";
/** Find or create a guest user for the client reviewer based on the session email */ /** Find or create a guest user for the client reviewer based on the session email */
async function getOrCreateClientUser(email: string, label?: string | null) { async function getOrCreateClientUser(email: string, label?: string | null) {
@@ -16,22 +17,19 @@ async function getOrCreateClientUser(email: string, label?: string | null) {
}); });
} }
async function validateToken(token: string) {
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) return null;
if (session.expiresAt && session.expiresAt < new Date()) return null;
return session;
}
export async function POST( export async function POST(
req: NextRequest, req: NextRequest,
{ params }: { params: Promise<{ token: string }> } { params }: { params: Promise<{ token: string }> }
) { ) {
const { token } = await params; const { token } = await params;
const session = await validateToken(token); const result = await validateReviewToken(token, req);
if (!session) { if (result.type === "requiresPassword") {
return NextResponse.json({ requiresPassword: true }, { status: 401 });
}
if (result.type === "invalid") {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }); return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
} }
const session = result.session;
const body = await req.json(); const body = await req.json();
const { versionId, frameNumber, timestamp, text } = body; const { versionId, frameNumber, timestamp, text } = body;
+7 -9
View File
@@ -1,12 +1,6 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { validateReviewToken } from "@/lib/review-auth";
async function validateToken(token: string) {
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) return null;
if (session.expiresAt && session.expiresAt < new Date()) return null;
return session;
}
/** GET /api/client/[token]/project — returns project + shots with tasks that have client-visible versions */ /** GET /api/client/[token]/project — returns project + shots with tasks that have client-visible versions */
export async function GET( export async function GET(
@@ -14,10 +8,14 @@ export async function GET(
{ params }: { params: Promise<{ token: string }> } { params }: { params: Promise<{ token: string }> }
) { ) {
const { token } = await params; const { token } = await params;
const session = await validateToken(token); const result = await validateReviewToken(token, req);
if (!session) { if (result.type === "requiresPassword") {
return NextResponse.json({ requiresPassword: true }, { status: 401 });
}
if (result.type === "invalid") {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }); return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
} }
const session = result.session;
const project = await db.project.findUnique({ const project = await db.project.findUnique({
where: { id: session.projectId }, where: { id: session.projectId },
@@ -1,12 +1,6 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { validateReviewToken } from "@/lib/review-auth";
async function validateToken(token: string) {
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) return null;
if (session.expiresAt && session.expiresAt < new Date()) return null;
return session;
}
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */ /** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
export async function GET( export async function GET(
@@ -14,10 +8,14 @@ export async function GET(
{ params }: { params: Promise<{ token: string; versionId: string }> } { params }: { params: Promise<{ token: string; versionId: string }> }
) { ) {
const { token, versionId } = await params; const { token, versionId } = await params;
const session = await validateToken(token); const result = await validateReviewToken(token, req);
if (!session) { if (result.type === "requiresPassword") {
return NextResponse.json({ requiresPassword: true }, { status: 401 });
}
if (result.type === "invalid") {
return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }); return NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 });
} }
const session = result.session;
const version = await db.version.findUnique({ const version = await db.version.findUnique({
where: { id: versionId }, where: { id: versionId },
+8 -1
View File
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { addDays } from "date-fns"; import { addDays } from "date-fns";
import bcrypt from "bcryptjs";
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const session = await auth(); const session = await auth();
@@ -32,7 +33,7 @@ export async function POST(req: NextRequest) {
} }
const body = await req.json(); const body = await req.json();
const { projectId, label, email, expiresInDays = 30 } = body; const { projectId, label, email, expiresInDays = 30, password } = body;
if (!projectId) { if (!projectId) {
return NextResponse.json({ error: "projectId is required" }, { status: 400 }); return NextResponse.json({ error: "projectId is required" }, { status: 400 });
@@ -43,11 +44,17 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Project not found" }, { status: 404 }); return NextResponse.json({ error: "Project not found" }, { status: 404 });
} }
const passwordHash =
password && typeof password === "string" && password.length > 0
? await bcrypt.hash(password, 12)
: null;
const reviewSession = await db.reviewSession.create({ const reviewSession = await db.reviewSession.create({
data: { data: {
projectId, projectId,
label: label || `Review — ${project.name}`, label: label || `Review — ${project.name}`,
email: email || null, email: email || null,
passwordHash,
expiresAt: addDays(new Date(), expiresInDays), expiresAt: addDays(new Date(), expiresInDays),
}, },
}); });
+29 -3
View File
@@ -15,6 +15,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Montserrat } from 'next/font/google'; import { Montserrat } from 'next/font/google';
import { ReviewPasswordGate } from '@/components/clients/ReviewPasswordGate';
const montserrat = Montserrat({ const montserrat = Montserrat({
subsets: ['latin'], subsets: ['latin'],
@@ -121,6 +122,7 @@ export default function ClientPortalPage({
const [sessionLabel, setSessionLabel] = useState<string>(''); const [sessionLabel, setSessionLabel] = useState<string>('');
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [requiresPassword, setRequiresPassword] = useState(false);
const [collapsedEpisodes, setCollapsedEpisodes] = useState<Set<string>>(new Set()); const [collapsedEpisodes, setCollapsedEpisodes] = useState<Set<string>>(new Set());
const toggleEpisode = (ep: string) => { const toggleEpisode = (ep: string) => {
@@ -134,21 +136,36 @@ export default function ClientPortalPage({
useEffect(() => { useEffect(() => {
params.then(({ token: t }) => { params.then(({ token: t }) => {
setToken(t); setToken(t);
loadProject(t);
});
}, [params]);
const loadProject = (t: string) => {
setLoading(true);
setError(null);
fetch(`/api/client/${t}/project`) fetch(`/api/client/${t}/project`)
.then((r) => { .then(async (r) => {
if (r.status === 401) {
const data = await r.json().catch(() => ({}));
if (data.requiresPassword) {
setRequiresPassword(true);
return null;
}
}
if (!r.ok) throw new Error('Invalid or expired review link'); if (!r.ok) throw new Error('Invalid or expired review link');
return r.json(); return r.json();
}) })
.then((data) => { .then((data) => {
if (!data) return;
setProject(data.project); setProject(data.project);
setShots(data.shots ?? []); setShots(data.shots ?? []);
setAssetTasks(data.assetTasks ?? []); setAssetTasks(data.assetTasks ?? []);
setSessionLabel(data.sessionLabel ?? ''); setSessionLabel(data.sessionLabel ?? '');
setRequiresPassword(false);
}) })
.catch((e) => setError(e.message)) .catch((e) => setError(e.message))
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}); };
}, [params]);
if (loading) { if (loading) {
return ( return (
@@ -158,6 +175,15 @@ export default function ClientPortalPage({
); );
} }
if (requiresPassword) {
return (
<ReviewPasswordGate
token={token}
onUnlocked={() => loadProject(token)}
/>
);
}
if (error || !project) { if (error || !project) {
return ( return (
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center gap-4 text-center px-4"> <div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center gap-4 text-center px-4">
+33 -5
View File
@@ -28,6 +28,7 @@ import {
Clock, Clock,
} from "lucide-react"; } from "lucide-react";
import { useReviewStore } from "@/hooks/use-review-player"; import { useReviewStore } from "@/hooks/use-review-player";
import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate";
interface Comment { interface Comment {
id: string; id: string;
@@ -80,6 +81,8 @@ export default function ClientReviewPage({
const [comments, setComments] = useState<Comment[]>([]); const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [requiresPassword, setRequiresPassword] = useState(false);
const [versionId, setVersionId] = useState("");
const currentFrame = useReviewStore((s) => s.currentFrame); const currentFrame = useReviewStore((s) => s.currentFrame);
@@ -101,22 +104,38 @@ export default function ClientReviewPage({
const { toast } = useToast(); const { toast } = useToast();
useEffect(() => { useEffect(() => {
params.then(({ token: t, versionId }) => { params.then(({ token: t, versionId: vId }) => {
setToken(t); setToken(t);
fetch(`/api/client/${t}/versions/${versionId}`) setVersionId(vId);
.then((r) => { loadVersion(t, vId);
});
}, [params]);
const loadVersion = (t: string, vId: string) => {
setLoading(true);
setError(null);
fetch(`/api/client/${t}/versions/${vId}`)
.then(async (r) => {
if (r.status === 401) {
const data = await r.json().catch(() => ({}));
if (data.requiresPassword) {
setRequiresPassword(true);
return null;
}
}
if (!r.ok) throw new Error("Invalid or expired review link"); if (!r.ok) throw new Error("Invalid or expired review link");
return r.json(); return r.json();
}) })
.then((data) => { .then((data) => {
if (!data) return;
setVersion(data.version); setVersion(data.version);
setComments(data.comments); setComments(data.comments);
setCurrentApprovalStatus(data.version.approvalStatus); setCurrentApprovalStatus(data.version.approvalStatus);
setRequiresPassword(false);
}) })
.catch((e) => setError(e.message)) .catch((e) => setError(e.message))
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}); };
}, [params]);
const refreshComments = useCallback(async (t: string, vId: string) => { const refreshComments = useCallback(async (t: string, vId: string) => {
const res = await fetch(`/api/client/${t}/versions/${vId}`); const res = await fetch(`/api/client/${t}/versions/${vId}`);
@@ -201,6 +220,15 @@ export default function ClientReviewPage({
); );
} }
if (requiresPassword) {
return (
<ReviewPasswordGate
token={token}
onUnlocked={() => loadVersion(token, versionId)}
/>
);
}
if (error || !version) { if (error || !version) {
return ( return (
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center gap-4 text-center px-4"> <div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center gap-4 text-center px-4">
+122
View File
@@ -0,0 +1,122 @@
"use client";
import { useState } from "react";
import Image from "next/image";
import { Film, Lock, Eye, EyeOff } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Montserrat } from "next/font/google";
const montserrat = Montserrat({
subsets: ["latin"],
weight: ["200", "500", "600"],
});
interface ReviewPasswordGateProps {
token: string;
onUnlocked: () => void;
}
export function ReviewPasswordGate({ token, onUnlocked }: ReviewPasswordGateProps) {
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!password.trim()) return;
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/client/${token}/auth`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
if (res.ok) {
onUnlocked();
} else {
const data = await res.json().catch(() => ({}));
setError(data.error ?? "Incorrect password. Please try again.");
}
} catch {
setError("Something went wrong. Please try again.");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center px-4">
<div className="w-full max-w-sm space-y-6">
{/* Logo */}
<div className={`flex items-center gap-3 justify-center ${montserrat.className}`}>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-black border border-zinc-800">
<Image src="/logo.svg" alt="Logo" width={28} height={28} />
</div>
<div>
<span className="block text-xl font-light text-white leading-none">TWO TALES</span>
<span className="block text-[10px] tracking-[0.18em] italic text-zinc-400 leading-none mt-0.5">
vfx review
</span>
</div>
</div>
{/* Card */}
<div className="rounded-2xl border border-zinc-800 bg-zinc-900 p-8 space-y-5">
<div className="flex flex-col items-center gap-2 text-center">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-amber-500/10 border border-amber-500/20">
<Lock className="h-6 w-6 text-amber-400" />
</div>
<h1 className="text-lg font-semibold text-white">Password Required</h1>
<p className="text-sm text-zinc-400">
This review link is password protected. Enter the password to access the content.
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-3">
<div className="relative">
<Input
type={showPassword ? "text" : "password"}
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="pr-10 bg-zinc-950 border-zinc-700 focus:border-amber-500/50"
autoFocus
disabled={loading}
/>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-200 transition-colors"
onClick={() => setShowPassword((v) => !v)}
tabIndex={-1}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
{error && (
<p className="text-xs text-red-400 flex items-center gap-1.5">
<span className="inline-block h-1 w-1 rounded-full bg-red-400 shrink-0" />
{error}
</p>
)}
<Button
type="submit"
className="w-full bg-amber-500 hover:bg-amber-400 text-black font-medium"
disabled={loading || !password.trim()}
>
{loading ? "Verifying..." : "Access Review"}
</Button>
</form>
</div>
<p className="text-center text-xs text-zinc-600">
Contact your studio if you don&apos;t have the password.
</p>
</div>
</div>
);
}
+45 -2
View File
@@ -17,7 +17,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast"; import { useToast } from "@/components/ui/use-toast";
import { Copy, Check, ExternalLink } from "lucide-react"; import { Copy, Check, ExternalLink, Eye, EyeOff, Lock } from "lucide-react";
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -31,6 +31,7 @@ const schema = z.object({
label: z.string().min(1, "Label is required"), label: z.string().min(1, "Label is required"),
email: z.string().email("Invalid email"), email: z.string().email("Invalid email"),
expiresInDays: z.number().int().positive().default(30), expiresInDays: z.number().int().positive().default(30),
password: z.string().optional(),
}); });
type FormValues = z.infer<typeof schema>; type FormValues = z.infer<typeof schema>;
@@ -56,7 +57,9 @@ export function ShareReviewDialog({
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [portalUrl, setPortalUrl] = useState<string | null>(null); const [portalUrl, setPortalUrl] = useState<string | null>(null);
const [isPasswordProtected, setIsPasswordProtected] = useState(false);
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const { toast } = useToast(); const { toast } = useToast();
const router = useRouter(); const router = useRouter();
@@ -74,6 +77,7 @@ export function ShareReviewDialog({
label: "Review Round 1", label: "Review Round 1",
email: clientEmail, email: clientEmail,
expiresInDays: 30, expiresInDays: 30,
password: "",
}, },
}); });
@@ -86,11 +90,13 @@ export function ShareReviewDialog({
const handleReset = () => { const handleReset = () => {
setPortalUrl(null); setPortalUrl(null);
setIsPasswordProtected(false);
reset({ reset({
projectId: projects[0]?.id ?? "", projectId: projects[0]?.id ?? "",
label: "Review Round 1", label: "Review Round 1",
email: clientEmail, email: clientEmail,
expiresInDays: 30, expiresInDays: 30,
password: "",
}); });
}; };
@@ -100,7 +106,10 @@ export function ShareReviewDialog({
const res = await fetch("/api/review-sessions", { const res = await fetch("/api/review-sessions", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(values), body: JSON.stringify({
...values,
password: values.password?.trim() || undefined,
}),
}); });
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({})); const err = await res.json().catch(() => ({}));
@@ -108,6 +117,7 @@ export function ShareReviewDialog({
} }
const data = await res.json(); const data = await res.json();
setPortalUrl(data.portalUrl); setPortalUrl(data.portalUrl);
setIsPasswordProtected(!!(values.password?.trim()));
router.refresh(); router.refresh();
} catch (e) { } catch (e) {
toast({ toast({
@@ -139,6 +149,12 @@ export function ShareReviewDialog({
<p className="text-sm text-zinc-400"> <p className="text-sm text-zinc-400">
Your review link is ready. Copy it and share it with your client. Your review link is ready. Copy it and share it with your client.
</p> </p>
{isPasswordProtected && (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs">
<Lock className="h-3.5 w-3.5 shrink-0" />
This link is password protected. Share the password separately.
</div>
)}
<div className="flex items-center gap-2 p-3 rounded-lg bg-zinc-800 border border-zinc-700"> <div className="flex items-center gap-2 p-3 rounded-lg bg-zinc-800 border border-zinc-700">
<ExternalLink className="h-4 w-4 text-zinc-500 shrink-0" /> <ExternalLink className="h-4 w-4 text-zinc-500 shrink-0" />
<span className="flex-1 text-sm font-mono text-zinc-300 truncate">{portalUrl}</span> <span className="flex-1 text-sm font-mono text-zinc-300 truncate">{portalUrl}</span>
@@ -212,6 +228,33 @@ export function ShareReviewDialog({
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="space-y-1.5">
<Label htmlFor="password" className="flex items-center gap-1.5">
<Lock className="h-3.5 w-3.5 text-zinc-400" />
Password <span className="text-zinc-500 font-normal">(optional)</span>
</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="Leave blank for no password"
className="pr-9"
{...register("password")}
/>
<button
type="button"
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-200 transition-colors"
onClick={() => setShowPassword((v) => !v)}
tabIndex={-1}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
</div>
<DialogFooter> <DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)}> <Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancel Cancel
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import crypto from "crypto";
import type { ReviewSession } from "@prisma/client";
export type TokenValidation =
| { type: "ok"; session: ReviewSession }
| { type: "invalid" }
| { type: "requiresPassword" };
export function makeUnlockCookieValue(token: string): string {
const secret = process.env.AUTH_SECRET ?? "fallback-secret";
return crypto.createHmac("sha256", secret).update(token).digest("hex");
}
export async function validateReviewToken(
token: string,
req: NextRequest
): Promise<TokenValidation> {
const session = await db.reviewSession.findUnique({ where: { token } });
if (!session || !session.isActive) return { type: "invalid" };
if (session.expiresAt && session.expiresAt < new Date()) return { type: "invalid" };
if (session.passwordHash) {
const cookieName = `rsauth_${token}`;
const cookieValue = req.cookies.get(cookieName)?.value;
const expected = makeUnlockCookieValue(token);
if (!cookieValue || cookieValue !== expected) {
return { type: "requiresPassword" };
}
}
return { type: "ok", session };
}
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "review_sessions" ADD COLUMN "passwordHash" TEXT;
+1
View File
@@ -523,6 +523,7 @@ model ReviewSession {
token String @unique @default(cuid()) token String @unique @default(cuid())
label String? label String?
email String? email String?
passwordHash String?
expiresAt DateTime expiresAt DateTime
isActive Boolean @default(true) isActive Boolean @default(true)
accessCount Int @default(0) accessCount Int @default(0)