Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Merge main

React-Admin CI89d87d9fcbdf
diff --git a/.env.development b/.env.development
index f0c6af4c..13861991 100644
--- a/.env.development
+++ b/.env.development
@@ -1,8 +1,6 @@
SKIP_PREFLIGHT_CHECK=true
VITE_SUPABASE_URL=http://127.0.0.1:54321
-VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
+VITE_SB_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH
VITE_IS_DEMO=false
VITE_INBOUND_EMAIL=2aff30e603e54dc3eb556bd9e03ee099@inbound.postmarkapp.com
-SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
-DATABASE_URL=postgres://postgres:[email protected]:54322/postgres
\ No newline at end of file
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index 4654af75..894f2bce 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -101,8 +101,8 @@ jobs:
SUPABASE_DB_PASSWORD: ${{ secrets.SUPABASE_DB_PASSWORD }}
SUPABASE_PROJECT_ID: ${{ secrets.SUPABASE_PROJECT_ID }}
VITE_SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
- VITE_SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }}
- IS_SUPABASE_CONFIGURED: ${{ secrets.SUPABASE_ACCESS_TOKEN && secrets.SUPABASE_DB_PASSWORD && secrets.SUPABASE_PROJECT_ID && secrets.SUPABASE_URL && secrets.SUPABASE_ANON_KEY }}
+ VITE_SB_PUBLISHABLE_KEY: ${{ secrets.SB_PUBLISHABLE_KEY }}
+ IS_SUPABASE_CONFIGURED: ${{ secrets.SUPABASE_ACCESS_TOKEN && secrets.SUPABASE_DB_PASSWORD && secrets.SUPABASE_PROJECT_ID && secrets.SUPABASE_URL && secrets.SB_PUBLISHABLE_KEY }}
VITE_IS_DEMO: ${{ vars.VITE_IS_DEMO }}
VITE_INBOUND_EMAIL: ${{ vars.VITE_INBOUND_EMAIL }}
PRODUCTION_REMOTE: https://git:${{ secrets.DEPLOY_TOKEN || secrets.GITHUB_TOKEN }}@github.com/${{ vars.DEPLOY_REPOSITORY }}
@@ -172,9 +172,9 @@ jobs:
name: Check SUPABASE_URL secret
run: echo ':warning:SUPABASE_URL secret is missing' >> $GITHUB_STEP_SUMMARY
- - if: ${{ !env.VITE_SUPABASE_ANON_KEY }}
- name: Check SUPABASE_ANON_KEY secret
- run: echo ':warning:SUPABASE_ANON_KEY secret is missing' >> $GITHUB_STEP_SUMMARY
+ - if: ${{ !env.VITE_SB_PUBLISHABLE_KEY }}
+ name: Check SB_PUBLISHABLE_KEY secret
+ run: echo ':warning:SB_PUBLISHABLE_KEY secret is missing' >> $GITHUB_STEP_SUMMARY
- if: ${{ !env.POSTMARK_WEBHOOK_USER }}
name: Check POSTMARK_WEBHOOK_USER secret
diff --git a/doc/src/content/docs/developers/data-providers.mdx b/doc/src/content/docs/developers/data-providers.mdx
index 76446743..d0e54c1a 100644
--- a/doc/src/content/docs/developers/data-providers.mdx
+++ b/doc/src/content/docs/developers/data-providers.mdx
@@ -53,7 +53,7 @@ export default App;
```
-**Warning**: As supabase is still the default data provider, its environment variables (`VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY`) are **still required**.
+**Warning**: As supabase is still the default data provider, its environment variables (`VITE_SUPABASE_URL` and `VITE_SB_PUBLISHABLE_KEY`) are **still required**.
### Filters Syntax
diff --git a/doc/src/content/docs/developers/deploy.mdx b/doc/src/content/docs/developers/deploy.mdx
index 3dce77a1..61119169 100644
--- a/doc/src/content/docs/developers/deploy.mdx
+++ b/doc/src/content/docs/developers/deploy.mdx
@@ -67,7 +67,7 @@ SUPABASE_ACCESS_TOKEN: Your personal access token, can be found at https://supab
SUPABASE_DB_PASSWORD: Your supabase database password
SUPABASE_PROJECT_ID: Your supabase project id
SUPABASE_URL: Your supabase project URL
-SUPABASE_ANON_KEY: Your supabase project anonymous key
+SB_PUBLISHABLE_KEY: Your supabase project publishable key
POSTMARK_WEBHOOK_USER: User configured in Postmark to secure the webhook
POSTMARK_WEBHOOK_PASSWORD: Password configured in Postmark to secure the webhook
POSTMARK_WEBHOOK_AUTHORIZED_IPS: List of IPs (comma separated) authorized to send requests to the Postmark webhook
diff --git a/doc/src/content/docs/developers/supabase-configuration.mdx b/doc/src/content/docs/developers/supabase-configuration.mdx
index 7df48bfe..1b9c4292 100644
--- a/doc/src/content/docs/developers/supabase-configuration.mdx
+++ b/doc/src/content/docs/developers/supabase-configuration.mdx
@@ -33,6 +33,12 @@ Now, link the local project to the Supabase instance. You'll be asked to enter t
npx supabase link --project-ref ********************
```
+Set up secrets for the Supabase instance (follow this [guide](https://supabase.com/docs/guides/api/api-keys#where-to-find-keys) to find your publishable and secret keys):
+
+```sh
+npx supabase secrets set SB_PUBLISHABLE_KEY=<publishable_key> SB_SECRET_KEY=<secret_key>
+```
+
Then, apply the migrations and deploy the edge functions:
```sh
@@ -44,7 +50,7 @@ Finally, add a `.env.production.local` file in the root directory with your remo
```sh
VITE_SUPABASE_URL=<instance_url>
-VITE_SUPABASE_ANON_KEY=<instance_anon_token>
+VITE_SB_PUBLISHABLE_KEY=<instance_publishable_key>
```
Atomic CRM requires that you set up an email provider on your Supabase instance. If you don't have one yet, please follow the instructions detailed in the [Email Provider Setup](#email-provider-setup) section.
diff --git a/scripts/supabase-remote-init.mjs b/scripts/supabase-remote-init.mjs
index 84513a07..2a151be2 100644
--- a/scripts/supabase-remote-init.mjs
+++ b/scripts/supabase-remote-init.mjs
@@ -17,7 +17,7 @@ import fs from "node:fs";
await waitForProjectToBeReady({ projectRef });
// This also ensures the project is ready
- const { anonKey } = await fetchApiKeys({
+ const { publishableKey, secretKey } = await fetchApiKeys({
projectRef,
});
@@ -30,9 +30,15 @@ import fs from "node:fs";
databasePassword,
});
+ await setupSupabaseSecrets({
+ projectRef,
+ publishableKey,
+ secretKey,
+ });
+
await persistSupabaseEnv({
projectRef,
- anonKey,
+ publishableKey,
});
})();
@@ -150,7 +156,8 @@ async function setupDatabase({ databasePassword }) {
}
async function fetchApiKeys({ projectRef }) {
- let anonKey = "";
+ let publishableKey = "";
+ let secretKey = "";
try {
const { stdout, exitCode } = await execa(
"npx",
@@ -175,8 +182,25 @@ async function fetchApiKeys({ projectRef }) {
if (!matchJSON) {
throw new Error("Invalid JSON output");
}
- const jsonOuput = JSON.parse(matchJSON[0]);
- anonKey = jsonOuput.find((key) => key.name === "anon")?.api_key;
+ const jsonOutput = JSON.parse(matchJSON[0]);
+
+ // Prioritize the default publishable key, but any publishable key will work.
+ publishableKey = jsonOutput.find(
+ (key) => key.type === "publishable" && key.name === "default",
+ )?.api_key;
+ if (!publishableKey) {
+ publishableKey = jsonOutput.find(
+ (key) => key.type === "publishable",
+ )?.api_key;
+ }
+
+ // Prioritize the default secret key, but any secret key will work.
+ secretKey = jsonOutput.find(
+ (key) => key.type === "secret" && key.name === "default",
+ )?.api_key;
+ if (!secretKey) {
+ secretKey = jsonOutput.find((key) => key.type === "secret")?.api_key;
+ }
}
} catch (e) {
console.error("Failed to fetch API keys");
@@ -184,20 +208,38 @@ async function fetchApiKeys({ projectRef }) {
throw e;
}
- if (anonKey === "") {
+ if (publishableKey === "" || secretKey === "") {
await sleep(1000);
return fetchApiKeys({ projectRef });
}
- return { anonKey };
+ return { publishableKey, secretKey };
+}
+
+async function setupSupabaseSecrets({ projectRef, publishableKey, secretKey }) {
+ await execa(
+ "npx",
+ [
+ "supabase",
+ "secrets",
+ "set",
+ `SB_PUBLISHABLE_KEY=${publishableKey}`,
+ `SB_SECRET_KEY=${secretKey}`,
+ "--project-ref",
+ projectRef,
+ ],
+ {
+ stdio: "inherit",
+ },
+ );
}
-async function persistSupabaseEnv({ projectRef, anonKey }) {
+async function persistSupabaseEnv({ projectRef, publishableKey }) {
fs.writeFileSync(
`${process.cwd()}/.env.production.local`,
`
VITE_SUPABASE_URL=https://${projectRef}.supabase.co
-VITE_SUPABASE_ANON_KEY=${anonKey}`,
+VITE_SB_PUBLISHABLE_KEY=${publishableKey}`,
{ flag: "a" },
);
}
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 9e593e41..4524c18e 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -22,13 +22,15 @@ import { supabase } from "./supabase";
if (import.meta.env.VITE_SUPABASE_URL === undefined) {
throw new Error("Please set the VITE_SUPABASE_URL environment variable");
}
-if (import.meta.env.VITE_SUPABASE_ANON_KEY === undefined) {
- throw new Error("Please set the VITE_SUPABASE_ANON_KEY environment variable");
+if (import.meta.env.VITE_SB_PUBLISHABLE_KEY === undefined) {
+ throw new Error(
+ "Please set the VITE_SB_PUBLISHABLE_KEY environment variable",
+ );
}
const baseDataProvider = supabaseDataProvider({
instanceUrl: import.meta.env.VITE_SUPABASE_URL,
- apiKey: import.meta.env.VITE_SUPABASE_ANON_KEY,
+ apiKey: import.meta.env.VITE_SB_PUBLISHABLE_KEY,
supabaseClient: supabase,
sortOrder: "asc,desc.nullslast" as any,
});
@@ -145,7 +147,7 @@ const dataProviderWithCustomMethods = {
},
async updatePassword(id: Identifier) {
const { data: passwordUpdated, error } =
- await supabase.functions.invoke<boolean>("updatePassword", {
+ await supabase.functions.invoke<boolean>("update_password", {
method: "PATCH",
body: {
sales_id: id,
@@ -153,7 +155,7 @@ const dataProviderWithCustomMethods = {
});
if (!passwordUpdated || error) {
- console.error("passwordUpdate.error", error);
+ console.error("update_password.error", error);
throw new Error("Failed to update password");
}
@@ -191,13 +193,13 @@ const dataProviderWithCustomMethods = {
return getIsInitialized();
},
async mergeContacts(sourceId: Identifier, targetId: Identifier) {
- const { data, error } = await supabase.functions.invoke("mergeContacts", {
+ const { data, error } = await supabase.functions.invoke("merge_contacts", {
method: "POST",
body: { loserId: sourceId, winnerId: targetId },
});
if (error) {
- console.error("mergeContacts.error", error);
+ console.error("merge_contacts.error", error);
throw new Error("Failed to merge contacts");
}
diff --git a/src/components/atomic-crm/providers/supabase/supabase.ts b/src/components/atomic-crm/providers/supabase/supabase.ts
index a958c0c3..26146103 100644
--- a/src/components/atomic-crm/providers/supabase/supabase.ts
+++ b/src/components/atomic-crm/providers/supabase/supabase.ts
@@ -2,5 +2,5 @@ import { createClient } from "@supabase/supabase-js";
export const supabase = createClient(
import.meta.env.VITE_SUPABASE_URL,
- import.meta.env.VITE_SUPABASE_ANON_KEY,
+ import.meta.env.VITE_SB_PUBLISHABLE_KEY,
);
diff --git a/supabase/config.toml b/supabase/config.toml
index 76296942..1d14c65b 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -153,10 +153,11 @@ s3_access_key = "env(S3_ACCESS_KEY)"
# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
s3_secret_key = "env(S3_SECRET_KEY)"
+[functions.merge_contacts]
+verify_jwt = false
[functions.postmark]
verify_jwt = false
-
-# https://github.com/supabase/supabase/issues/17164#issuecomment-2683354018
-# This should only affect Supabase local instances
+[functions.update_password]
+verify_jwt = false
[functions.users]
verify_jwt = false
diff --git a/supabase/functions/.env.development b/supabase/functions/.env.development
index 111e35bd..c07bcf9c 100644
--- a/supabase/functions/.env.development
+++ b/supabase/functions/.env.development
@@ -5,3 +5,7 @@ POSTMARK_WEBHOOK_PASSWORD=testpwd
# 172.18.0.1 and 172.19.0.1 are for local dev only
# 192.168.65.1 is for Docker Desktop on Mac
POSTMARK_WEBHOOK_AUTHORIZED_IPS=3.134.147.250,50.31.156.6,50.31.156.77,18.217.206.57,172.18.0.1,172.19.0.1,192.168.65.1
+
+SB_JWT_ISSUER=http://127.0.0.1:54321/auth/v1
+SB_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH
+SB_SECRET_KEY=sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz
diff --git a/supabase/functions/_shared/authentication.ts b/supabase/functions/_shared/authentication.ts
new file mode 100644
index 00000000..504eafa0
--- /dev/null
+++ b/supabase/functions/_shared/authentication.ts
@@ -0,0 +1,80 @@
+// Based on https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/_shared/jwt/default.ts
+import * as jose from "jsr:@panva/jose@6";
+import { createClient, type User } from "jsr:@supabase/supabase-js@2";
+import { createErrorResponse } from "./utils.ts";
+
+const SUPABASE_JWT_ISSUER =
+ Deno.env.get("SB_JWT_ISSUER") ?? Deno.env.get("SUPABASE_URL") + "/auth/v1";
+
+const SUPABASE_JWT_KEYS = jose.createRemoteJWKSet(
+ new URL(Deno.env.get("SUPABASE_URL")! + "/auth/v1/.well-known/jwks.json"),
+);
+
+function getAuthToken(req: Request) {
+ const authHeader = req.headers.get("authorization");
+ if (!authHeader) {
+ throw new Error("Missing authorization header");
+ }
+ const [bearer, token] = authHeader.split(" ");
+ if (bearer !== "Bearer") {
+ throw new Error(`Auth header is not 'Bearer {token}'`);
+ }
+
+ return token;
+}
+
+function verifySupabaseJWT(jwt: string) {
+ return jose.jwtVerify(jwt, SUPABASE_JWT_KEYS, {
+ issuer: SUPABASE_JWT_ISSUER,
+ });
+}
+
+/**
+ * Validates the Authorization header to ensure that a user is authenticated.
+ */
+export const AuthMiddleware = async (
+ req: Request,
+ next: (req: Request) => Promise<Response>,
+) => {
+ if (req.method === "OPTIONS") return await next(req);
+
+ try {
+ const token = getAuthToken(req);
+ const isValidJWT = await verifySupabaseJWT(token);
+
+ if (isValidJWT) return await next(req);
+
+ return createErrorResponse(401, "Invalid authentication");
+ } catch (e) {
+ return createErrorResponse(401, e?.toString() || "Unauthorized");
+ }
+};
+
+/**
+ * Get the authenticated user using the authorization header.
+ * User will be undefined for OPTIONS requests.
+ */
+export const UserMiddleware = async (
+ req: Request,
+ next: (req: Request, user?: User) => Promise<Response>,
+) => {
+ if (req.method === "OPTIONS") return await next(req);
+
+ try {
+ const authHeader = req.headers.get("Authorization")!;
+ const localClient = createClient(
+ Deno.env.get("SUPABASE_URL") ?? "",
+ Deno.env.get("SB_PUBLISHABLE_KEY") ?? "",
+ { global: { headers: { Authorization: authHeader } } },
+ );
+
+ const { data, error: authError } = await localClient.auth.getUser();
+ if (!data?.user || authError) {
+ return createErrorResponse(401, "Unauthorized");
+ }
+
+ return next(req, data.user);
+ } catch (err) {
+ return createErrorResponse(401, err?.toString() || "Unauthorized");
+ }
+};
diff --git a/supabase/functions/_shared/cors.ts b/supabase/functions/_shared/cors.ts
new file mode 100644
index 00000000..44e91c72
--- /dev/null
+++ b/supabase/functions/_shared/cors.ts
@@ -0,0 +1,20 @@
+export const corsHeaders = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers":
+ "authorization, x-client-info, apikey, content-type",
+ "Access-Control-Allow-Methods": "POST, PATCH, DELETE",
+};
+
+/**
+ * Handle OPTIONS requests for CORS preflight.
+ */
+export function OptionsMiddleware(
+ req: Request,
+ next: (req: Request) => Promise<Response>,
+) {
+ if (req.method === "OPTIONS") {
+ return new Response(null, { status: 204, headers: corsHeaders });
+ }
+
+ return next(req);
+}
diff --git a/supabase/functions/_shared/getUserSale.ts b/supabase/functions/_shared/getUserSale.ts
new file mode 100644
index 00000000..83cc794d
--- /dev/null
+++ b/supabase/functions/_shared/getUserSale.ts
@@ -0,0 +1,15 @@
+import { type User } from "jsr:@supabase/supabase-js@2";
+import { supabaseAdmin } from "./supabaseAdmin.ts";
+
+/**
+ * Get the sale associated to the provided user.
+ */
+export const getUserSale = async (user: User) => {
+ return (
+ await supabaseAdmin
+ .from("sales")
+ .select("*")
+ .eq("user_id", user.id)
+ .single()
+ )?.data;
+};
diff --git a/supabase/functions/_shared/supabaseAdmin.ts b/supabase/functions/_shared/supabaseAdmin.ts
index bdbdf263..72b26943 100644
--- a/supabase/functions/_shared/supabaseAdmin.ts
+++ b/supabase/functions/_shared/supabaseAdmin.ts
@@ -3,7 +3,7 @@ import { createClient } from "jsr:@supabase/supabase-js@2";
export const supabaseAdmin: SupabaseClient = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
- Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "",
+ Deno.env.get("SB_SECRET_KEY") ?? "",
{
auth: {
autoRefreshToken: false,
diff --git a/supabase/functions/_shared/utils.ts b/supabase/functions/_shared/utils.ts
index 2195aae1..d4399cf2 100644
--- a/supabase/functions/_shared/utils.ts
+++ b/supabase/functions/_shared/utils.ts
@@ -1,9 +1,4 @@
-export const corsHeaders = {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Headers":
- "authorization, x-client-info, apikey, content-type",
- "Access-Control-Allow-Methods": "POST, PATCH, DELETE",
-};
+import { corsHeaders } from "./cors.ts";
export function createErrorResponse(status: number, message: string) {
return new Response(JSON.stringify({ status, message }), {
diff --git a/supabase/functions/mergeContacts/index.ts b/supabase/functions/merge_contacts/index.ts
similarity index 73%
rename from supabase/functions/mergeContacts/index.ts
rename to supabase/functions/merge_contacts/index.ts
index bace4688..bd3d28e7 100644
--- a/supabase/functions/mergeContacts/index.ts
+++ b/supabase/functions/merge_contacts/index.ts
@@ -1,8 +1,9 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
-import { createClient } from "jsr:@supabase/supabase-js@2";
import { sql, type Selectable } from "https://esm.sh/[email protected]";
import { db, type ContactsTable, CompiledQuery } from "../_shared/db.ts";
-import { corsHeaders, createErrorResponse } from "../_shared/utils.ts";
+import { corsHeaders, OptionsMiddleware } from "../_shared/cors.ts";
+import { createErrorResponse } from "../_shared/utils.ts";
+import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";
type Contact = Selectable<ContactsTable>;
@@ -157,59 +158,37 @@ async function mergeContacts(
}
}
-Deno.serve(async (req: Request) => {
- // Handle CORS preflight
- if (req.method === "OPTIONS") {
- return new Response(null, {
- status: 204,
- headers: corsHeaders,
- });
- }
-
- // Authenticate user via Supabase client (bypasses RLS, so we need explicit auth check)
- const authHeader = req.headers.get("Authorization");
- if (!authHeader) {
- return createErrorResponse(401, "Missing Authorization header");
- }
-
- const supabaseClient = createClient(
- Deno.env.get("SUPABASE_URL") ?? "",
- Deno.env.get("SUPABASE_ANON_KEY") ?? "",
- { global: { headers: { Authorization: authHeader } } },
- );
-
- const {
- data: { user },
- error: authError,
- } = await supabaseClient.auth.getUser();
- if (!user || authError) {
- return createErrorResponse(401, "Unauthorized");
- }
-
- // Handle POST request
- if (req.method === "POST") {
- try {
- const { loserId, winnerId } = await req.json();
-
- if (!loserId || !winnerId) {
- return createErrorResponse(400, "Missing loserId or winnerId");
- }
-
- const result = await mergeContacts(loserId, winnerId, user.id);
-
- return new Response(JSON.stringify(result), {
- headers: { "Content-Type": "application/json", ...corsHeaders },
- });
- } catch (error) {
- console.error("Merge failed:", error);
- return createErrorResponse(
- 500,
- `Failed to merge contacts: ${
- error instanceof Error ? error.message : "Unknown error"
- }`,
- );
- }
- }
-
- return createErrorResponse(405, "Method Not Allowed");
-});
+Deno.serve(async (req: Request) =>
+ OptionsMiddleware(req, async (req) =>
+ AuthMiddleware(req, async (req) =>
+ UserMiddleware(req, async (req, user) => {
+ // Handle POST request
+ if (req.method === "POST") {
+ try {
+ const { loserId, winnerId } = await req.json();
+
+ if (!loserId || !winnerId) {
+ return createErrorResponse(400, "Missing loserId or winnerId");
+ }
+
+ const result = await mergeContacts(loserId, winnerId, user.id);
+
+ return new Response(JSON.stringify(result), {
+ headers: { "Content-Type": "application/json", ...corsHeaders },
+ });
+ } catch (error) {
+ console.error("Merge failed:", error);
+ return createErrorResponse(
+ 500,
+ `Failed to merge contacts: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ );
+ }
+ }
+
+ return createErrorResponse(405, "Method Not Allowed");
+ }),
+ ),
+ ),
+);
diff --git a/supabase/functions/updatePassword/index.ts b/supabase/functions/updatePassword/index.ts
deleted file mode 100644
index a53ae46e..00000000
--- a/supabase/functions/updatePassword/index.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import "jsr:@supabase/functions-js/edge-runtime.d.ts";
-import { createClient } from "jsr:@supabase/supabase-js@2";
-import { corsHeaders, createErrorResponse } from "../_shared/utils.ts";
-import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
-
-async function updatePassword(user: any) {
- const { data, error } = await supabaseAdmin.auth.resetPasswordForEmail(
- user.email,
- );
-
- if (!data || error) {
- return createErrorResponse(500, "Internal Server Error");
- }
-
- return new Response(
- JSON.stringify({
- data,
- }),
- {
- headers: { "Content-Type": "application/json", ...corsHeaders },
- },
- );
-}
-
-Deno.serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response(null, {
- status: 204,
- headers: corsHeaders,
- });
- }
-
- const authHeader = req.headers.get("Authorization")!;
- const localClient = createClient(
- Deno.env.get("SUPABASE_URL") ?? "",
- Deno.env.get("SUPABASE_ANON_KEY") ?? "",
- { global: { headers: { Authorization: authHeader } } },
- );
-
- const { data } = await localClient.auth.getUser();
- if (!data?.user) {
- return createErrorResponse(401, "Unauthorized");
- }
-
- if (req.method === "PATCH") {
- return updatePassword(data.user);
- }
-
- return createErrorResponse(405, "Method Not Allowed");
-});
diff --git a/supabase/functions/update_password/index.ts b/supabase/functions/update_password/index.ts
new file mode 100644
index 00000000..c43b26e6
--- /dev/null
+++ b/supabase/functions/update_password/index.ts
@@ -0,0 +1,38 @@
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { corsHeaders, OptionsMiddleware } from "../_shared/cors.ts";
+import { createErrorResponse } from "../_shared/utils.ts";
+import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
+import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";
+
+async function updatePassword(user: any) {
+ const { data, error } = await supabaseAdmin.auth.resetPasswordForEmail(
+ user.email,
+ );
+
+ if (!data || error) {
+ return createErrorResponse(500, "Internal Server Error");
+ }
+
+ return new Response(
+ JSON.stringify({
+ data,
+ }),
+ {
+ headers: { "Content-Type": "application/json", ...corsHeaders },
+ },
+ );
+}
+
+Deno.serve(async (req: Request) =>
+ OptionsMiddleware(req, async (req) =>
+ AuthMiddleware(req, async (req) =>
+ UserMiddleware(req, async (req, user) => {
+ if (req.method === "PATCH") {
+ return updatePassword(user);
+ }
+
+ return createErrorResponse(405, "Method Not Allowed");
+ }),
+ ),
+ ),
+);
diff --git a/vite.config.ts b/vite.config.ts
index faeb0828..3cb0e73c 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -32,8 +32,8 @@ export default defineConfig({
"import.meta.env.VITE_SUPABASE_URL": JSON.stringify(
process.env.VITE_SUPABASE_URL,
),
- "import.meta.env.VITE_SUPABASE_ANON_KEY": JSON.stringify(
- process.env.VITE_SUPABASE_ANON_KEY,
+ "import.meta.env.VITE_SB_PUBLISHABLE_KEY": JSON.stringify(
+ process.env.VITE_SB_PUBLISHABLE_KEY,
),
"import.meta.env.VITE_INBOUND_EMAIL": JSON.stringify(
process.env.VITE_INBOUND_EMAIL,
diff --git a/vite.demo.config.ts b/vite.demo.config.ts
index 09574e30..1be2da60 100644
--- a/vite.demo.config.ts
+++ b/vite.demo.config.ts
@@ -28,8 +28,8 @@ export default defineConfig({
"import.meta.env.VITE_SUPABASE_URL": JSON.stringify(
process.env.VITE_SUPABASE_URL ?? "https://demo.example.org",
),
- "import.meta.env.VITE_SUPABASE_ANON_KEY": JSON.stringify(
- process.env.VITE_SUPABASE_ANON_KEY ?? "https://demo.example.org",
+ "import.meta.env.VITE_SB_PUBLISHABLE_KEY": JSON.stringify(
+ process.env.VITE_SB_PUBLISHABLE_KEY ?? "https://demo.example.org",
),
},
base: "./",