Skip to content

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

Feat(auth): Update supabase password via CRM UI

Anthony Rimet74bf059348fc
diff --git a/makefile b/makefile
index 632ba567..dfb6a674 100644
--- a/makefile
+++ b/makefile
@@ -6,6 +6,9 @@ help:
install: package.json ## install dependencies
npm install;
+start-supabase-functions: ## start the supabase Functions watcher
+ npx supabase functions serve
+
start-supabase: ## start supabase locally
npx supabase start
diff --git a/src/dataProvider.ts b/src/dataProvider.ts
index 14164617..dc6dcb70 100644
--- a/src/dataProvider.ts
+++ b/src/dataProvider.ts
@@ -22,6 +22,7 @@ import {
Sale,
SalesFormData,
SignUpData,
+ UpdatePasswordData,
} from './types';
if (import.meta.env.VITE_SUPABASE_URL === undefined) {
@@ -167,6 +168,26 @@ const dataProviderWithCustomMethods = {
return data;
},
+ async updatePassword(id: Identifier, data: UpdatePasswordData) {
+ const { currentPassword, newPassword } = data;
+
+ const { data: passwordUpdated, error } =
+ await supabase.functions.invoke<Sale>('updatePassword', {
+ method: 'PATCH',
+ body: {
+ sales_id: id,
+ currentPassword,
+ newPassword,
+ },
+ });
+
+ if (!passwordUpdated || error) {
+ console.error('passwordUpdate.error', error);
+ throw new Error('Failed to update password');
+ }
+
+ return data;
+ },
async unarchiveDeal(deal: Deal) {
// get all deals where stage is the same as the deal to unarchive
const { data: deals } = await baseDataProvider.getList<Deal>('deals', {
diff --git a/src/settings/UpdatePassword.tsx b/src/settings/UpdatePassword.tsx
index 8d883826..f3f97b2b 100644
--- a/src/settings/UpdatePassword.tsx
+++ b/src/settings/UpdatePassword.tsx
@@ -7,9 +7,17 @@ import {
Stack,
TextField,
} from '@mui/material';
-import { Toolbar, useGetIdentity, useNotify, useUpdate } from 'react-admin';
+import {
+ Toolbar,
+ useDataProvider,
+ useGetIdentity,
+ useNotify,
+} from 'react-admin';
import { useForm } from 'react-hook-form';
import { DialogCloseButton } from '../misc/DialogCloseButton';
+import { useMutation } from '@tanstack/react-query';
+import { CustomDataProvider } from '../dataProvider';
+import { UpdatePasswordData } from '../types';
const PASSWORD_POLICY = {
regex: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, // Example policy: Minimum 8 characters, at least one letter and one number
@@ -23,7 +31,6 @@ export const UpdatePassword = ({
open: boolean;
setOpen: (value: boolean) => void;
}) => {
- const [update] = useUpdate();
const {
register,
handleSubmit,
@@ -36,33 +43,32 @@ export const UpdatePassword = ({
const newPassword = watch('newPassword');
const { identity } = useGetIdentity();
const notify = useNotify();
+ const dataProvider = useDataProvider<CustomDataProvider>();
+
+ const { mutate } = useMutation({
+ mutationKey: ['updatePassword'],
+ mutationFn: async (data: UpdatePasswordData) => {
+ if (!identity) {
+ throw new Error('Record not found');
+ }
+ return dataProvider.updatePassword(identity.id, data);
+ },
+ onSuccess: () => {
+ notify('Your password has been updated');
+ setOpen(false);
+ reset();
+ },
+ onError: e => {
+ notify(`${e}`, {
+ type: 'error',
+ });
+ },
+ });
if (!identity) return null;
const onSubmit = async (data: any) => {
- await update(
- 'sales',
- {
- id: identity.id,
- data: {
- password: data.newPassword,
- },
- previousData: identity,
- },
- {
- onSuccess: _ => {
- notify('Your password has been updated');
- setOpen(false);
- reset();
- },
- onError: _ => {
- notify('An error occurred. Please try again', {
- type: 'error',
- });
- },
- }
- );
- setOpen(false);
+ mutate(data);
};
const handleClose = () => {
diff --git a/src/types.ts b/src/types.ts
index 3527780a..25a67b61 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -24,6 +24,11 @@ export type SalesFormData = {
disabled: boolean;
};
+export type UpdatePasswordData = {
+ currentPassword: string;
+ newPassword: string;
+};
+
export interface Sale extends RaRecord {
first_name: string;
last_name: string;
diff --git a/supabase/functions/_shared/supabaseAdmin.ts b/supabase/functions/_shared/supabaseAdmin.ts
new file mode 100644
index 00000000..fad89bbe
--- /dev/null
+++ b/supabase/functions/_shared/supabaseAdmin.ts
@@ -0,0 +1,12 @@
+import { createClient, SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+
+export const supabaseAdmin: SupabaseClient = createClient(
+ Deno.env.get('SUPABASE_URL') ?? '',
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
+ {
+ auth: {
+ autoRefreshToken: false,
+ persistSession: false,
+ },
+ }
+);
\ No newline at end of file
diff --git a/supabase/functions/_shared/utils.ts b/supabase/functions/_shared/utils.ts
new file mode 100644
index 00000000..dc7e1a42
--- /dev/null
+++ b/supabase/functions/_shared/utils.ts
@@ -0,0 +1,13 @@
+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',
+};
+
+export function createErrorResponse(status: number, message: string) {
+ return new Response(JSON.stringify({ status, message }), {
+ headers: { 'Content-Type': 'application/json', ...corsHeaders },
+ status,
+ });
+}
diff --git a/supabase/functions/updatePassword/index.ts b/supabase/functions/updatePassword/index.ts
new file mode 100644
index 00000000..fca35c76
--- /dev/null
+++ b/supabase/functions/updatePassword/index.ts
@@ -0,0 +1,62 @@
+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(req: Request, user: any) {
+ const { currentPassword, newPassword } = await req.json();
+
+ const { _, error: errorLogin } =
+ await supabaseAdmin.auth.signInWithPassword({
+ email: user.email,
+ password: currentPassword,
+ });
+
+ if (errorLogin) {
+ return createErrorResponse(400, 'Invalid current password');
+ }
+
+ const { data, error: errorUpdate } = await supabaseAdmin.auth.updateUser({
+ password: newPassword,
+ });
+
+ if (!data || errorUpdate) {
+ 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(req, data.user);
+ }
+
+ return createErrorResponse(405, 'Method Not Allowed');
+});
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 958370ac..4f7ce8cb 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -1,33 +1,10 @@
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
import { createClient } from 'jsr:@supabase/supabase-js@2';
-
-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',
-};
-
-const supabaseServiceClient = createClient(
- Deno.env.get('SUPABASE_URL') ?? '',
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
- {
- auth: {
- autoRefreshToken: false,
- persistSession: false,
- },
- }
-);
-
-function createErrorResponse(status: number, message: string) {
- return new Response(JSON.stringify({ status, message }), {
- headers: { 'Content-Type': 'application/json', ...corsHeaders },
- status,
- });
-}
+import { supabaseAdmin } from '../_shared/supabaseAdmin.ts';
+import { corsHeaders, createErrorResponse } from '../_shared/utils.ts';
async function updateSaleDisabled(user_id: string, disabled: boolean) {
- return await supabaseServiceClient
+ return await supabaseAdmin
.from('sales')
.update({ disabled: disabled ?? false })
.eq('user_id', user_id);
@@ -37,7 +14,7 @@ async function updateSaleAdministrator(
user_id: string,
administrator: boolean
) {
- const { data: sales, error: salesError } = await supabaseServiceClient
+ const { data: sales, error: salesError } = await supabaseAdmin
.from('sales')
.update({ administrator })
.eq('user_id', user_id)
@@ -55,7 +32,7 @@ async function inviteUser(req: Request) {
await req.json();
const { data, error: userError } =
- await supabaseServiceClient.auth.admin.createUser({
+ await supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true,
@@ -88,7 +65,7 @@ async function inviteUser(req: Request) {
async function patchUser(req: Request) {
const { sales_id, email, first_name, last_name, administrator, disabled } =
await req.json();
- const { data: sale } = await supabaseServiceClient
+ const { data: sale } = await supabaseAdmin
.from('sales')
.select('*')
.eq('id', sales_id)
@@ -99,7 +76,7 @@ async function patchUser(req: Request) {
}
const { data, error: userError } =
- await supabaseServiceClient.auth.admin.updateUserById(sale.user_id, {
+ await supabaseAdmin.auth.admin.updateUserById(sale.user_id, {
email,
ban_duration: disabled ? '87600h' : 'none',
user_metadata: { first_name, last_name },