Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
wip: Remove Supabase from codebase
Richie McIlroy1a763dcaa099
diff --git a/.env.example b/.env.exampleindex 6cce076d6..2e0ff9758 100644--- a/.env.example+++ b/.env.example@@ -7,19 +7,10 @@# - REQUIRED ****************-# Update these with your Supabase details from your project settings > API-# https://app.supabase.com/project/_/settings/api-###### TODO: Consolidate next and vite env variables into one set of variables.###-NEXT_PUBLIC_SUPABASE_URL=-NEXT_PUBLIC_SUPABASE_ANON_KEY=--VITE_SUPABASE_URL=-VITE_SUPABASE_ANON_KEY=-NEXT_PUBLIC_ENVIRONMENT=developmentNEXT_PUBLIC_URL=http://localhost:3000@@ -36,5 +27,4 @@ VITE_AWS_REGION=# - MISC, NOT REQUIRED FOR DEV ****************-SUPABASE_SERVICE_ROLE_KEY=NEXT_LOOPS_KEY=\ No newline at end of filediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 583d618bc..81185e160 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -20,14 +20,6 @@ There are many ways to contribute to Cap. You can:- [Suggest a feature (via Discord)](https://discord.com/invite/y8gdQ3WRN3)- Submit a PR-### How do I set up a local Supabase database?--1. Follow the instructions here to install the Supabase CLI: https://supabase.com/docs/guides/cli/getting-started-2. Run `cd supabase && supabase start` from the route of the project. This will take you to the supabase folder, and start the local Supabase server.-3. On first run, it'll take a few mins to set up the local Supabase server.-4. Once running, your local Supabase server env vars will be printed to the console. Copy these into your .env file.-5. To stop the local Supabase server, run `supabase stop` from the supabase folder, and `supabase start` to start it again.-### How do I get started with development on my local machine?This is a very top level guide right now, but the basics are:@@ -39,9 +31,3 @@ This is a very top level guide right now, but the basics are:5. Run the app with `pnpm dev`6. Make sure the app can be built without any errors with `pnpm build`7. Submit a PR with your changes--### How do I generate types?--At the root of the folder, run `npx supabase gen types typescript --project-id 'your_id_here' --schema public > packages/utils/src/types/database.ts` with your own Supabase project ID.--This will generate the latest types for the database, and save them to the utils package.diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 7fe5e6234..301be4997 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -26,7 +26,6 @@"vite-tsconfig-paths": "^4.2.1"},"devDependencies": {- "@supabase/supabase-js": "^2.39.0","@tauri-apps/cli": "^1.5.0","@types/react": "^18.2.15","@types/react-dom": "latest",diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex afb22011a..97eb89aca 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -11,9 +11,12 @@ import { emit } from "@tauri-apps/api/event";import { showMenu } from "tauri-plugin-context-menu";import { invoke } from "@tauri-apps/api/tauri";import { Countdown } from "./Countdown";-import { AuthSession } from "@supabase/supabase-js";-import { supabase } from "@/utils/database/client";-import type { Database } from "@cap/utils";+// import { AuthSession } from "@supabase/supabase-js";+// import { supabase } from "@/utils/database/client";+// import type { Database } from "@cap/utils";++//TODO: Auth+import { useMediaRecorder } from "@/utils/recording/useMediaRecorder";import { getSelectedVideoProperties } from "@/utils/recording/utils";import { getLatestVideoId, saveLatestVideoId } from "@/utils/database/utils";@@ -22,7 +25,7 @@ import { uuidParse } from "@cap/utils";import toast, { Toaster } from "react-hot-toast";import { LogicalSize, WebviewWindow, appWindow } from "@tauri-apps/api/window";-export const Recorder = ({ session }: { session: AuthSession | null }) => {+export const Recorder = ({ session }: { session: null }) => {const {devices,selectedVideoDevice,@@ -78,37 +81,37 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {setCountdownActive(false);};- const prepareVideoData = async () => {- return await supabase- .from("videos")- .insert({- owner_id: session?.user?.id,- aws_region: import.meta.env.VITE_AWS_REGION,- aws_bucket: import.meta.env.VITE_AWS_BUCKET,- })- .select()- .single()- .then(- ({- data,- error,- }: {- data: Database["public"]["Tables"]["videos"]["Row"] | null;- error: any;- }) => {- if (error) {- console.error("Error fetching video data:", error);- return null;- }- if (!data) {- console.error("No video data received");- return null;- }- saveLatestVideoId(data.id);- return data;- }- );- };+ // const prepareVideoData = async () => {+ // return await supabase+ // .from("videos")+ // .insert({+ // owner_id: session?.user?.id,+ // aws_region: import.meta.env.VITE_AWS_REGION,+ // aws_bucket: import.meta.env.VITE_AWS_BUCKET,+ // })+ // .select()+ // .single()+ // .then(+ // ({+ // data,+ // error,+ // }: {+ // data: Database["public"]["Tables"]["videos"]["Row"] | null;+ // error: any;+ // }) => {+ // if (error) {+ // console.error("Error fetching video data:", error);+ // return null;+ // }+ // if (!data) {+ // console.error("No video data received");+ // return null;+ // }+ // saveLatestVideoId(data.id);+ // return data;+ // }+ // );+ // };const startDualRecording = async (videoData: {id: any;@@ -120,7 +123,7 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {if (mediaSettings?.resolution && mediaSettings?.framerate) {await invoke("start_dual_recording", {options: {- user_id: session?.user?.id,+ // user_id: session?.user?.id,video_id: videoData.id,aws_region: videoData.aws_region,aws_bucket: videoData.aws_bucket,@@ -139,22 +142,22 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {const handleStartAllRecordings = async () => {setCountdownActive(true);- try {- const videoData = await prepareVideoData();- if (videoData) {- const stream = await navigator.mediaDevices.getUserMedia({- audio: { deviceId: selectedAudioDevice?.deviceId },- video: { deviceId: selectedVideoDevice?.deviceId },- });- await startMediaRecording(stream);- await startDualRecording(videoData);- } else {- throw new Error("Failed to prepare video data.");- }- } catch (error) {- console.error("Error starting recordings:", error);- setCountdownActive(false);- }+ // try {+ // const videoData = await prepareVideoData();+ // if (videoData) {+ // const stream = await navigator.mediaDevices.getUserMedia({+ // audio: { deviceId: selectedAudioDevice?.deviceId },+ // video: { deviceId: selectedVideoDevice?.deviceId },+ // });+ // await startMediaRecording(stream);+ // await startDualRecording(videoData);+ // } else {+ // throw new Error("Failed to prepare video data.");+ // }+ // } catch (error) {+ // console.error("Error starting recordings:", error);+ // setCountdownActive(false);+ // }};const handleStopAllRecordings = async () => {diff --git a/apps/desktop/src/components/windows/inner/SignIn.tsx b/apps/desktop/src/components/windows/inner/SignIn.tsxindex 1f7ab8b9a..dbf15589d 100644--- a/apps/desktop/src/components/windows/inner/SignIn.tsx+++ b/apps/desktop/src/components/windows/inner/SignIn.tsx@@ -1,48 +1,50 @@import { useState } from "react";-import { supabase } from "@/utils/database/client";+// import { supabase } from "@/utils/database/client";import { Button } from "@/components/Button";import { Logo } from "@/components/icons/Logo";-import toast from "react-hot-toast";+// import toast from "react-hot-toast";++//TODO: Authexport const SignIn = () => {const [email, setEmail] = useState<string>("");const [OTPcode, setOTPcode] = useState<string>("");const [enterCode, setEnterCode] = useState(false);- const handleLogin = async () => {- const { error } = await supabase.auth.signInWithOtp({- email: email,- });+ // const handleLogin = async () => {+ // const { error } = await supabase.auth.signInWithOtp({+ // email: email,+ // });- if (error) {- toast.error(`Error: ${error.message}`);- console.log({ error });- return;- }+ // if (error) {+ // toast.error(`Error: ${error.message}`);+ // console.log({ error });+ // return;+ // }- setEnterCode(true);- };+ // setEnterCode(true);+ // };- const verifyOTPCode = async () => {- if (!email || !OTPcode) {- toast.error(`Error: Email or OTP code is missing`);- return;- }+ // const verifyOTPCode = async () => {+ // if (!email || !OTPcode) {+ // toast.error(`Error: Email or OTP code is missing`);+ // return;+ // }- console.log({ email, OTPcode });+ // console.log({ email, OTPcode });- const { error } = await supabase.auth.verifyOtp({- email: email,- token: OTPcode,- type: "magiclink",- });+ // const { error } = await supabase.auth.verifyOtp({+ // email: email,+ // token: OTPcode,+ // type: "magiclink",+ // });- if (error) {- toast.error(`Error: ${error.message}`);- console.log({ error });- return;- }- };+ // if (error) {+ // toast.error(`Error: ${error.message}`);+ // console.log({ error });+ // return;+ // }+ // };return (<div className="w-[85%] h-[85%] flex items-center justify-center overflow-hidden px-2 py-4 rounded-[25px] border-2 border-gray-100 bg-gradient-to-b from-gray-200 to-white flex flex-col items-center justify-center">@@ -64,7 +66,7 @@ export const SignIn = () => {{enterCode === false ? (<div className="mt-3 text-center absolute right-0 h-full"><Button- handler={handleLogin}+ handler={() => {}}variant="primary"label="Continue"className="h-full rounded-tr-full rounded-br-full min-w-[100px] border-none"@@ -73,7 +75,7 @@ export const SignIn = () => {) : (<div className="mt-3 text-center absolute right-0 h-full"><Button- handler={verifyOTPCode}+ handler={() => {}}variant="primary"label="Confirm"className="h-full rounded-tr-full rounded-br-full min-w-[100px] border-none"diff --git a/apps/desktop/src/utils/database/AuthContext.tsx b/apps/desktop/src/utils/database/AuthContext.tsxdeleted file mode 100644index e0854e076..000000000--- a/apps/desktop/src/utils/database/AuthContext.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { createContext, useState, useEffect, useContext, useRef } from "react";-import { Session, User } from "@supabase/supabase-js";-import { supabase } from "@/utils/database/client";-import { saveUserId } from "@/utils/database/utils";--interface AuthContextProps {- session: Session | null;- user: User | null;- userRef: React.MutableRefObject<User | null>;-}--const AuthContext = createContext<AuthContextProps>({- session: null,- user: null,- userRef: { current: null },-});--export const useAuth = () => useContext(AuthContext);--export const AuthProvider: React.FC<React.PropsWithChildren<{}>> = ({- children,-}) => {- const [session, setSession] = useState<Session | null>(null);- const [user, setUser] = useState<User | null>(null);- const userRef = useRef<User | null>(null);-- useEffect(() => {- const updateAuthState = (session: Session | null) => {- setSession(session);- setUser(session?.user || null);- userRef.current = session?.user || null;- if (session?.user) {- saveUserId(session.user.id);- }- };-- supabase.auth.getSession().then(({ data: { session }, error }) => {- if (error) {- console.error("Error retrieving session:", error);- return;- }- updateAuthState(session);- });-- const { data: authListener } = supabase.auth.onAuthStateChange(- (_event, session) => {- updateAuthState(session);- }- );-- return () => {- authListener.subscription.unsubscribe();- };- }, []);-- return (- <AuthContext.Provider value={{ session, user, userRef }}>- {children}- </AuthContext.Provider>- );-};diff --git a/apps/desktop/src/utils/database/client.tsx b/apps/desktop/src/utils/database/client.tsxdeleted file mode 100644index 708a96509..000000000--- a/apps/desktop/src/utils/database/client.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { createClient } from "@supabase/supabase-js";--const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;-const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;--export const supabase = createClient(supabaseUrl, supabaseAnonKey, {- auth: {- persistSession: true,- storageKey: "CapSupabase",- storage: window.localStorage,- flowType: "pkce",- },-});diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.tsindex c34eca456..b1fd795e4 100644--- a/apps/desktop/vite.config.ts+++ b/apps/desktop/vite.config.ts@@ -7,14 +7,6 @@ import dotenv from "dotenv";// Load the environment variablesdotenv.config({ path: "../../.env" });-const requiredEnvVariables = ["VITE_SUPABASE_URL", "VITE_SUPABASE_ANON_KEY"];--requiredEnvVariables.forEach((envVar) => {- if (!process.env[envVar]) {- throw new Error(`Please set ${envVar} in .env file`);- }-});-// https://vitejs.dev/config/export default defineConfig(async () => ({plugins: [million.vite({ optimize: true }), react(), tsconfigPaths()],diff --git a/apps/web/app/auth/callback/route.ts b/apps/web/app/auth/callback/route.tsdeleted file mode 100644index 8b1cf7897..000000000--- a/apps/web/app/auth/callback/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { cookies } from "next/headers";-import { NextResponse } from "next/server";-import { type CookieOptions, createServerClient } from "@supabase/ssr";--export async function GET(request: Request) {- const { searchParams, origin } = new URL(request.url);- const code = searchParams.get("code");- const next = searchParams.get("next") ?? "/";-- if (code) {- const cookieStore = cookies();- const supabase = createServerClient(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,- {- cookies: {- get(name: string) {- return cookieStore.get(name)?.value;- },- set(name: string, value: string, options: CookieOptions) {- cookieStore.set({ name, value, ...options });- },- remove(name: string, options: CookieOptions) {- cookieStore.delete({ name, ...options });- },- },- }- );- const { error } = await supabase.auth.exchangeCodeForSession(code);- if (!error) {- return NextResponse.redirect(`${origin}${next}`);- }- }-- // return the user to an error page with instructions- return NextResponse.redirect(`${origin}/auth/auth-code-error`);-}diff --git a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsxindex 9107f1a59..4ce99b936 100644--- a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx+++ b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx@@ -30,8 +30,10 @@ import {} from "@cap/ui";import { NewSpace } from "@/components/forms/NewSpace";import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";-import { handleActiveSpace } from "@/utils/database/supabase/helpers";-import { supabase } from "@/utils/database/supabase/client";+// import { handleActiveSpace } from "@/utils/database/supabase/helpers";+// import { supabase } from "@/utils/database/supabase/client";++//TODO: Authexport const AdminNavItems = () => {const pathname = usePathname();@@ -50,13 +52,13 @@ export const AdminNavItems = () => {"flex items-center justify-start p-2 rounded-lg border border-transparent outline-none w-full";const handleLogout = async () => {- const { error } = await supabase.auth.signOut();+ // const { error } = await supabase.auth.signOut();router.refresh();- if (error) {- console.log({ error });- }+ // if (error) {+ // console.log({ error });+ // }};return (@@ -88,7 +90,7 @@ export const AdminNavItems = () => {<CommandInput placeholder="Search spaces..." /><CommandEmpty>No spaces found.</CommandEmpty><CommandGroup>- {spaceData?.map((space) => (+ {/* {spaceData?.map((space) => (<CommandItemkey={space.name}onSelect={async () => {@@ -99,7 +101,7 @@ export const AdminNavItems = () => {>{space.name}</CommandItem>- ))}+ ))} */}<DialogTrigger className="w-full"><CommandItem className="bg-filler aria-selected:bg-filler-2 rounded-lg"><Plus className="w-4 h-auto mr-1" />diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsxindex 018a7e6be..0a1c356d5 100644--- a/apps/web/app/dashboard/caps/page.tsx+++ b/apps/web/app/dashboard/caps/page.tsx@@ -1,22 +1,24 @@"use server";import { Caps } from "./Caps";import { DashboardTemplate } from "@/components/templates/DashboardTemplate";-import { createSupabaseServerClient } from "@/utils/database/supabase/server";+// import { createSupabaseServerClient } from "@/utils/database/supabase/server";type Props = {params: { [key: string]: string | string[] | undefined };};+//TODO: Auth+export default async function DocumentsPage(props: Props) {- const supabase = await createSupabaseServerClient();- const caps = await supabase- .from("videos")- .select("*")- .order("created_at", { ascending: true });+ // const supabase = await createSupabaseServerClient();+ // const caps = await supabase+ // .from("videos")+ // .select("*")+ // .order("created_at", { ascending: true });return (<DashboardTemplate>- <Caps data={caps?.data} />+ <Caps data={null} /></DashboardTemplate>);}diff --git a/apps/web/app/dashboard/layout.tsx b/apps/web/app/dashboard/layout.tsxindex 55d2e9659..e2d116432 100644--- a/apps/web/app/dashboard/layout.tsx+++ b/apps/web/app/dashboard/layout.tsx@@ -1,37 +1,40 @@"use server";-import DynamicSharedLayout from "@/app/dashboard/_components/DynamicSharedLayout";-import {- createSupabaseServerClient,- getSession,- getActiveSpace,-} from "@/utils/database/supabase/server";-import SupabaseProvider from "@/utils/database/supabase/provider";-import SupabaseListener from "@/utils/database/supabase/listener";+// import DynamicSharedLayout from "@/app/dashboard/_components/DynamicSharedLayout";+// import {+// createSupabaseServerClient,+// getSession,+// getActiveSpace,+// } from "@/utils/database/supabase/server";+// import SupabaseProvider from "@/utils/database/supabase/provider";+// import SupabaseListener from "@/utils/database/supabase/listener";++//TODO: Authexport default async function DashboardLayout({children,}: {children: React.ReactNode;}) {- const supabase = await createSupabaseServerClient();- const spaceData = await supabase- .from("spaces")- .select("*")- .order("created_at", { ascending: true });- const activeSpace = await getActiveSpace();- const session = await getSession();+ // const supabase = await createSupabaseServerClient();+ // const spaceData = await supabase+ // .from("spaces")+ // .select("*")+ // .order("created_at", { ascending: true });+ // const activeSpace = await getActiveSpace();+ // const session = await getSession();- console.log("session", session);+ // console.log("session", session);return (- <SupabaseProvider session={session}>- <DynamicSharedLayout- spaceData={spaceData?.data}- activeSpace={activeSpace}- >- <SupabaseListener serverAccessToken={session?.access_token} />- <div className="full-layout">{children}</div>- </DynamicSharedLayout>- </SupabaseProvider>+ <p></p>+ // <SupabaseProvider session={session}>+ // <DynamicSharedLayout+ // spaceData={spaceData?.data}+ // activeSpace={activeSpace}+ // >+ // <SupabaseListener serverAccessToken={session?.access_token} />+ // <div className="full-layout">{children}</div>+ // </DynamicSharedLayout>+ // </SupabaseProvider>);}diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsxindex 3228ebf80..e906fb4ad 100644--- a/apps/web/app/login/page.tsx+++ b/apps/web/app/login/page.tsx@@ -1,75 +1,6 @@"use client";-import { useSupabase } from "@/utils/database/supabase/provider";-import { LogoBadge } from "@cap/ui";-import dynamic from "next/dynamic";-const Auth = dynamic(- () => import("@supabase/auth-ui-react").then((mod) => mod.Auth),- {- ssr: false,- }-);-import { ThemeSupa } from "@supabase/auth-ui-shared";-import { useRouter } from "next/navigation";-import { supabase } from "@/utils/database/supabase/client";-import { useEffect } from "react";--export default function AuthUI() {- const supabaseHelper = useSupabase();- const router = useRouter();-- useEffect(() => {- const session = supabaseHelper?.session;- if (session && typeof window !== "undefined") {- router.replace("/dashboard/caps");- }- }, [supabaseHelper?.session, router]);-- return (- <div>- <div className="w-full h-full min-h-screen flex items-center relative">- <div className="wrapper text-center">- <div className="max-w-md mx-auto animate-fadeinfast overflow-hidden">- <div className="bg-white p-10 space-y-6 text-sm">- <div>- <a href="/">- <LogoBadge className="h-16 w-auto mx-auto mb-3" />- </a>- <h1 className="text-3xl">Sign in to Cap</h1>- </div>- <div className="flex flex-col space-y-4">- <Auth- supabaseClient={supabase}- view="magic_link"- otpType="magiclink"- providers={[]}- redirectTo={`${process.env.NEXT_PUBLIC_URL}/auth/callback`}- magicLink={true}- showLinks={false}- appearance={{- theme: ThemeSupa,- variables: {- default: {- colors: {- brand: "var(--primary)",- brandAccent: "var(--primary-2)",- },- fonts: {- bodyFontFamily: "var(--font-primary)",- buttonFontFamily: "var(--font-primary)",- inputFontFamily: "var(--font-primary)",- labelFontFamily: "var(--font-primary)",- },- },- },- }}- theme="default"- />- </div>- </div>- </div>- </div>- </div>- </div>- );+//TODO: Auth+export default function LoginPage() {+ return <p>Login</p>;}diff --git a/apps/web/app/share/[videoId]/page.tsx b/apps/web/app/share/[videoId]/page.tsxindex e8a302b9b..eefbdd6a4 100644--- a/apps/web/app/share/[videoId]/page.tsx+++ b/apps/web/app/share/[videoId]/page.tsx@@ -1,18 +1,20 @@"use server";import { Share } from "./Share";-import { createSupabaseServerClient } from "@/utils/database/supabase/server";+// import { createSupabaseServerClient } from "@/utils/database/supabase/server";import { uuidFormat } from "@cap/utils";type Props = {params: { [key: string]: string | string[] | undefined };};+//TODO: Auth+export default async function ShareVideoPage(props: Props) {- const supabase = await createSupabaseServerClient();+ // const supabase = await createSupabaseServerClient();const params = props.params;const videoId = uuidFormat(params.videoId as string);- const video = await supabase.from("videos").select("*").eq("id", videoId);+ // const video = await supabase.from("videos").select("*").eq("id", videoId);- return <Share data={video?.data ? video?.data[0] : null} />;+ return <Share data={null} />;}diff --git a/apps/web/components/forms/NewSpace.tsx b/apps/web/components/forms/NewSpace.tsxindex 0332cda0b..935df3a69 100644--- a/apps/web/components/forms/NewSpace.tsx+++ b/apps/web/components/forms/NewSpace.tsx@@ -14,12 +14,12 @@ import {} from "@cap/ui";import { Input } from "@cap/ui";import { useForm } from "react-hook-form";-import { useSupabase } from "@/utils/database/supabase/provider";+// import { useSupabase } from "@/utils/database/supabase/provider";import { useState } from "react";-import { supabase } from "@/utils/database/supabase/client";+// import { supabase } from "@/utils/database/supabase/client";export function NewSpace() {- const { session } = useSupabase();+ // const { session } = useSupabase();const [isLoading, setIsLoading] = useState(false);const { replace } = useRouter();@@ -31,57 +31,60 @@ export function NewSpace() {resolver: zodResolver(formSchema),});- async function onSubmit(values: z.infer<typeof formSchema>) {- setIsLoading(true);+ //TODO: Auth- const { name } = values;+ // async function onSubmit(values: z.infer<typeof formSchema>) {+ // setIsLoading(true);- console.log("session:");- console.log(session);+ // const { name } = values;- if (!session) {- alert("You must be logged in to create a space.");- setIsLoading(false);- return;- }+ // console.log("session:");+ // console.log(session);- console.log("session:");- console.log(session);+ // if (!session) {+ // alert("You must be logged in to create a space.");+ // setIsLoading(false);+ // return;+ // }- const { error } = await supabase- .from("spaces")- .insert([{ name, owner_id: session.user.id }]);+ // console.log("session:");+ // console.log(session);- if (error) {- alert(error.message);- } else {- window.location.href = "/dashboard";- }- setIsLoading(false);- }+ // const { error } = await supabase+ // .from("spaces")+ // .insert([{ name, owner_id: session.user.id }]);++ // if (error) {+ // alert(error.message);+ // } else {+ // window.location.href = "/dashboard";+ // }+ // setIsLoading(false);+ // }return (- <Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)}>- <div className="space-y-4 mb-8">- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Name</FormLabel>- <FormControl>- <Input placeholder="Your space name" {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- </div>- <Button type="submit" disabled={isLoading}>- {isLoading ? "Loading..." : "Create Space"}- </Button>- </form>- </Form>+ // <Form {...form}>+ // <form onSubmit={form.handleSubmit(onSubmit)}>+ // <div className="space-y-4 mb-8">+ // <FormField+ // control={form.control}+ // name="name"+ // render={({ field }) => (+ // <FormItem>+ // <FormLabel>Name</FormLabel>+ // <FormControl>+ // <Input placeholder="Your space name" {...field} />+ // </FormControl>+ // <FormMessage />+ // </FormItem>+ // )}+ // />+ // </div>+ // <Button type="submit" disabled={isLoading}>+ // {isLoading ? "Loading..." : "Create Space"}+ // </Button>+ // </form>+ // </Form>+ <p></p>);}diff --git a/apps/web/middleware.ts b/apps/web/middleware.tsdeleted file mode 100644index 0fb5a64cc..000000000--- a/apps/web/middleware.ts+++ /dev/null@@ -1,77 +0,0 @@-import { createServerClient, type CookieOptions } from "@supabase/ssr";-import { NextResponse, type NextRequest } from "next/server";-import type { Database } from "@cap/utils";--export async function middleware(request: NextRequest) {- let response = NextResponse.next({- request: {- headers: request.headers,- },- });-- const supabase = createServerClient<Database>(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,- {- cookies: {- get(name: string) {- return request.cookies.get(name)?.value;- },- set(name: string, value: string, options: CookieOptions) {- request.cookies.set({- name,- value,- ...options,- });- response = NextResponse.next({- request: {- headers: request.headers,- },- });- response.cookies.set({- name,- value,- ...options,- });- },- remove(name: string, options: CookieOptions) {- request.cookies.set({- name,- value: "",- ...options,- });- response = NextResponse.next({- request: {- headers: request.headers,- },- });- response.cookies.set({- name,- value: "",- ...options,- });- },- },- }- );-- const user = await supabase.auth.getUser();-- console.log("user:");- console.log(user);-- return response;-}--export const config = {- matcher: [- /*- * Match all request paths except for the ones starting with:- * - _next/static (static files)- * - _next/image (image optimization files)- * - favicon.ico (favicon file)- * Feel free to modify this pattern to include more paths.- */- "/((?!_next/static|_next/image|favicon.ico).*)",- ],-};diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjsindex 7af91db24..98582c241 100644--- a/apps/web/next.config.mjs+++ b/apps/web/next.config.mjs@@ -4,13 +4,6 @@ import million from "million/compiler";import("dotenv").then(({ config }) => config({ path: "../../.env" }));-if (- !process.env.NEXT_PUBLIC_SUPABASE_URL ||- !process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY-) {- throw new Error("Please set Supabase env vars in .env file");-}-if (!process.env.NEXT_PUBLIC_ENVIRONMENT || !process.env.NEXT_PUBLIC_URL) {throw new Error("Please set env vars in .env file");}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0ef69653c..1231f0570 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -16,11 +16,6 @@"@cap/utils": "workspace:*","@headlessui/react": "^1.7.17","@hookform/resolvers": "^3.3.2",- "@supabase/auth-helpers-nextjs": "^0.8.7",- "@supabase/auth-ui-react": "^0.4.2",- "@supabase/auth-ui-shared": "^0.1.6",- "@supabase/ssr": "^0.0.10",- "@supabase/supabase-js": "^2.39.0","aws-sdk": "^2.1530.0","clsx": "^2.0.0","dotenv": "^16.3.1",@@ -44,7 +39,6 @@"eslint": "^8.41.0","eslint-config-next": "13.4.3","postcss": "^8.4.23",- "supabase": "^1.63.1","tailwindcss": "^3","typescript": "^5.3.2"},diff --git a/apps/web/utils/database/supabase/admin.ts b/apps/web/utils/database/supabase/admin.tsdeleted file mode 100644index 7f442c7b0..000000000--- a/apps/web/utils/database/supabase/admin.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createClient } from "@supabase/supabase-js";--export const supabaseAdmin = createClient(- process.env.NEXT_PUBLIC_SUPABASE_URL ?? "",- process.env.SUPABASE_SERVICE_ROLE_KEY ?? ""-);diff --git a/apps/web/utils/database/supabase/browser.ts b/apps/web/utils/database/supabase/browser.tsdeleted file mode 100644index 74aa88d33..000000000--- a/apps/web/utils/database/supabase/browser.ts+++ /dev/null@@ -1,8 +0,0 @@-import { createPagesBrowserClient } from "@supabase/auth-helpers-nextjs";-import type { Database } from "@cap/utils";--export const createBrowserClient = () =>- createPagesBrowserClient<Database>({- supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,- supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,- });diff --git a/apps/web/utils/database/supabase/client.ts b/apps/web/utils/database/supabase/client.tsdeleted file mode 100644index b7482f802..000000000--- a/apps/web/utils/database/supabase/client.ts+++ /dev/null@@ -1,13 +0,0 @@-import { createClient } from "@supabase/supabase-js";--export const supabase = createClient(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,- {- auth: {- autoRefreshToken: false,- detectSessionInUrl: false,- persistSession: false,- },- }-);diff --git a/apps/web/utils/database/supabase/helpers.ts b/apps/web/utils/database/supabase/helpers.tsdeleted file mode 100644index 7d54bbf6f..000000000--- a/apps/web/utils/database/supabase/helpers.ts+++ /dev/null@@ -1,43 +0,0 @@-import { supabase } from "@/utils/database/supabase/client";--export const handleActiveSpace = async (spaceId: string) => {- const { error: userUpdateError } = await supabase- .from("users")- .update({ active_space_id: spaceId });-- if (userUpdateError) {- console.error(userUpdateError);- return false;- }-- return true;-};--const getSession = async () => {- const {- data: { session },- } = await supabase.auth.getSession();-- const { access_token, refresh_token }: any = session;-- await setSession(access_token, refresh_token);-- return session;-};--const refreshSession = async () => {- const {- data: { session },- } = await supabase.auth.refreshSession();-- return session;-};--const setSession = async (access_token: string, refresh_token: string) => {- const { data, error } = await supabase.auth.setSession({- access_token,- refresh_token,- });-- return true;-};diff --git a/apps/web/utils/database/supabase/listener.tsx b/apps/web/utils/database/supabase/listener.tsxdeleted file mode 100644index ce27bc5e6..000000000--- a/apps/web/utils/database/supabase/listener.tsx+++ /dev/null@@ -1,38 +0,0 @@-"use client";-import { useRouter } from "next/navigation";-import { useEffect } from "react";-import { AuthChangeEvent, Session } from "@supabase/supabase-js";-import { supabase } from "@/utils/database/supabase/client";--// this component handles refreshing server data when the user logs in or out-// this method avoids the need to pass a session down to child components-// in order to re-render when the user's session changes-// #elegant!-export default function SupabaseListener({- serverAccessToken,-}: {- serverAccessToken?: string;-}) {- const router = useRouter();-- useEffect(() => {- const {- data: { subscription },- } = supabase.auth.onAuthStateChange(- (_event: AuthChangeEvent, session: Session | null) => {- if (session?.access_token !== serverAccessToken) {- // server and client are out of sync- // reload the page to fetch fresh server data- // https://beta.nextjs.org/docs/data-fetching/mutating- router.refresh();- }- }- );-- return () => {- subscription.unsubscribe();- };- }, [serverAccessToken, router, supabase]);-- return null;-}diff --git a/apps/web/utils/database/supabase/provider.tsx b/apps/web/utils/database/supabase/provider.tsxdeleted file mode 100644index 464a36490..000000000--- a/apps/web/utils/database/supabase/provider.tsx+++ /dev/null@@ -1,28 +0,0 @@-"use client";-import { type Session } from "@supabase/auth-helpers-nextjs";-import { createContext, useContext } from "react";--type MaybeSession = Session | null;--type SupabaseContext = {- session: MaybeSession;-};--// @ts-ignore-const Context = createContext<SupabaseContext>();--export default function SupabaseProvider({- children,- session,-}: {- children: React.ReactNode;- session: MaybeSession;-}) {- return (- <Context.Provider value={{ session }}>- <>{children}</>- </Context.Provider>- );-}--export const useSupabase = () => useContext(Context);diff --git a/apps/web/utils/database/supabase/route.ts b/apps/web/utils/database/supabase/route.tsdeleted file mode 100644index 690f6e6b3..000000000--- a/apps/web/utils/database/supabase/route.ts+++ /dev/null@@ -1,21 +0,0 @@-import { createServerClient } from "@supabase/ssr";-import { cookies } from "next/headers";-import type { Database } from "@cap/utils";--export async function createSupabaseServerClient() {- const cookieStore = cookies();-- const supabase = createServerClient<Database>(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,- {- cookies: {- get(name: string) {- return cookieStore.get(name)?.value;- },- },- }- );-- return supabase;-}diff --git a/apps/web/utils/database/supabase/server.ts b/apps/web/utils/database/supabase/server.tsdeleted file mode 100644index 0fcfc7749..000000000--- a/apps/web/utils/database/supabase/server.ts+++ /dev/null@@ -1,88 +0,0 @@-"use server";--import { createServerClient } from "@supabase/ssr";-import type { Database } from "@cap/utils";-import { cookies } from "next/headers";--export async function createSupabaseServerClient() {- const cookieStore = cookies();-- const supabase = createServerClient<Database>(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,- {- cookies: {- get(name: string) {- return cookieStore.get(name)?.value;- },- },- }- );-- return supabase;-}--export const getSession = async () => {- const supabase = await createSupabaseServerClient();- try {- const {- data: { session },- } = await supabase.auth.getSession();- return session;- } catch (error) {- console.error("Error:", error);- return null;- }-};--export const getActiveSpace = async () => {- const supabase = await createSupabaseServerClient();-- const { data: userData, error: userError } = await supabase- .from("users")- .select("active_space_id")- .single();-- if (userError) {- console.error(userError);- return null;- }-- let spaceId = userData?.active_space_id;-- // If there's no active space set, we need to find the first available space- if (!spaceId) {- const { data: firstSpace, error: firstSpaceError } = await supabase- .from("spaces")- .select("id")- .order("created_at", { ascending: true })- .limit(1)- .single();-- if (firstSpaceError) {- console.error(firstSpaceError);- return null;- }-- spaceId = firstSpace?.id;- }-- if (!spaceId) {- // If we still don't have a space ID, it means there are no spaces available- return null;- }-- // Now retrieve the full details of the active space- const { data: spaceData, error: spaceError } = await supabase- .from("spaces")- .select("*")- .eq("id", spaceId)- .single();-- if (spaceError) {- console.error(spaceError);- return null;- }-- return spaceData;-};diff --git a/package.json b/package.jsonindex 1a2ee9246..77b91c9c9 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"scripts": {"build": "dotenv -e .env -- turbo run build",- "dev": "cd supabase && supabase start && cd .. && dotenv -e .env -- turbo run dev",+ "dev": "dotenv -e .env -- turbo run dev","lint": "turbo run lint","format": "prettier --write \"**/*.{ts,tsx,md}\""},@@ -10,7 +10,6 @@"eslint": "^7.32.0","prettier": "^2.5.1","turbo": "^1.10.16",- "supabase": "^1.131.4","dotenv-cli": "latest"},"packageManager": "[email protected]",diff --git a/packages/utils/schema/schema.sql b/packages/utils/schema/schema.sqldeleted file mode 100644index 960f5796c..000000000--- a/packages/utils/schema/schema.sql+++ /dev/null@@ -1,374 +0,0 @@-CREATE EXTENSION IF NOT EXISTS "pgcrypto";-CREATE EXTENSION IF NOT EXISTS "citext";--CREATE TYPE user_role AS ENUM ('owner', 'admin', 'member');------------ ### TABLES ### --------------------- #################### --------------------- #################### --------------------- #################### ------------CREATE TABLE users (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- full_name VARCHAR(255),- email VARCHAR(255) UNIQUE NOT NULL,- onboarding_questions JSONB,- avatar_url TEXT,- video_quota INT NOT NULL DEFAULT 10,- videos_created INT NOT NULL DEFAULT 0,- stripe_customer_id VARCHAR(255),- stripe_subscription_id VARCHAR(255),- stripe_subscription_status VARCHAR(255),- stripe_subscription_price_id VARCHAR(255),- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Spaces table definition-CREATE TABLE spaces (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- name VARCHAR(255) NOT NULL,- owner_id UUID REFERENCES users(id) ON DELETE SET NULL,- metadata JSONB,- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Now that 'spaces' has been created, we can add the foreign key to 'users'-ALTER TABLE users-ADD COLUMN active_space_id UUID REFERENCES spaces(id) ON DELETE SET NULL;---- Space members table definition (junction table for space to users many-to-many relationship)-CREATE TABLE space_members (- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- space_id UUID NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,- role user_role NOT NULL,- PRIMARY KEY (user_id, space_id)-);---- Videos table definition-CREATE TABLE videos (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- owner_id UUID REFERENCES users(id) ON DELETE CASCADE,- name VARCHAR(255) NOT NULL default 'My Video: ' || to_char(now(), 'YYYY-MM-DD HH24:MI:SS'),- s3_url TEXT default null, -- AWS S3 URL to the video- aws_region VARCHAR(255) default null, -- AWS region where the video is stored- aws_bucket VARCHAR(255) default null, -- AWS bucket where the video is stored- thumbnail_url TEXT, -- URL to the video's thumbnail- duration NUMERIC, -- The length of the video- metadata JSONB, -- Any additional metadata about the video- complete BOOLEAN NOT NULL DEFAULT true, -- Whether video is fully processed- is_public BOOLEAN NOT NULL DEFAULT false, -- Can be shared to spaces- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Shared videos table definition (junction table for video to spaces many-to-many relationship)-CREATE TABLE shared_videos (- video_id UUID REFERENCES videos(id) ON DELETE CASCADE,- space_id UUID REFERENCES spaces(id) ON DELETE CASCADE,- shared_by_user_id UUID REFERENCES users(id) ON DELETE CASCADE, -- Who shared the video- shared_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- PRIMARY KEY (video_id, space_id) -- Ensure a video can't be shared to the same space more than once-);------------ ### RLS POLICIES ### --------------------- #################### --------------------- #################### --------------------- #################### ---------------------- ### USERS ###-ALTER TABLE users ENABLE ROW LEVEL SECURITY;--CREATE POLICY user_view_own_data ON users-FOR SELECT USING (id = auth.uid());--CREATE POLICY user_modify_own_data ON users-FOR UPDATE USING (id = auth.uid());--CREATE POLICY user_delete_own_data ON users-FOR DELETE USING (id = auth.uid());------------ ### SPACES ###-ALTER TABLE spaces ENABLE ROW LEVEL SECURITY;--CREATE POLICY space_view ON spaces-FOR SELECT USING (- EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid())- OR owner_id = auth.uid()-);--CREATE POLICY space_modify ON spaces-FOR UPDATE USING (- (owner_id = auth.uid()) OR- (EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid() AND space_members.role = 'admin'))-);--CREATE POLICY space_delete ON spaces-FOR DELETE USING (- (owner_id = auth.uid()) OR- (EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid() AND space_members.role = 'admin'))-);--CREATE POLICY space_create ON spaces-FOR INSERT WITH CHECK (- (owner_id = auth.uid())-);------------ ### SPACE_MEMBERS ###--ALTER TABLE space_members ENABLE ROW LEVEL SECURITY;--- Allow insertion into space members if you are the owner or an admin of that space-CREATE POLICY space_members_insert ON space_members-FOR INSERT WITH CHECK (- EXISTS (- SELECT 1 FROM spaces- WHERE spaces.id = space_members.space_id- AND spaces.owner_id = auth.uid()- ) OR- EXISTS (- SELECT 1 FROM space_members adm- WHERE- adm.space_id = space_members.space_id- AND adm.user_id = auth.uid()- AND adm.role = 'admin'- )-);---- Allow deletion of space members if you are the owner or an admin of that space-CREATE POLICY space_members_delete ON space_members-FOR DELETE USING (- EXISTS (- SELECT 1 FROM spaces- WHERE spaces.id = space_members.space_id- AND spaces.owner_id = auth.uid()- ) OR- EXISTS (- SELECT 1 FROM space_members adm- WHERE- adm.space_id = space_members.space_id- AND adm.user_id = auth.uid()- AND adm.role = 'admin'- )-);------------ ### VIDEOS ###-ALTER TABLE videos ENABLE ROW LEVEL SECURITY;--CREATE POLICY insert_video ON videos-FOR INSERT WITH CHECK (- auth.uid() = owner_id-);---- Policy to allow users to view their own videos or view videos shared with spaces they belong to-CREATE POLICY select_video ON videos-FOR SELECT USING (- auth.uid() = owner_id OR- EXISTS (- SELECT 1- FROM shared_videos- JOIN space_members ON shared_videos.space_id = space_members.space_id- WHERE shared_videos.video_id = videos.id AND space_members.user_id = auth.uid()- )-);---- Policy to allow users to update their own videos-CREATE POLICY update_video ON videos-FOR UPDATE USING (- auth.uid() = owner_id-);---- Policy to allow users to delete their own videos and to adjust the remaining quota if needed-CREATE POLICY delete_video ON videos-FOR DELETE USING (- auth.uid() = owner_id-);------------ ### SHARED VIDEOS ###-ALTER TABLE shared_videos ENABLE ROW LEVEL SECURITY;---- Policy to view shared videos within the spaces a user belongs to-CREATE POLICY view_shared_videos ON shared_videos-FOR SELECT USING (- EXISTS (- SELECT 1- FROM space_members- WHERE- space_members.space_id = shared_videos.space_id AND- space_members.user_id = auth.uid()- )-);---- Policy to share a video with a space-CREATE POLICY share_video ON shared_videos-FOR INSERT WITH CHECK (- EXISTS (- SELECT 1- FROM videos- WHERE videos.id = shared_videos.video_id- AND videos.owner_id = auth.uid()- ) AND- EXISTS (- SELECT 1- FROM space_members- WHERE space_members.space_id = shared_videos.space_id- AND space_members.user_id = auth.uid()- )-);---- Policy to update shared video records-CREATE POLICY update_shared_videos ON shared_videos-FOR UPDATE USING (- auth.uid() = shared_videos.shared_by_user_id-);---- Adding a policy for deletion if it's allowed to unshare videos,--- it grants permission to the user who shared the video-CREATE POLICY delete_shared_videos ON shared_videos-FOR DELETE USING (- auth.uid() = shared_videos.shared_by_user_id-);------------ ### FUNCTIONS ### --------------------- #################### --------------------- #################### --------------------- #################### ------------/**-* This trigger automatically creates a user entry when a new user signs up via Supabase Auth.-*/-create or replace function public.handle_new_user()-returns trigger as $$-begin- insert into public.users (id, email, full_name, avatar_url)- values (new.id, new.email, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');-- return new;-end;-$$ language plpgsql security definer;-create trigger on_auth_user_created- after insert on auth.users- for each row execute procedure public.handle_new_user();---- Function to increment 'videos_created' counter-CREATE OR REPLACE FUNCTION increment_videos_created()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users- SET videos_created = videos_created + 1- WHERE id = NEW.owner_id;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;---- Trigger to fire the above function after a video is successfully inserted-CREATE TRIGGER increment_videos_created_trigger-AFTER INSERT ON videos-FOR EACH ROW-EXECUTE FUNCTION increment_videos_created();---- Function to decrement 'videos_created' counter-CREATE OR REPLACE FUNCTION decrement_videos_created()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users- SET videos_created = videos_created - 1- WHERE id = OLD.owner_id;- RETURN OLD;-END;-$$ LANGUAGE plpgsql;---- Trigger to fire the above function before a video is successfully deleted-CREATE TRIGGER decrement_videos_created_trigger-BEFORE DELETE ON videos-FOR EACH ROW-EXECUTE FUNCTION decrement_videos_created();---- Automatically update the 'updated_at' column when a row is updated-CREATE OR REPLACE FUNCTION update_timestamp()-RETURNS TRIGGER AS $$-BEGIN- NEW.updated_at = NOW();- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER update_videos_timestamp-BEFORE UPDATE ON videos-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();--CREATE TRIGGER update_spaces_timestamp-BEFORE UPDATE ON spaces-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();--CREATE TRIGGER update_users_timestamp-BEFORE UPDATE ON users-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();---- Validate space membership-CREATE OR REPLACE FUNCTION validate_space_membership()-RETURNS TRIGGER AS $$-BEGIN- IF NOT EXISTS (- SELECT 1 FROM space_members- WHERE user_id = NEW.shared_by_user_id AND space_id = NEW.space_id- )- THEN- RAISE EXCEPTION 'User is not a member of the space.';- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER validate_space_membership_trigger-BEFORE INSERT ON shared_videos-FOR EACH ROW-EXECUTE FUNCTION validate_space_membership();---- Enforce video quota-CREATE OR REPLACE FUNCTION enforce_video_quota()-RETURNS TRIGGER AS $$-BEGIN- IF (SELECT videos_created FROM users WHERE id = NEW.owner_id) >= (SELECT video_quota FROM users WHERE id = NEW.owner_id) THEN- RAISE EXCEPTION 'You have reached your video quota.';- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER enforce_video_quota_trigger-BEFORE INSERT ON videos-FOR EACH ROW-EXECUTE FUNCTION enforce_video_quota();---- Function to set the active space if it's the user's first space or if active_space_id is null-CREATE OR REPLACE FUNCTION set_active_space()-RETURNS TRIGGER AS $$-BEGIN- IF (SELECT active_space_id FROM users WHERE id = NEW.owner_id) IS NULL THEN- UPDATE users SET active_space_id = NEW.id WHERE id = NEW.owner_id;- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;---- Trigger to automatically set active space when a new space is created-CREATE TRIGGER set_active_space_trigger-AFTER INSERT ON spaces-FOR EACH ROW-EXECUTE FUNCTION set_active_space();------------ ### INDEXES ### --------------------- #################### --------------------- #################### --------------------- #################### ------------CREATE INDEX idx_users_active_space ON users(active_space_id);-CREATE INDEX idx_videos_owner ON videos(owner_id);-CREATE INDEX idx_shared_videos_video_id ON shared_videos(video_id);-CREATE INDEX idx_shared_videos_space_id ON shared_videos(space_id);-CREATE INDEX idx_space_members_user_id ON space_members(user_id);-CREATE INDEX idx_space_members_space_id ON space_members(space_id);\ No newline at end of filediff --git a/supabase/.gitignore b/supabase/.gitignoredeleted file mode 100644index 773c7c3e0..000000000--- a/supabase/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-# Supabase-.branches-.tempdiff --git a/supabase/config.toml b/supabase/config.tomldeleted file mode 100644index 4f1e223ca..000000000--- a/supabase/config.toml+++ /dev/null@@ -1,72 +0,0 @@-# A string used to distinguish different Supabase projects on the same host. Defaults to the working-# directory name when running `supabase init`.-project_id = "cap"--[api]-# Port to use for the API URL.-port = 54321-# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API-# endpoints. public and storage are always included.-schemas = ["public", "storage", "graphql_public"]-# Extra schemas to add to the search_path of every request. public is always included.-extra_search_path = ["public", "extensions"]-# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size-# for accidental or malicious requests.-max_rows = 1000--[db]-# Port to use for the local database URL.-port = 54322-# The database major version to use. This has to be the same as your remote database's. Run `SHOW-# server_version;` on the remote database to check.-major_version = 15--[studio]-# Port to use for Supabase Studio.-port = 54323--# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they-# are monitored, and you can view the emails that would have been sent from the web interface.-[inbucket]-# Port to use for the email testing server web interface.-port = 54324-smtp_port = 54325-pop3_port = 54326--[storage]-# The maximum file size allowed (e.g. "5MB", "500KB").-file_size_limit = "50MiB"--[auth]-# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used-# in emails.-site_url = "http://localhost:3000"-# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.-additional_redirect_urls = ["http://localhost:3000/**", "https://localhost:3000/**", "http://localhost:3000/auth/callback", "http://localhost:3000/dashboard", "http://localhost:1420/**", "https://localhost:1420/**"]-# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one-# week).-jwt_expiry = 3600-# Allow/disallow new user signups to your project.-enable_signup = true--[auth.email]-# Allow/disallow new user signups via email to your project.-enable_signup = true-# If enabled, a user will be required to confirm any email change on both the old, and new email-# addresses. If disabled, only the new email is required to confirm.-double_confirm_changes = true-# If enabled, users need to confirm their email address before signing in.-enable_confirmations = false--# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,-# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin`, `notion`, `twitch`,-# `twitter`, `slack`, `spotify`, `workos`, `zoom`.-[auth.external.apple]-enabled = false-client_id = ""-secret = ""-# Overrides the default auth redirectUrl.-redirect_uri = ""-# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,-# or any other third-party OIDC providers.-url = ""diff --git a/supabase/seed.sql b/supabase/seed.sqldeleted file mode 100644index 960f5796c..000000000--- a/supabase/seed.sql+++ /dev/null@@ -1,374 +0,0 @@-CREATE EXTENSION IF NOT EXISTS "pgcrypto";-CREATE EXTENSION IF NOT EXISTS "citext";--CREATE TYPE user_role AS ENUM ('owner', 'admin', 'member');------------ ### TABLES ### --------------------- #################### --------------------- #################### --------------------- #################### ------------CREATE TABLE users (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- full_name VARCHAR(255),- email VARCHAR(255) UNIQUE NOT NULL,- onboarding_questions JSONB,- avatar_url TEXT,- video_quota INT NOT NULL DEFAULT 10,- videos_created INT NOT NULL DEFAULT 0,- stripe_customer_id VARCHAR(255),- stripe_subscription_id VARCHAR(255),- stripe_subscription_status VARCHAR(255),- stripe_subscription_price_id VARCHAR(255),- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Spaces table definition-CREATE TABLE spaces (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- name VARCHAR(255) NOT NULL,- owner_id UUID REFERENCES users(id) ON DELETE SET NULL,- metadata JSONB,- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Now that 'spaces' has been created, we can add the foreign key to 'users'-ALTER TABLE users-ADD COLUMN active_space_id UUID REFERENCES spaces(id) ON DELETE SET NULL;---- Space members table definition (junction table for space to users many-to-many relationship)-CREATE TABLE space_members (- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- space_id UUID NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,- role user_role NOT NULL,- PRIMARY KEY (user_id, space_id)-);---- Videos table definition-CREATE TABLE videos (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- owner_id UUID REFERENCES users(id) ON DELETE CASCADE,- name VARCHAR(255) NOT NULL default 'My Video: ' || to_char(now(), 'YYYY-MM-DD HH24:MI:SS'),- s3_url TEXT default null, -- AWS S3 URL to the video- aws_region VARCHAR(255) default null, -- AWS region where the video is stored- aws_bucket VARCHAR(255) default null, -- AWS bucket where the video is stored- thumbnail_url TEXT, -- URL to the video's thumbnail- duration NUMERIC, -- The length of the video- metadata JSONB, -- Any additional metadata about the video- complete BOOLEAN NOT NULL DEFAULT true, -- Whether video is fully processed- is_public BOOLEAN NOT NULL DEFAULT false, -- Can be shared to spaces- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()-);---- Shared videos table definition (junction table for video to spaces many-to-many relationship)-CREATE TABLE shared_videos (- video_id UUID REFERENCES videos(id) ON DELETE CASCADE,- space_id UUID REFERENCES spaces(id) ON DELETE CASCADE,- shared_by_user_id UUID REFERENCES users(id) ON DELETE CASCADE, -- Who shared the video- shared_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- PRIMARY KEY (video_id, space_id) -- Ensure a video can't be shared to the same space more than once-);------------ ### RLS POLICIES ### --------------------- #################### --------------------- #################### --------------------- #################### ---------------------- ### USERS ###-ALTER TABLE users ENABLE ROW LEVEL SECURITY;--CREATE POLICY user_view_own_data ON users-FOR SELECT USING (id = auth.uid());--CREATE POLICY user_modify_own_data ON users-FOR UPDATE USING (id = auth.uid());--CREATE POLICY user_delete_own_data ON users-FOR DELETE USING (id = auth.uid());------------ ### SPACES ###-ALTER TABLE spaces ENABLE ROW LEVEL SECURITY;--CREATE POLICY space_view ON spaces-FOR SELECT USING (- EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid())- OR owner_id = auth.uid()-);--CREATE POLICY space_modify ON spaces-FOR UPDATE USING (- (owner_id = auth.uid()) OR- (EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid() AND space_members.role = 'admin'))-);--CREATE POLICY space_delete ON spaces-FOR DELETE USING (- (owner_id = auth.uid()) OR- (EXISTS (SELECT 1 FROM space_members WHERE space_members.space_id = spaces.id AND space_members.user_id = auth.uid() AND space_members.role = 'admin'))-);--CREATE POLICY space_create ON spaces-FOR INSERT WITH CHECK (- (owner_id = auth.uid())-);------------ ### SPACE_MEMBERS ###--ALTER TABLE space_members ENABLE ROW LEVEL SECURITY;--- Allow insertion into space members if you are the owner or an admin of that space-CREATE POLICY space_members_insert ON space_members-FOR INSERT WITH CHECK (- EXISTS (- SELECT 1 FROM spaces- WHERE spaces.id = space_members.space_id- AND spaces.owner_id = auth.uid()- ) OR- EXISTS (- SELECT 1 FROM space_members adm- WHERE- adm.space_id = space_members.space_id- AND adm.user_id = auth.uid()- AND adm.role = 'admin'- )-);---- Allow deletion of space members if you are the owner or an admin of that space-CREATE POLICY space_members_delete ON space_members-FOR DELETE USING (- EXISTS (- SELECT 1 FROM spaces- WHERE spaces.id = space_members.space_id- AND spaces.owner_id = auth.uid()- ) OR- EXISTS (- SELECT 1 FROM space_members adm- WHERE- adm.space_id = space_members.space_id- AND adm.user_id = auth.uid()- AND adm.role = 'admin'- )-);------------ ### VIDEOS ###-ALTER TABLE videos ENABLE ROW LEVEL SECURITY;--CREATE POLICY insert_video ON videos-FOR INSERT WITH CHECK (- auth.uid() = owner_id-);---- Policy to allow users to view their own videos or view videos shared with spaces they belong to-CREATE POLICY select_video ON videos-FOR SELECT USING (- auth.uid() = owner_id OR- EXISTS (- SELECT 1- FROM shared_videos- JOIN space_members ON shared_videos.space_id = space_members.space_id- WHERE shared_videos.video_id = videos.id AND space_members.user_id = auth.uid()- )-);---- Policy to allow users to update their own videos-CREATE POLICY update_video ON videos-FOR UPDATE USING (- auth.uid() = owner_id-);---- Policy to allow users to delete their own videos and to adjust the remaining quota if needed-CREATE POLICY delete_video ON videos-FOR DELETE USING (- auth.uid() = owner_id-);------------ ### SHARED VIDEOS ###-ALTER TABLE shared_videos ENABLE ROW LEVEL SECURITY;---- Policy to view shared videos within the spaces a user belongs to-CREATE POLICY view_shared_videos ON shared_videos-FOR SELECT USING (- EXISTS (- SELECT 1- FROM space_members- WHERE- space_members.space_id = shared_videos.space_id AND- space_members.user_id = auth.uid()- )-);---- Policy to share a video with a space-CREATE POLICY share_video ON shared_videos-FOR INSERT WITH CHECK (- EXISTS (- SELECT 1- FROM videos- WHERE videos.id = shared_videos.video_id- AND videos.owner_id = auth.uid()- ) AND- EXISTS (- SELECT 1- FROM space_members- WHERE space_members.space_id = shared_videos.space_id- AND space_members.user_id = auth.uid()- )-);---- Policy to update shared video records-CREATE POLICY update_shared_videos ON shared_videos-FOR UPDATE USING (- auth.uid() = shared_videos.shared_by_user_id-);---- Adding a policy for deletion if it's allowed to unshare videos,--- it grants permission to the user who shared the video-CREATE POLICY delete_shared_videos ON shared_videos-FOR DELETE USING (- auth.uid() = shared_videos.shared_by_user_id-);------------ ### FUNCTIONS ### --------------------- #################### --------------------- #################### --------------------- #################### ------------/**-* This trigger automatically creates a user entry when a new user signs up via Supabase Auth.-*/-create or replace function public.handle_new_user()-returns trigger as $$-begin- insert into public.users (id, email, full_name, avatar_url)- values (new.id, new.email, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');-- return new;-end;-$$ language plpgsql security definer;-create trigger on_auth_user_created- after insert on auth.users- for each row execute procedure public.handle_new_user();---- Function to increment 'videos_created' counter-CREATE OR REPLACE FUNCTION increment_videos_created()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users- SET videos_created = videos_created + 1- WHERE id = NEW.owner_id;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;---- Trigger to fire the above function after a video is successfully inserted-CREATE TRIGGER increment_videos_created_trigger-AFTER INSERT ON videos-FOR EACH ROW-EXECUTE FUNCTION increment_videos_created();---- Function to decrement 'videos_created' counter-CREATE OR REPLACE FUNCTION decrement_videos_created()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users- SET videos_created = videos_created - 1- WHERE id = OLD.owner_id;- RETURN OLD;-END;-$$ LANGUAGE plpgsql;---- Trigger to fire the above function before a video is successfully deleted-CREATE TRIGGER decrement_videos_created_trigger-BEFORE DELETE ON videos-FOR EACH ROW-EXECUTE FUNCTION decrement_videos_created();---- Automatically update the 'updated_at' column when a row is updated-CREATE OR REPLACE FUNCTION update_timestamp()-RETURNS TRIGGER AS $$-BEGIN- NEW.updated_at = NOW();- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER update_videos_timestamp-BEFORE UPDATE ON videos-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();--CREATE TRIGGER update_spaces_timestamp-BEFORE UPDATE ON spaces-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();--CREATE TRIGGER update_users_timestamp-BEFORE UPDATE ON users-FOR EACH ROW-EXECUTE FUNCTION update_timestamp();---- Validate space membership-CREATE OR REPLACE FUNCTION validate_space_membership()-RETURNS TRIGGER AS $$-BEGIN- IF NOT EXISTS (- SELECT 1 FROM space_members- WHERE user_id = NEW.shared_by_user_id AND space_id = NEW.space_id- )- THEN- RAISE EXCEPTION 'User is not a member of the space.';- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER validate_space_membership_trigger-BEFORE INSERT ON shared_videos-FOR EACH ROW-EXECUTE FUNCTION validate_space_membership();---- Enforce video quota-CREATE OR REPLACE FUNCTION enforce_video_quota()-RETURNS TRIGGER AS $$-BEGIN- IF (SELECT videos_created FROM users WHERE id = NEW.owner_id) >= (SELECT video_quota FROM users WHERE id = NEW.owner_id) THEN- RAISE EXCEPTION 'You have reached your video quota.';- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER enforce_video_quota_trigger-BEFORE INSERT ON videos-FOR EACH ROW-EXECUTE FUNCTION enforce_video_quota();---- Function to set the active space if it's the user's first space or if active_space_id is null-CREATE OR REPLACE FUNCTION set_active_space()-RETURNS TRIGGER AS $$-BEGIN- IF (SELECT active_space_id FROM users WHERE id = NEW.owner_id) IS NULL THEN- UPDATE users SET active_space_id = NEW.id WHERE id = NEW.owner_id;- END IF;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;---- Trigger to automatically set active space when a new space is created-CREATE TRIGGER set_active_space_trigger-AFTER INSERT ON spaces-FOR EACH ROW-EXECUTE FUNCTION set_active_space();------------ ### INDEXES ### --------------------- #################### --------------------- #################### --------------------- #################### ------------CREATE INDEX idx_users_active_space ON users(active_space_id);-CREATE INDEX idx_videos_owner ON videos(owner_id);-CREATE INDEX idx_shared_videos_video_id ON shared_videos(video_id);-CREATE INDEX idx_shared_videos_space_id ON shared_videos(space_id);-CREATE INDEX idx_space_members_user_id ON space_members(user_id);-CREATE INDEX idx_space_members_space_id ON space_members(space_id);\ No newline at end of filediff --git a/supabase/templates/magic_link.html b/supabase/templates/magic_link.htmldeleted file mode 100644index 288f8cf63..000000000--- a/supabase/templates/magic_link.html+++ /dev/null@@ -1,6 +0,0 @@-<html>- <body>- <h2>Your Cap Signin</h2>- <p>Use code <strong>{{ .Token }} to sign in to Cap</strong></p>- </body>-</html>