Skip to content

Commit 76e053b

Browse files
authored
✨ Add password reset functionality (fastapi#624)
1 parent d03d5af commit 76e053b

File tree

4 files changed

+88
-20
lines changed

4 files changed

+88
-20
lines changed

src/backend/app/utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def send_test_email(email_to: str) -> None:
4343
email_to=email_to,
4444
subject_template=subject,
4545
html_template=template_str,
46-
current_environment={"project_name": settings.PROJECT_NAME, "email": email_to},
46+
environment={"project_name": settings.PROJECT_NAME, "email": email_to},
4747
)
4848

4949

@@ -58,7 +58,7 @@ def send_reset_password_email(email_to: str, email: str, token: str) -> None:
5858
email_to=email_to,
5959
subject_template=subject,
6060
html_template=template_str,
61-
current_environment={
61+
environment={
6262
"project_name": settings.PROJECT_NAME,
6363
"username": email,
6464
"email": email_to,
@@ -78,7 +78,7 @@ def send_new_account_email(email_to: str, username: str, password: str) -> None:
7878
email_to=email_to,
7979
subject_template=subject,
8080
html_template=template_str,
81-
current_environment={
81+
environment={
8282
"project_name": settings.PROJECT_NAME,
8383
"username": username,
8484
"password": password,
@@ -104,6 +104,6 @@ def generate_password_reset_token(email: str) -> str:
104104
def verify_password_reset_token(token: str) -> str | None:
105105
try:
106106
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
107-
return decoded_token["email"]
107+
return decoded_token["sub"]
108108
except jwt.JWTError:
109109
return None

src/new-frontend/src/pages/RecoverPassword.tsx

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React from "react";
22

3-
import { Button, Container, FormControl, Heading, Input, Text } from "@chakra-ui/react";
3+
import { Button, Container, FormControl, FormErrorMessage, Heading, Input, Text } from "@chakra-ui/react";
44
import { SubmitHandler, useForm } from "react-hook-form";
55

66
import { LoginService } from "../client";
@@ -11,14 +11,13 @@ interface FormData {
1111
}
1212

1313
const RecoverPassword: React.FC = () => {
14-
const { register, handleSubmit } = useForm<FormData>();
14+
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormData>();
1515
const showToast = useCustomToast();
1616

1717
const onSubmit: SubmitHandler<FormData> = async (data) => {
18-
const response = await LoginService.recoverPassword({
18+
await LoginService.recoverPassword({
1919
email: data.email,
2020
});
21-
console.log(response)
2221

2322
showToast("Email sent.", "We sent an email with a link to get back into your account.", "success");
2423
};
@@ -37,19 +36,14 @@ const RecoverPassword: React.FC = () => {
3736
<Heading size="xl" color="ui.main" textAlign="center" mb={2}>
3837
Password Recovery
3938
</Heading>
40-
<FormControl id="username">
41-
<Text align="center">
42-
A password recovery email will be sent to the registered account.
43-
</Text>
44-
<Input
45-
{...register("email")}
46-
47-
mt={4}
48-
placeholder="Enter your email"
49-
type="text"
50-
/>
39+
<Text align="center">
40+
A password recovery email will be sent to the registered account.
41+
</Text>
42+
<FormControl isInvalid={!!errors.email}>
43+
<Input id='email' {...register('email', { required: 'Email is required', pattern: { value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, message: 'Invalid email address' } })} placeholder='Email' type='email' />
44+
{errors.email && <FormErrorMessage>{errors.email.message}</FormErrorMessage>}
5145
</FormControl>
52-
<Button bg="ui.main" color="white" _hover={{ opacity: 0.8 }} type="submit">
46+
<Button bg="ui.main" color="white" _hover={{ opacity: 0.8 }} type="submit" isLoading={isSubmitting}>
5347
Continue
5448
</Button>
5549
</Container>
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import React from "react";
2+
3+
import { Button, Container, FormControl, FormErrorMessage, FormLabel, Heading, Input, Text } from "@chakra-ui/react";
4+
import { SubmitHandler, useForm } from "react-hook-form";
5+
6+
import { LoginService, NewPassword } from "../client";
7+
import useCustomToast from "../hooks/useCustomToast";
8+
9+
interface NewPasswordForm extends NewPassword {
10+
confirm_password: string;
11+
}
12+
13+
const ResetPassword: React.FC = () => {
14+
const { register, handleSubmit, getValues, formState: { errors } } = useForm<NewPasswordForm>({
15+
mode: 'onBlur',
16+
criteriaMode: 'all',
17+
defaultValues: {
18+
new_password: '',
19+
}
20+
});
21+
const showToast = useCustomToast();
22+
23+
const onSubmit: SubmitHandler<NewPasswordForm> = async (data) => {
24+
try {
25+
const token = new URLSearchParams(window.location.search).get('token');
26+
await LoginService.resetPassword({
27+
requestBody: { new_password: data.new_password, token: token! }
28+
});
29+
showToast("Password reset.", "Your password has been reset successfully.", "success");
30+
} catch (error) {
31+
showToast("Error", "An error occurred while resetting your password.", "error");
32+
}
33+
};
34+
35+
return (
36+
<Container
37+
as="form"
38+
onSubmit={handleSubmit(onSubmit)}
39+
h="100vh"
40+
maxW="sm"
41+
alignItems="stretch"
42+
justifyContent="center"
43+
gap={4}
44+
centerContent
45+
>
46+
<Heading size="xl" color="ui.main" textAlign="center" mb={2}>
47+
Reset Password
48+
</Heading>
49+
<Text textAlign="center">
50+
Please enter your new password and confirm it to reset your password.
51+
</Text>
52+
<FormControl mt={4} isInvalid={!!errors.new_password}>
53+
<FormLabel htmlFor='password'>Set Password</FormLabel>
54+
<Input id='password' {...register('new_password', { required: 'Password is required', minLength: { value: 8, message: 'Password must be at least 8 characters' } })} placeholder='Password' type='password' />
55+
{errors.new_password && <FormErrorMessage>{errors.new_password.message}</FormErrorMessage>}
56+
</FormControl>
57+
<FormControl mt={4} isInvalid={!!errors.confirm_password}>
58+
<FormLabel htmlFor='confirm_password'>Confirm Password</FormLabel>
59+
<Input id='confirm_password' {...register('confirm_password', {
60+
required: 'Please confirm your password',
61+
validate: value => value === getValues().new_password || 'The passwords do not match'
62+
})} placeholder='Password' type='password' />
63+
{errors.confirm_password && <FormErrorMessage>{errors.confirm_password.message}</FormErrorMessage>}
64+
</FormControl>
65+
<Button bg="ui.main" color="white" _hover={{ opacity: 0.8 }} type="submit">
66+
Reset Password
67+
</Button>
68+
</Container>
69+
);
70+
};
71+
72+
export default ResetPassword;

src/new-frontend/src/routes/public_route.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import ErrorPage from '../pages/ErrorPage';
22
import Login from '../pages/Login';
33
import RecoverPassword from '../pages/RecoverPassword';
4+
import ResetPassword from '../pages/ResetPassword';
45

56
export default function publicRoutes() {
67
return [
78
{ path: '/login', element: <Login />, errorElement: <ErrorPage /> },
89
{ path: 'recover-password', element: <RecoverPassword />, errorElement: <ErrorPage /> },
10+
{ path: 'reset-password', element: <ResetPassword />, errorElement: <ErrorPage /> },
911
// TODO: complete this
1012
// { path: '*', element: <Navigate to='/login' replace /> }
1113
];

0 commit comments

Comments
 (0)