Skip to content

Commit

Permalink
fix: Show correct login error (#369)
Browse files Browse the repository at this point in the history
* final

* fix

* commit

* final

* final edit

* final edit

* edit
  • Loading branch information
Nimasheth authored Jul 12, 2023
1 parent cc4c20e commit 5805755
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 42 deletions.
11 changes: 6 additions & 5 deletions frontend/src/APIClients/AuthAPIClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ const login = async (
localStorage.setItem(AUTHENTICATED_USER_KEY, JSON.stringify(user));
}
} catch (e: unknown) {
// eslint-disable-next-line no-alert
window.alert("Failed to login");
throw new Error("Failed to login");
}
return user;
};
Expand All @@ -56,7 +55,6 @@ type RegisterFunction = (
Record<string, unknown>
>
>;

const registerTeacher = async (
firstName: string,
lastName: string,
Expand Down Expand Up @@ -85,8 +83,11 @@ const registerTeacher = async (
localStorage.setItem(AUTHENTICATED_USER_KEY, JSON.stringify(user));
}
} catch (e: unknown) {
// eslint-disable-next-line no-alert
window.alert("Failed to sign up");
if (e instanceof Error && e.message.includes("duplicate key")) {
throw new Error("Email already exists");
} else {
throw new Error("Failed to sign up");
}
}
return user;
};
Expand Down
44 changes: 30 additions & 14 deletions frontend/src/components/auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const Login = (): React.ReactElement => {

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [invalidFormError, setInvalidFormError] = useState(false);
const [loginError, setLoginError] = useState(false);

const [forgotPassword, setForgotPassword] = useState(false);
Expand All @@ -36,21 +37,28 @@ const Login = (): React.ReactElement => {
}>(LOGIN);

const onLogInClick = async () => {
setInvalidFormError(false);
setLoginError(false);

if (!(email && password)) {
setLoginError(true);
setInvalidFormError(true);
return;
}
const user: VerifiableUser | null = await authAPIClient.login(
email,
password,
login,
);

if (user?.emailVerified === false) {
setUnverifiedUser(true);
return;

try {
const user: VerifiableUser | null = await authAPIClient.login(
email,
password,
login,
);
if (user?.emailVerified === false) {
setUnverifiedUser(true);
return;
}
setAuthenticatedUser(user);
} catch (error) {
setLoginError(true);
}
setAuthenticatedUser(user);
};

if (authenticatedUser) {
Expand All @@ -62,7 +70,7 @@ const Login = (): React.ReactElement => {
const image = isAdmin ? ADMIN_SIGNUP_IMAGE : TEACHER_SIGNUP_IMAGE;
const form = (
<>
<FormControl isInvalid={loginError && !email} isRequired>
<FormControl isInvalid={invalidFormError && !email} isRequired>
<FormLabel color="grey.400">Email Address</FormLabel>
<Input
onChange={(e) => setEmail(e.target.value)}
Expand All @@ -72,7 +80,7 @@ const Login = (): React.ReactElement => {
/>
</FormControl>

<FormControl isInvalid={loginError && !password} isRequired>
<FormControl isInvalid={invalidFormError && !password} isRequired>
<FormLabel color="grey.400">Password</FormLabel>
<Input
onChange={(e) => setPassword(e.target.value)}
Expand Down Expand Up @@ -110,7 +118,15 @@ const Login = (): React.ReactElement => {
<BackButton size="md" text="Back to Home" />
</>
);
const error = loginError ? "Please ensure fields are filled" : "";

let error = "";
if (invalidFormError) {
error = "Please ensure fields are filled";
}

if (loginError) {
error = "Failed to login";
}

if (forgotPassword) return <ForgotPassword isAdmin={isAdmin} />;
if (unverifiedUser) return <UnverifiedUsers email={email} />;
Expand Down
8 changes: 7 additions & 1 deletion frontend/src/components/auth/teacher-signup/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext } from "react";
import React, { useContext, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useMutation } from "@apollo/client";

Expand Down Expand Up @@ -61,13 +61,18 @@ const TeacherSignup = (): React.ReactElement => {
mode: "onChange",
});
const [page, setPage] = React.useState(1);
const [error, setError] = useState("");
const [registerTeacher] = useMutation<{ register: AuthenticatedUser }>(
REGISTER_TEACHER,
{
onCompleted(data: { register: AuthenticatedUser }) {
setError("");
setAuthenticatedUser(data.register);
setPage(5);
},
onError: async () => {
setError("Failed to Sign Up");
},
},
);

Expand All @@ -91,6 +96,7 @@ const TeacherSignup = (): React.ReactElement => {
{renderPageComponent(page, {
setPage,
handleSubmitCallback,
error,
})}
</FormProvider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,16 @@ const TeacherSignupOne = ({
const [firstNameError, setFirstNameError] = React.useState(false);
const [lastNameError, setLastNameError] = React.useState(false);
const [emailError, setEmailError] = React.useState(false);
const [acceptEmailError, setAcceptEmailError] = React.useState(false);
const [gradesError, setGradesError] = React.useState(false);
const history = useHistory();

const { value: gradesValues, setValue: setGradesValue } = useCheckboxGroup({
defaultValue: watch("grades") || [],
});

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const handleChange = (
event: React.ChangeEvent<HTMLInputElement>,
field: TeacherInput,
Expand All @@ -57,6 +60,7 @@ const TeacherSignupOne = ({
break;
case "email":
setEmailError(false);
setAcceptEmailError(false);
break;
case "grades":
setGradesError(false);
Expand All @@ -72,32 +76,53 @@ const TeacherSignupOne = ({
setGradesError(false);
};

const validateFields = (): boolean => {
const validateFields = async (): Promise<boolean> => {
let isValid = true;

if (!watch("firstName") || !!errors.firstName) {
setFirstNameError(true);
return false;
isValid = false;
} else {
setFirstNameError(false);
}

if (!watch("lastName") || !!errors.lastName) {
setLastNameError(true);
return false;
isValid = false;
} else {
setLastNameError(false);
}

if (!watch("email") || !!errors.email) {
const emailValue = watch("email");
if (!emailValue || !!errors.email) {
setEmailError(true);
return false;
isValid = false;
} else {
setEmailError(false);
}

if (!emailRegex.test(emailValue)) {
setAcceptEmailError(true);
isValid = false;
} else {
setAcceptEmailError(false);
}

if (!watch("grades.0") || !!errors.grades) {
setGradesError(true);
return false;
isValid = false;
} else {
setGradesError(false);
}

return true;
return isValid;
};

const onContinueClick = () => {
if (validateFields()) setPage(2);
const onContinueClick = async () => {
const isValid = await validateFields();
if (isValid) {
setPage(2);
}
};

const title = "Teacher Sign Up";
Expand Down Expand Up @@ -125,7 +150,7 @@ const TeacherSignupOne = ({
</FormControl>
</Stack>

<FormControl isInvalid={emailError} isRequired>
<FormControl isInvalid={acceptEmailError || emailError} isRequired>
<FormLabel color="grey.400">Email Address</FormLabel>
<Input
onChange={(e) => handleChange(e, "email")}
Expand Down Expand Up @@ -155,10 +180,16 @@ const TeacherSignupOne = ({
/>
</>
);
const error =
firstNameError || lastNameError || emailError || gradesError
? "Please ensure fields are filled"
: "";

let error = "";

if (acceptEmailError) {
error = "Invalid email";
}

if (firstNameError || lastNameError || emailError || gradesError) {
error = "Please ensure fields are filled";
}

return (
<AuthWrapper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import PasswordForm from "../../password/PasswordForm";
const TeacherSignupFour = ({
setPage,
handleSubmitCallback,
error,
}: TeacherSignupProps): React.ReactElement => {
const { setValue, watch } = useFormContext<TeacherSignupForm>();
const title = "Teacher Sign Up";
Expand All @@ -33,7 +34,13 @@ const TeacherSignupFour = ({
);

return (
<AuthWrapper form={form} image={image} subtitle={subtitle} title={title} />
<AuthWrapper
error={error}
form={form}
image={image}
subtitle={subtitle}
title={title}
/>
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,32 +57,33 @@ const TeacherSignupThree = ({
};

const validateFields = (): boolean => {
let isValid = true;

if (!watch("school.name") || !!errors.school?.name) {
setSchoolNameError(true);
return false;
isValid = false;
}

if (!watch("school.country") || !!errors.school?.country) {
setCountryError(true);
return false;
isValid = false;
}

if (!watch("school.city") || !!errors.school?.city) {
setCityError(true);
return false;
isValid = false;
}

if (!watch("school.district") || !!errors.school?.district) {
setDistrictError(true);
return false;
isValid = false;
}

if (!watch("school.address") || !!errors.school?.address) {
setAddressError(true);
return false;
isValid = false;
}

return true;
return isValid;
};

const onContinueClick = () => {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/types/TeacherSignupTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,5 @@ export interface SchoolMetadata {
export interface TeacherSignupProps {
setPage: React.Dispatch<React.SetStateAction<number>>;
handleSubmitCallback: (e: React.MouseEvent<HTMLButtonElement>) => void;
error: string;
}

0 comments on commit 5805755

Please sign in to comment.