A full-featured CRM built with React, shadcn/ui, and Supabase.
Feat(auth): For reseting user password, send reset email
Anthony Rimetb600a3e152b5
diff --git a/src/providers/fakerest/dataProvider.ts b/src/providers/fakerest/dataProvider.tsindex e78b252d..d810417d 100644--- a/src/providers/fakerest/dataProvider.ts+++ b/src/providers/fakerest/dataProvider.ts@@ -15,7 +15,6 @@ import {SalesFormData,SignUpData,Task,- UpdatePasswordData,} from '../../types';import { getActivityLog } from '../commons/activity';import { getCompanyAvatar } from '../commons/getCompanyAvatar';@@ -202,10 +201,7 @@ const dataProviderWithCustomMethod: CrmDataProvider = {}return true;},- updatePassword: async (- id: Identifier,- data: UpdatePasswordData- ): Promise<UpdatePasswordData> => {+ updatePassword: async (id: Identifier): Promise<true> => {const currentUser = await authProvider.getIdentity?.();if (!currentUser) {throw new Error('User not found');@@ -221,19 +217,15 @@ const dataProviderWithCustomMethod: CrmDataProvider = {throw new Error('User not found');}- if (previousData.password !== data.currentPassword) {- throw new Error('Current password is incorrect');- }-await dataProvider.update('sales', {id,data: {- password: data.newPassword,+ password: 'demo_newPassword',},previousData,});- return data;+ return true;},};diff --git a/src/providers/supabase/dataProvider.ts b/src/providers/supabase/dataProvider.tsindex 33c3eb06..fa0e1c0e 100644--- a/src/providers/supabase/dataProvider.ts+++ b/src/providers/supabase/dataProvider.ts@@ -17,7 +17,6 @@ import {Sale,SalesFormData,SignUpData,- UpdatePasswordData,} from '../../types';import { getActivityLog } from '../commons/activity';import { getCompanyAvatar } from '../commons/getCompanyAvatar';@@ -171,16 +170,12 @@ const dataProviderWithCustomMethods = {return data;},- async updatePassword(id: Identifier, data: UpdatePasswordData) {- const { currentPassword, newPassword } = data;-+ async updatePassword(id: Identifier) {const { data: passwordUpdated, error } =- await supabase.functions.invoke<Sale>('updatePassword', {+ await supabase.functions.invoke<boolean>('updatePassword', {method: 'PATCH',body: {sales_id: id,- currentPassword,- newPassword,},});@@ -189,7 +184,7 @@ const dataProviderWithCustomMethods = {throw new Error('Failed to update password');}- return data;+ return passwordUpdated;},async unarchiveDeal(deal: Deal) {// get all deals where stage is the same as the deal to unarchivediff --git a/src/settings/SettingsPage.tsx b/src/settings/SettingsPage.tsxindex 1f31b7ce..79c62fff 100644--- a/src/settings/SettingsPage.tsx+++ b/src/settings/SettingsPage.tsx@@ -9,7 +9,6 @@ import {Stack,Typography,} from '@mui/material';-import { useMutation } from '@tanstack/react-query';import { useState } from 'react';import {Form,@@ -26,7 +25,7 @@ import { useFormState } from 'react-hook-form';import ImageEditorField from '../misc/ImageEditorField';import { CrmDataProvider } from '../providers/types';import { SalesFormData } from '../types';-import { UpdatePassword } from './UpdatePassword';+import { useMutation } from '@tanstack/react-query';export const SettingsPage = () => {const [isEditMode, setEditMode] = useState(false);@@ -87,12 +86,32 @@ const SettingsForm = ({const notify = useNotify();const { identity, refetch } = useGetIdentity();const { isDirty } = useFormState();- const [openPasswordChange, setOpenPasswordChange] = useState(false);+ const dataProvider = useDataProvider<CrmDataProvider>();++ const { mutate } = useMutation({+ mutationKey: ['updatePassword'],+ mutationFn: async () => {+ if (!identity) {+ throw new Error('Record not found');+ }+ return dataProvider.updatePassword(identity.id);+ },+ onSuccess: () => {+ notify(+ 'An reset password email has been sent to your email address'+ );+ },+ onError: e => {+ notify(`${e}`, {+ type: 'error',+ });+ },+ });if (!identity) return null;const handleClickOpenPasswordChange = () => {- setOpenPasswordChange(true);+ mutate();};const handleAvatarUpdate = async (values: any) => {@@ -145,10 +164,6 @@ const SettingsForm = ({>Change password</Button>- <UpdatePassword- open={openPasswordChange}- setOpen={setOpenPasswordChange}- /></>)}</CardContent>diff --git a/src/settings/UpdatePassword.tsx b/src/settings/UpdatePassword.tsxdeleted file mode 100644index 06b2fea3..00000000--- a/src/settings/UpdatePassword.tsx+++ /dev/null@@ -1,165 +0,0 @@-import {- Button,- Dialog,- DialogActions,- DialogContent,- DialogTitle,- Stack,- TextField,-} from '@mui/material';-import { useMutation } from '@tanstack/react-query';-import {- Toolbar,- useDataProvider,- useGetIdentity,- useNotify,-} from 'react-admin';-import { useForm } from 'react-hook-form';-import { DialogCloseButton } from '../misc/DialogCloseButton';-import { CrmDataProvider } from '../providers/types';-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- text: 'Password must be at least 8 characters long and contain at least one letter and one number.',-};--export const UpdatePassword = ({- open,- setOpen,-}: {- open: boolean;- setOpen: (value: boolean) => void;-}) => {- const {- register,- handleSubmit,- watch,- formState: { errors, isValid },- reset,- } = useForm({- mode: 'onChange',- });- const newPassword = watch('newPassword');- const { identity } = useGetIdentity();- const notify = useNotify();- const dataProvider = useDataProvider<CrmDataProvider>();-- 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) => {- mutate(data);- };-- const handleClose = () => {- setOpen(false);- };-- return (- <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>- <DialogCloseButton onClose={handleClose} />- <DialogTitle>Change Password</DialogTitle>- <form onSubmit={handleSubmit(onSubmit)}>- <DialogContent>- <Stack gap={1}>- <TextField- {...register('currentPassword', {- required: 'Current password is required',- })}- required- autoFocus- margin="dense"- label="Current Password"- type="password"- fullWidth- error={!!errors.currentPassword}- helperText={- errors.currentPassword- ? 'Current password is required'- : ''- }- />- <TextField- {...register('newPassword', {- required: 'New password is required',- pattern: {- value: PASSWORD_POLICY.regex,- message: PASSWORD_POLICY.text,- },- })}- margin="dense"- label="New Password"- type="password"- required- fullWidth- error={!!errors.newPassword}- helperText={- errors.newPassword ? PASSWORD_POLICY.text : ''- }- />- <TextField- {...register('confirmNewPassword', {- required: 'Please confirm your new password',- validate: value =>- value === newPassword ||- 'Passwords do not match',- })}- margin="dense"- label="Confirm New Password"- type="password"- required- fullWidth- error={!!errors.confirmNewPassword}- helperText={- errors.confirmNewPassword- ? 'Passwords do not match'- : ''- }- />- </Stack>- </DialogContent>- <DialogActions- sx={{- justifyContent: 'flex-start',- p: 0,- }}- >- <Toolbar- sx={{- width: '100%',- }}- >- <Button- type="submit"- color="primary"- variant="contained"- disabled={!isValid}- >- Update- </Button>- </Toolbar>- </DialogActions>- </form>- </Dialog>- );-};diff --git a/src/types.ts b/src/types.tsindex b2db784f..5bf968b0 100644--- a/src/types.ts+++ b/src/types.ts@@ -24,11 +24,6 @@ export type SalesFormData = {disabled: boolean;};-export type UpdatePasswordData = {- currentPassword: string;- newPassword: string;-};-export type Sale = {first_name: string;last_name: string;diff --git a/supabase/functions/updatePassword/index.ts b/supabase/functions/updatePassword/index.tsindex fca35c76..9c15aae0 100644--- a/supabase/functions/updatePassword/index.ts+++ b/supabase/functions/updatePassword/index.ts@@ -3,24 +3,12 @@ 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,- });+async function updatePassword(user: any) {+ const { data, error } = await supabaseAdmin.auth.resetPasswordForEmail(+ user.email+ );- if (!data || errorUpdate) {+ if (!data || error) {return createErrorResponse(500, 'Internal Server Error');}@@ -55,7 +43,7 @@ Deno.serve(async (req: Request) => {}if (req.method === 'PATCH') {- return updatePassword(req, data.user);+ return updatePassword(data.user);}return createErrorResponse(405, 'Method Not Allowed');