Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
password protect playlist route (#598)
Brendan Allan4961b3476d06
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.tsindex 9fb228912..5181e51dd 100644--- a/apps/web/app/api/playlist/route.ts+++ b/apps/web/app/api/playlist/route.ts@@ -15,6 +15,7 @@ import z from "zod";import { handle } from "hono/vercel";import { corsMiddleware, withOptionalAuth } from "../utils";+import { userHasAccessToVideo } from "@/utils/auth";export const revalidate = "force-dynamic";@@ -42,6 +43,7 @@ const app = new Hono()),async (c) => {const { videoId, videoType, thumbnail, fileType } = c.req.valid("query");+ const user = c.get("user");const query = await db().select({ video: videos, bucket: s3Buckets })@@ -49,25 +51,26 @@ const app = new Hono().leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id)).where(eq(videos.id, videoId));- if (!query[0]) {+ if (!query[0])return c.json(JSON.stringify({ error: true, message: "Video does not exist" }),404);- }const { video, bucket: customBucket } = query[0];- if (video.public === false) {- const user = await getCurrentUser();+ const hasAccess = await userHasAccessToVideo(user, video);- if (!user || user.id !== video.ownerId) {- return c.json(- JSON.stringify({ error: true, message: "Video is not public" }),- 401- );- }- }+ if (hasAccess === "private")+ return c.json(+ JSON.stringify({ error: true, message: "Video is not public" }),+ 401+ );+ else if (hasAccess === "needs-password")+ return c.json(+ JSON.stringify({ error: true, message: "Video requires password" }),+ 403+ );const bucket = await createBucketProvider(customBucket);diff --git a/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx b/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsxindex ae9e82897..55f7a3dfb 100644--- a/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx+++ b/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx@@ -1,14 +1,6 @@"use client";-import {- Button,- Dialog,- DialogContent,- DialogTitle,- Input,- Logo,-} from "@cap/ui";-import { motion } from "framer-motion";+import { Button, Dialog, DialogContent, Input, Logo } from "@cap/ui";import { useState } from "react";import { toast } from "sonner";import { verifyVideoPassword } from "@/actions/videos/password";@@ -20,8 +12,6 @@ interface PasswordOverlayProps {videoId: string;}-const MotionDialogContent = motion.create(DialogContent);-export const PasswordOverlay: React.FC<PasswordOverlayProps> = ({isOpen,videoId,@@ -46,13 +36,7 @@ export const PasswordOverlay: React.FC<PasswordOverlayProps> = ({return (<Dialog open={isOpen}>- <MotionDialogContent- // initial={{ opacity: 0, scale: 0.95 }}- // animate={{ opacity: 1, scale: 1 }}- // exit={{ opacity: 0, scale: 0.95 }}- // transition={{ duration: 0.2 }}- className="w-[90vw] sm:max-w-md p-8 rounded-xl border border-gray-200 bg-white shadow-xl"- >+ <DialogContent className="w-[90vw] sm:max-w-md p-8 rounded-xl border border-gray-200 bg-white shadow-xl"><div className="flex flex-col items-center space-y-6"><div className="flex flex-col items-center space-y-4"><Logo className="w-24 h-auto" />@@ -98,7 +82,7 @@ export const PasswordOverlay: React.FC<PasswordOverlayProps> = ({</Button></div></div>- </MotionDialogContent>+ </DialogContent></Dialog>);};diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsxindex 70f175288..7c32ba54d 100644--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx@@ -32,8 +32,8 @@ export const ShareHeader = ({}: {data: typeof videos.$inferSelect;user: typeof userSelectProps | null;- customDomain: string | null;- domainVerified: boolean;+ customDomain?: string | null;+ domainVerified?: boolean;sharedOrganizations?: { id: string; name: string }[];userOrganizations?: { id: string; name: string }[];}) => {@@ -46,7 +46,7 @@ export const ShareHeader = ({const [currentSharedOrganizations, setCurrentSharedOrganizations] =useState(sharedOrganizations);- const isOwner = user !== null && user.id.toString() === data.ownerId;+ const isOwner = user && user.id.toString() === data.ownerId;const { webUrl } = usePublicEnv();@@ -167,10 +167,7 @@ export const ShareHeader = ({<h1className="text-xl sm:text-2xl"onClick={() => {- if (- user !== null &&- user.id.toString() === data.ownerId- ) {+ if (user && user.id.toString() === data.ownerId) {setIsEditing(true);}}}diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex dcec983be..9758d9116 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -1,5 +1,5 @@import { db } from "@cap/database";-import { eq, desc, sql, count } from "drizzle-orm";+import { eq, desc, sql, count, InferSelectModel } from "drizzle-orm";import { Logo } from "@cap/ui";import {videos,@@ -24,8 +24,8 @@ import { isAiGenerationEnabled, isAiUiEnabled } from "@/utils/flags";import { Share } from "./Share";import { PasswordOverlay } from "./_components/PasswordOverlay";import { ImageViewer } from "./_components/ImageViewer";-import { decrypt } from "@cap/database/crypto";import { ShareHeader } from "./_components/ShareHeader";+import { userHasAccessToVideo } from "@/utils/auth";export const dynamic = "auto";export const dynamicParams = true;@@ -245,7 +245,7 @@ export default async function ShareVideoPage(props: Props) {const videoId = params.videoId as string;console.log("[ShareVideoPage] Starting page load for videoId:", videoId);- const user = (await getCurrentUser()) as typeof userSelectProps | null;+ const user = await getCurrentUser();const userId = user?.id as string | undefined;console.log("[ShareVideoPage] Current user:", userId);@@ -287,6 +287,35 @@ export default async function ShareVideoPage(props: Props) {return <p>No video found</p>;}+ const userAccess = await userHasAccessToVideo(user, video);++ if (userAccess === "private") return <p>This video is private</p>;++ return (+ <div className="min-h-screen flex flex-col bg-[#F7F8FA]">+ <PasswordOverlay+ isOpen={userAccess === "needs-password"}+ videoId={video.id}+ />+ {userAccess === "has-access" && (+ <AuthorizedContent video={video} user={user} />+ )}+ </div>+ );+}++async function AuthorizedContent({+ video,+ user,+}: {+ video: InferSelectModel<typeof videos> & {+ sharedOrganization: { organizationId: string } | null;+ };+ user: InferSelectModel<typeof users> | null;+}) {+ const videoId = video.id;+ const userId = user?.id;+let aiGenerationEnabled = false;const videoOwnerQuery = await db().select({@@ -423,10 +452,6 @@ export default async function ShareVideoPage(props: Props) {}}- if (video.public === false && userId !== video.ownerId) {- return <p>This video is private</p>;- }-const commentsQuery: CommentWithAuthor[] = await db().select({id: comments.id,@@ -593,69 +618,48 @@ export default async function ShareVideoPage(props: Props) {);}- const authorized =- !videoWithOrganizationInfo.hasPassword ||- user?.id === videoWithOrganizationInfo.ownerId ||- (await verifyPasswordCookie(video.password ?? ""));-return (- <div className="min-h-screen flex flex-col bg-[#F7F8FA]">- <PasswordOverlay- isOpen={!authorized}- videoId={videoWithOrganizationInfo.id}- />- {authorized && (- <>- <div className="container flex-1 px-4 py-4 mx-auto">- <ShareHeader- data={{- ...videoWithOrganizationInfo,- createdAt: video.metadata?.customCreatedAt- ? new Date(video.metadata.customCreatedAt)- : video.createdAt,- }}- user={user}- customDomain={customDomain}- domainVerified={domainVerified}- sharedOrganizations={- videoWithOrganizationInfo.sharedOrganizations || []- }- userOrganizations={userOrganizations}- />-- <Share- data={videoWithOrganizationInfo}- user={user}- comments={commentsQuery}- initialAnalytics={initialAnalytics}- customDomain={customDomain}- domainVerified={domainVerified}- userOrganizations={userOrganizations}- initialAiData={initialAiData}- aiGenerationEnabled={aiGenerationEnabled}- aiUiEnabled={aiUiEnabled}- />- </div>- <div className="py-4 mt-auto">- <a- target="_blank"- href={`/?ref=video_${video.id}`}- className="flex justify-center items-center px-4 py-2 mx-auto space-x-2 bg-gray-1 rounded-full new-card-style w-fit"- >- <span className="text-sm">Recorded with</span>- <Logo className="w-14 h-auto" />- </a>- </div>- </>- )}- </div>- );-}--async function verifyPasswordCookie(videoPassword: string) {- const password = cookies().get("x-cap-password")?.value;- if (!password) return false;+ <>+ <div className="container flex-1 px-4 py-4 mx-auto">+ <ShareHeader+ data={{+ ...videoWithOrganizationInfo,+ createdAt: video.metadata?.customCreatedAt+ ? new Date(video.metadata.customCreatedAt)+ : video.createdAt,+ }}+ user={user}+ customDomain={customDomain}+ domainVerified={domainVerified}+ sharedOrganizations={+ videoWithOrganizationInfo.sharedOrganizations || []+ }+ userOrganizations={userOrganizations}+ />- const decrypted = await decrypt(password).catch(() => "");- return decrypted === videoPassword;+ <Share+ data={videoWithOrganizationInfo}+ user={user}+ comments={commentsQuery}+ initialAnalytics={initialAnalytics}+ customDomain={customDomain}+ domainVerified={domainVerified}+ userOrganizations={userOrganizations}+ initialAiData={initialAiData}+ aiGenerationEnabled={aiGenerationEnabled}+ aiUiEnabled={aiUiEnabled}+ />+ </div>+ <div className="py-4 mt-auto">+ <a+ target="_blank"+ href={`/?ref=video_${video.id}`}+ className="flex justify-center items-center px-4 py-2 mx-auto space-x-2 bg-gray-1 rounded-full new-card-style w-fit"+ >+ <span className="text-sm">Recorded with</span>+ <Logo className="w-14 h-auto" />+ </a>+ </div>+ </>+ );}diff --git a/apps/web/lib/safe-action.ts b/apps/web/lib/safe-action.tsdeleted file mode 100644index 7f62198ae..000000000--- a/apps/web/lib/safe-action.ts+++ /dev/null@@ -1,3 +0,0 @@-import { createSafeActionClient } from "next-safe-action";--export const actionClient = createSafeActionClient();diff --git a/apps/web/utils/auth.ts b/apps/web/utils/auth.tsnew file mode 100644index 000000000..2b11f0045--- /dev/null+++ b/apps/web/utils/auth.ts@@ -0,0 +1,23 @@+import { decrypt } from "@cap/database/crypto";+import { videos } from "@cap/database/schema";+import { InferSelectModel } from "drizzle-orm";+import { cookies } from "next/headers";++async function verifyPasswordCookie(videoPassword: string) {+ const password = cookies().get("x-cap-password")?.value;+ if (!password) return false;++ const decrypted = await decrypt(password).catch(() => "");+ return decrypted === videoPassword;+}++export async function userHasAccessToVideo(+ user: { id: string } | undefined | null,+ video: InferSelectModel<typeof videos>+): Promise<"has-access" | "private" | "needs-password"> {+ if (video.public === false && (!user || user.id !== video.ownerId))+ return "private";+ if (video.password === null) return "has-access";+ if (!(await verifyPasswordCookie(video.password))) return "needs-password";+ return "has-access";+}diff --git a/packages/database/auth/session.ts b/packages/database/auth/session.tsindex 2684e8c84..b3ab672e1 100644--- a/packages/database/auth/session.ts+++ b/packages/database/auth/session.ts@@ -1,5 +1,5 @@import { getServerSession, Session } from "next-auth";-import { eq } from "drizzle-orm";+import { eq, InferSelectModel } from "drizzle-orm";import { authOptions } from "./auth-options";import { db } from "../";import { users } from "../schema";@@ -10,19 +10,19 @@ export const getSession = async () => {return session;};-export const getCurrentUser = async (session?: Session) => {+export const getCurrentUser = async (+ session?: Session+): Promise<InferSelectModel<typeof users> | null> => {const _session = session ?? (await getServerSession(authOptions()));- if (!_session) {- return null;- }+ if (!_session) return null;const [currentUser] = await db().select().from(users).where(eq(users.id, _session?.user.id));- return currentUser;+ return currentUser ?? null;};export const userSelectProps = users.$inferSelect;