diff --git a/client/src/Hooks/useRegisterForm.ts b/client/src/Hooks/useRegisterForm.ts new file mode 100644 index 000000000..99337a28b --- /dev/null +++ b/client/src/Hooks/useRegisterForm.ts @@ -0,0 +1,16 @@ +import { registerSchema, type RegisterFormData } from "@/Validation/register"; + +export const useRegisterForm = () => { + const defaults: RegisterFormData = { + firstName: "", + lastName: "", + email: "", + password: "", + confirm: "", + }; + + return { + schema: registerSchema, + defaults, + }; +}; diff --git a/client/src/Pages/Auth/Register/index.jsx b/client/src/Pages/Auth/Register/index.jsx deleted file mode 100644 index 821c56427..000000000 --- a/client/src/Pages/Auth/Register/index.jsx +++ /dev/null @@ -1,330 +0,0 @@ -// Components -import Stack from "@mui/material/Stack"; -import Typography from "@mui/material/Typography"; -import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx"; -import Button from "@mui/material/Button"; -import Box from "@mui/material/Box"; -import PasswordTooltip from "../components/PasswordTooltip.jsx"; - -// Utils -import { useTheme } from "@emotion/react"; -import { useTranslation } from "react-i18next"; -import { useState, useEffect } from "react"; -import { useNavigate } from "react-router-dom"; -import { useDispatch, useSelector } from "react-redux"; -import { useParams } from "react-router-dom"; -import { networkService } from "../../../main.jsx"; -import { newOrChangedCredentials } from "../../../Validation/validation.js"; -import { register } from "../../../Features/Auth/authSlice.js"; -import AuthPageWrapper from "../components/AuthPageWrapper.jsx"; -import { createToast } from "../../../Utils/toastUtils.jsx"; -import PropTypes from "prop-types"; - -const getFeedbackStatus = (form, errors, field, criteria) => { - const fieldErrors = errors?.[field]; - const isFieldEmpty = form?.[field]?.length === 0; - const hasError = fieldErrors?.includes(criteria) || fieldErrors?.includes("empty"); - const isCorrect = !isFieldEmpty && !hasError; - - if (isCorrect) { - return "success"; - } else if (hasError) { - return "error"; - } else { - return "info"; - } -}; - -const Register = ({ superAdminExists }) => { - // Redux - const { isLoading } = useSelector((state) => state.auth); - - // Local state - const [form, setForm] = useState({ - firstName: "", - lastName: "", - email: "", - password: "", - confirm: "", - role: [], - teamId: "", - }); - - const [errors, setErrors] = useState({}); - const [feedback, setFeedback] = useState({}); - - // Hooks - const theme = useTheme(); - const { t } = useTranslation(); - const { token } = useParams(); - const navigate = useNavigate(); - const dispatch = useDispatch(); - - // Effects - useEffect(() => { - const fetchInvite = async () => { - if (token !== undefined) { - try { - const res = await networkService.verifyInvitationToken(token); - const invite = res.data.data; - const { email } = invite; - setForm((prevForm) => { - if (!prevForm.email) { - return { ...prevForm, email }; - } - return prevForm; - }); - } catch (error) { - navigate("/register", { replace: true }); - } - } - }; - fetchInvite(); - }, [form, token, navigate]); - - // Handlers - const onChange = (e) => { - let { name, value } = e.target; - if (name === "email") value = value.toLowerCase(); - const updatedForm = { ...form, [name]: value }; - - const { error } = newOrChangedCredentials.validate( - { [name]: value }, - { abortEarly: false, context: { password: form.password } } - ); - - setErrors((prev) => ({ - ...prev, - [name]: error?.details?.[0]?.message || "", - })); - - setForm(updatedForm); - }; - - const onPasswordChange = (e) => { - const { name, value } = e.target; - const updatedForm = { ...form, [name]: value }; - setForm(updatedForm); - const validateValue = { [name]: value }; - const validateOptions = { abortEarly: false, context: { password: form.password } }; - if (name === "password" && form.confirm.length > 0) { - validateValue.confirm = form.confirm; - validateOptions.context = { password: value }; - } else if (name === "confirm") { - validateValue.password = form.password; - } - const { error } = newOrChangedCredentials.validate(validateValue, validateOptions); - - const pwdErrors = error?.details.map((error) => ({ - path: error.path[0], - type: error.type, - })); - - const errorsByPath = - pwdErrors && - pwdErrors.reduce((acc, { path, type }) => { - if (!acc[path]) { - acc[path] = []; - } - acc[path].push(type); - return acc; - }, {}); - - const oldErrors = { ...errors }; - if (name === "password") { - oldErrors.password = undefined; - } else if (name === "confirm") { - oldErrors.confirm = undefined; - } - const newErrors = { ...oldErrors, ...errorsByPath }; - - setErrors(newErrors); - - const newFeedback = { - length: getFeedbackStatus(updatedForm, errorsByPath, "password", "string.min"), - special: getFeedbackStatus(updatedForm, errorsByPath, "password", "special"), - number: getFeedbackStatus(updatedForm, errorsByPath, "password", "number"), - uppercase: getFeedbackStatus(updatedForm, errorsByPath, "password", "uppercase"), - lowercase: getFeedbackStatus(updatedForm, errorsByPath, "password", "lowercase"), - confirm: getFeedbackStatus(updatedForm, errorsByPath, "confirm", "different"), - }; - - setFeedback(newFeedback); - }; - - const onSubmit = async (e) => { - e.preventDefault(); - const toSubmit = { - ...form, - role: superAdminExists ? form.role : ["superadmin"], - inviteToken: token ? token : "", - }; - - const { error } = newOrChangedCredentials.validate(toSubmit, { - abortEarly: false, - context: { password: form.password }, - }); - - if (error) { - const formErrors = {}; - for (const err of error.details) { - formErrors[err.path[0]] = err.message; - } - setErrors(formErrors); - return; - } - - delete toSubmit.confirm; - - const action = await dispatch(register({ user: toSubmit, token })); - if (action.payload.success) { - navigate("/uptime"); - createToast({ - body: t("auth.registration.toasts.success"), - }); - } else { - if (action.payload) { - createToast({ - body: action.payload.msg, - }); - } else { - createToast({ - body: t("common.toasts.unknownError"), - }); - } - } - }; - - return ( - - - - {superAdminExists - ? t("auth.registration.description.user") - : t("auth.registration.description.superAdmin")} - - - - - - (e.target.value = e.target.value.toLowerCase())} - onChange={onChange} - error={errors.email ? true : false} - helperText={errors.email ? t(errors.email) : ""} // Localization keys are in validation.js - /> - - - - - - - - - - ); -}; - -Register.propTypes = { - superAdminExists: PropTypes.bool, -}; - -export default Register; diff --git a/client/src/Pages/Auth/Register/index.tsx b/client/src/Pages/Auth/Register/index.tsx new file mode 100644 index 000000000..80cee579f --- /dev/null +++ b/client/src/Pages/Auth/Register/index.tsx @@ -0,0 +1,162 @@ +import { BaseAuthPage } from "@/Components/v2/design-elements"; +import { Button, TextField } from "@/Components/v2/inputs"; +import { useForm, Controller } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod/dist/zod.js"; +import { useRegisterForm } from "@/Hooks/useRegisterForm"; +import type { RegisterFormData } from "@/Validation/register"; +import { useTranslation } from "react-i18next"; +import { usePost } from "@/Hooks/UseApi"; +import { setAuthState } from "@/Features/Auth/authSlice"; +import { useDispatch } from "react-redux"; +import { useNavigate, useParams } from "react-router-dom"; +import type { AuthResponse } from "@/Types/User"; +import { useEffect, useRef } from "react"; + +interface RegisterPayload { + user: Omit; + token?: string; +} + +interface InviteVerifyResponse { + email: string; +} + +const RegisterPage = () => { + const { t } = useTranslation(); + const { schema, defaults } = useRegisterForm(); + const { post, loading } = usePost(); + const dispatch = useDispatch(); + const navigate = useNavigate(); + const { token } = useParams<{ token?: string }>(); + + const { post: verifyToken } = usePost<{ token: string }, InviteVerifyResponse>(); + const hasVerified = useRef(false); + + const { control, handleSubmit, setError, reset } = useForm({ + resolver: zodResolver(schema), + defaultValues: defaults, + }); + + useEffect(() => { + if (!token || hasVerified.current) return; + hasVerified.current = true; + + verifyToken("/invite/verify", { token }).then((result) => { + if (result?.success && result?.data) { + reset({ + ...defaults, + email: result.data.email ?? "", + }); + } else { + navigate("/register", { replace: true }); + } + }); + }, [token]); + + const onSubmit = async (data: RegisterFormData) => { + if (loading) return; + + const { confirm, ...userData } = data; + const payload: RegisterPayload = { user: userData }; + if (token) { + payload.token = token; + } + const result = await post("/auth/register", payload); + + if (result?.success) { + dispatch(setAuthState(result)); + navigate("/uptime"); + } else if (result?.msg) { + if (result.msg.toLowerCase().includes("email")) { + setError("email", { message: result.msg }); + } + } + }; + + return ( + + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + + + ); +}; + +export default RegisterPage; diff --git a/client/src/Pages/Auth/components/AuthHeader.jsx b/client/src/Pages/Auth/components/AuthHeader.jsx deleted file mode 100644 index 56b69ef14..000000000 --- a/client/src/Pages/Auth/components/AuthHeader.jsx +++ /dev/null @@ -1,49 +0,0 @@ -// Components -import Stack from "@mui/material/Stack"; -import Typography from "@mui/material/Typography"; -import Logo from "@/assets/icons/checkmate-icon.svg?react"; -import LanguageSelector from "@/Components/LanguageSelector.jsx"; -import ThemeSwitch from "@/Components/v1/ThemeSwitch/index.jsx"; - -// Utils -import { useTheme } from "@mui/material/styles"; -import { useTranslation } from "react-i18next"; - -const AuthHeader = ({ hideLogo = false }) => { - // Hooks - const theme = useTheme(); - const { t } = useTranslation(); - - return ( - - - {!hideLogo && ( - <> - - {t("common.appName")} - - )} - - - - - - - ); -}; - -export default AuthHeader; diff --git a/client/src/Pages/Auth/components/AuthPageWrapper.jsx b/client/src/Pages/Auth/components/AuthPageWrapper.jsx deleted file mode 100644 index a5fbe311b..000000000 --- a/client/src/Pages/Auth/components/AuthPageWrapper.jsx +++ /dev/null @@ -1,107 +0,0 @@ -import Background from "@/assets/Images/background-grid.svg?react"; -import Stack from "@mui/material/Stack"; -import Box from "@mui/material/Box"; -import Typography from "@mui/material/Typography"; -import AuthHeader from "./AuthHeader.jsx"; -import { useTheme } from "@mui/material/styles"; -import Logo from "@/assets/icons/checkmate-icon.svg?react"; -import PropTypes from "prop-types"; - -const AuthPageWrapper = ({ children, heading, welcome }) => { - const theme = useTheme(); - return ( - - - - - - - - - - - - - - - - {welcome} - - {heading} - - {children} - - - ); -}; - -export default AuthPageWrapper; - -AuthPageWrapper.propTypes = { - children: PropTypes.node, - heading: PropTypes.node, - welcome: PropTypes.node, -}; diff --git a/client/src/Routes/index.jsx b/client/src/Routes/index.jsx index acc9ad0c1..936258595 100644 --- a/client/src/Routes/index.jsx +++ b/client/src/Routes/index.jsx @@ -9,7 +9,7 @@ import NotFound from "../Pages/NotFound/index.jsx"; // Auth import AuthLogin from "../Pages/Auth/Login"; -import AuthRegister from "../Pages/Auth/Register/index.jsx"; +import AuthRegister from "@/Pages/Auth/Register"; import AuthForgotPassword from "@/Pages/Auth/Recovery"; import AuthCheckEmail from "../Pages/Auth/CheckEmail.jsx"; import AuthSetNewPassword from "../Pages/Auth/SetNewPassword.jsx"; @@ -372,13 +372,25 @@ const Routes = () => { } + element={ + <> + + + + + } /> } + element={ + <> + + + + + } /> ~`|\\/]/; + +export const registerSchema = z + .object({ + firstName: z + .string() + .min(1, "First name is required") + .max(50, "First name must be 50 characters or less") + .regex(namePattern, "First name contains invalid characters") + .transform((val) => val.trim()), + lastName: z + .string() + .min(1, "Last name is required") + .max(50, "Last name must be 50 characters or less") + .regex(namePattern, "Last name contains invalid characters") + .transform((val) => val.trim()), + email: z + .email("Please enter a valid email address") + .min(1, "Email is required") + .transform((val) => val.toLowerCase().trim()), + password: z + .string() + .min(1, "Password is required") + .min(8, "Password must be at least 8 characters") + .refine((val) => /[A-Z]/.test(val), "Password must contain an uppercase letter") + .refine((val) => /[a-z]/.test(val), "Password must contain a lowercase letter") + .refine((val) => /\d/.test(val), "Password must contain a number") + .refine( + (val) => specialCharPattern.test(val), + "Password must contain a special character" + ), + confirm: z.string().min(1, "Please confirm your password"), + }) + .refine((data) => data.password === data.confirm, { + message: "Passwords do not match", + path: ["confirm"], + }); + +export type RegisterFormData = z.infer; diff --git a/client/src/locales/en.json b/client/src/locales/en.json index 90fe56997..305b3cf90 100644 --- a/client/src/locales/en.json +++ b/client/src/locales/en.json @@ -509,6 +509,9 @@ "password": { "label": "Password", "placeholder": "********" + }, + "confirmPassword": { + "label": "Confirm password" } } } @@ -528,6 +531,23 @@ } } }, + "register": { + "title": "Welcome back to Checkmate!", + "subtitle": "Sign up to get started", + "submit": "Register", + "form": { + "option": { + "name": { + "label": "Name", + "placeholder": "Your name" + }, + "surname": { + "label": "Surname", + "placeholder": "Your surname" + } + } + } + }, "forgotPassword": { "title": "Forgot your password?", "subtitle": "No worries, we'll send you reset instructions.", diff --git a/server/src/service/business/userService.ts b/server/src/service/business/userService.ts index a0273af99..281c03ab7 100644 --- a/server/src/service/business/userService.ts +++ b/server/src/service/business/userService.ts @@ -87,8 +87,9 @@ class UserService { const superAdminExists = await this.usersRepository.findSuperAdmin(); if (superAdminExists) { const invite = await this.invitesRepository.findByTokenAndDelete(inviteToken); - user.role = invite.role; + user.role = invite.role ?? ["user"]; user.teamId = invite.teamId; + user.email = invite.email; } else { // This is the first account, create JWT secret to use if one is not supplied by env const jwtSecret = this.crypto.randomBytes(64).toString("hex"); @@ -99,6 +100,7 @@ class UserService { } const team = await this.teamsRepository.create(user.email); user.teamId = team.id; + user.role = ["superadmin"]; } const newUser = await this.usersRepository.create({ ...user }, file); diff --git a/server/src/validation/joi.ts b/server/src/validation/joi.ts index 49f919a4a..c1e945961 100755 --- a/server/src/validation/joi.ts +++ b/server/src/validation/joi.ts @@ -51,9 +51,7 @@ const registrationBodyValidation = joi.object({ }), password: joi.string().min(8).required().pattern(passwordPattern), profileImage: joi.any(), - role: joi.array().items(joi.string().valid("superadmin", "admin", "user", "demo")), - teamId: joi.string().allow("").required(), - inviteToken: joi.string().allow("").required(), + inviteToken: joi.string().allow("").optional(), }); const editUserBodyValidation = joi.object({