Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Require old password on password change #210

Merged
merged 2 commits into from
Nov 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions src/components/Profile/PasswordChangeForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useMutation} from '@tanstack/react-query'
import axios from 'axios'
import axios, {AxiosError} from 'axios'
import {FC} from 'react'
import {SubmitHandler, useForm} from 'react-hook-form'

Expand All @@ -11,11 +11,13 @@ import {Dialog} from '../Dialog/Dialog'
import {FormInput} from '../FormItems/FormInput/FormInput'

type PasswordChangeDialogValues = {
old_password: string
new_password1: string
new_password2: string
}

const defaultValues: PasswordChangeDialogValues = {
old_password: '',
new_password1: '',
new_password2: '',
}
Expand All @@ -25,20 +27,33 @@ interface PasswordChangeDialogProps {
close: () => void
}

interface ChangePasswordErrorResponseData {
old_password?: string[]
}

export const PasswordChangeDialog: FC<PasswordChangeDialogProps> = ({open, close}) => {
const {handleSubmit, reset, control, getValues} = useForm<PasswordChangeDialogValues>({defaultValues})
const {handleSubmit, reset, control, getValues, setError} = useForm<PasswordChangeDialogValues>({defaultValues})

const onSuccess = () => {
alert('Zmena hesla prebehla úspešne.')
reset()
close()
}

const onError = (error: AxiosError<ChangePasswordErrorResponseData>) => {
if (error.response?.status === 400) {
if (error.response.data.old_password) {
setError('old_password', {type: 'manual', message: `* ${error.response.data.old_password[0]}`}) // TODO: We might want to simplify/reword this message
}
}
}

const {mutate: submitFormData} = useMutation({
mutationFn: (data: PasswordChangeDialogValues) => {
return axios.post<IGeneralPostResponse>(`/api/user/password/change`, data)
},
onSuccess: onSuccess,
onError: onError,
})

const onSubmit: SubmitHandler<PasswordChangeDialogValues> = async (data) => {
Expand All @@ -54,6 +69,13 @@ export const PasswordChangeDialog: FC<PasswordChangeDialogProps> = ({open, close
title="Zmena hesla"
contentText={
<form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
<FormInput
control={control}
name="old_password"
label="aktuálne heslo"
type="password"
rules={requiredRule}
/>
<FormInput
control={control}
name="new_password1"
Expand Down
Loading