A full-featured CRM built with React, shadcn/ui, and Supabase.
Setup new supabase JWT authentication, rename functions in snake_case, refactor authenticated user fetching.
Matthieu Hochlander9844ac900acc
diff --git a/.env.development b/.env.developmentindex f0c6af4c..5edd8d32 100644--- a/.env.development+++ b/.env.development@@ -1,8 +1,6 @@SKIP_PREFLIGHT_CHECK=trueVITE_SUPABASE_URL=http://127.0.0.1:54321-VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0+VITE_SUPABASE_ANON_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaHVITE_IS_DEMO=falseVITE_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 filediff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.tsindex 45943807..6c1ae3fd 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts@@ -173,7 +173,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,@@ -181,7 +181,7 @@ const dataProviderWithCustomMethods = {});if (!passwordUpdated || error) {- console.error("passwordUpdate.error", error);+ console.error("update_password.error", error);throw new Error("Failed to update password");}@@ -219,13 +219,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/supabase/config.toml b/supabase/config.tomlindex 79d46835..1d14c65b 100644--- a/supabase/config.toml+++ b/supabase/config.toml@@ -153,5 +153,11 @@ s3_access_key = "env(S3_ACCESS_KEY)"# Configures AWS_SECRET_ACCESS_KEY for S3 buckets3_secret_key = "env(S3_SECRET_KEY)"+[functions.merge_contacts]+verify_jwt = false[functions.postmark]-verify_jwt = false\ No newline at end of file+verify_jwt = false+[functions.update_password]+verify_jwt = false+[functions.users]+verify_jwt = falsediff --git a/supabase/functions/.env.development b/supabase/functions/.env.developmentindex 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 MacPOSTMARK_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_xSvEMPvzdiff --git a/supabase/functions/_shared/authentication.ts b/supabase/functions/_shared/authentication.tsnew file mode 100644index 00000000..b1f4ee8e--- /dev/null+++ b/supabase/functions/_shared/authentication.ts@@ -0,0 +1,94 @@+// 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";+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 Response.json(+ { msg: "Invalid authentication" },+ {+ status: 401,+ },+ );+ } catch (e) {+ return Response.json(+ { msg: e?.toString() },+ {+ status: 401,+ },+ );+ }+};++/**+ * Get the authenticated user using the authorization header.+ */+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 Response.json(+ { msg: err?.toString() },+ {+ status: 401,+ },+ );+ }+};diff --git a/supabase/functions/_shared/getUserSale.ts b/supabase/functions/_shared/getUserSale.tsnew file mode 100644index 00000000..7da2e37f--- /dev/null+++ b/supabase/functions/_shared/getUserSale.ts@@ -0,0 +1,15 @@+import { type User } from "jsr:@supabase/supabase-js";+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.tsindex 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/mergeContacts/index.ts b/supabase/functions/merge_contacts/index.tssimilarity index 74%rename from supabase/functions/mergeContacts/index.tsrename to supabase/functions/merge_contacts/index.tsindex bace4688..7099aac1 100644--- a/supabase/functions/mergeContacts/index.ts+++ b/supabase/functions/merge_contacts/index.ts@@ -1,8 +1,8 @@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 { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";type Contact = Selectable<ContactsTable>;@@ -157,59 +157,43 @@ 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");+Deno.serve(async (req: Request) =>+ AuthMiddleware(req, async (req) =>+ UserMiddleware(req, async (req, user) => {+ // Handle CORS preflight+ if (req.method === "OPTIONS") {+ return new Response(null, {+ status: 204,+ headers: corsHeaders,+ });}- 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"- }`,- );- }- }+ // 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");-});+ return createErrorResponse(405, "Method Not Allowed");+ }),+ ),+);diff --git a/supabase/functions/updatePassword/index.ts b/supabase/functions/updatePassword/index.tsdeleted file mode 100644index 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.tsnew file mode 100644index 00000000..059460f2--- /dev/null+++ b/supabase/functions/update_password/index.ts@@ -0,0 +1,42 @@+import "jsr:@supabase/functions-js/edge-runtime.d.ts";+import { corsHeaders, 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) =>+ AuthMiddleware(req, async (req) =>+ UserMiddleware(req, async (req, user) => {+ if (req.method === "OPTIONS") {+ return new Response(null, {+ status: 204,+ headers: corsHeaders,+ });+ }++ if (req.method === "PATCH") {+ return updatePassword(user);+ }++ return createErrorResponse(405, "Method Not Allowed");+ }),+ ),+);diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.tsindex a6c8c345..97611b8d 100644--- a/supabase/functions/users/index.ts+++ b/supabase/functions/users/index.ts@@ -1,7 +1,8 @@import "jsr:@supabase/functions-js/edge-runtime.d.ts";-import { createClient } from "jsr:@supabase/supabase-js@2";import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";import { corsHeaders, createErrorResponse } from "../_shared/utils.ts";+import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";+import { getUserSale } from "../_shared/getUserSale.ts";async function updateSaleDisabled(user_id: string, disabled: boolean) {return await supabaseAdmin@@ -167,40 +168,30 @@ async function patchUser(req: Request, currentUserSale: any) {}}-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");- }- const currentUserSale = await supabaseAdmin- .from("sales")- .select("*")- .eq("user_id", data.user.id)- .single();-- if (!currentUserSale?.data) {- return createErrorResponse(401, "Unauthorized");- }- if (req.method === "POST") {- return inviteUser(req, currentUserSale.data);- }-- if (req.method === "PATCH") {- return patchUser(req, currentUserSale.data);- }-- return createErrorResponse(405, "Method Not Allowed");-});+Deno.serve(async (req: Request) =>+ AuthMiddleware(req, async (req) =>+ UserMiddleware(req, async (req, user) => {+ if (req.method === "OPTIONS") {+ return new Response(null, {+ status: 204,+ headers: corsHeaders,+ });+ }++ const currentUserSale = await getUserSale(user);+ if (!currentUserSale) {+ return createErrorResponse(401, "Unauthorized");+ }++ if (req.method === "POST") {+ return inviteUser(req, currentUserSale);+ }++ if (req.method === "PATCH") {+ return patchUser(req, currentUserSale);+ }++ return createErrorResponse(405, "Method Not Allowed");+ }),+ ),+);