chore: update copy of register and login

This commit is contained in:
me
2026-05-08 21:00:18 +05:30
parent c6545a11b1
commit a7cced71ee
3 changed files with 307 additions and 297 deletions
+35 -36
View File
@@ -1,44 +1,43 @@
import type { UseFormRegisterReturn } from "react-hook-form";
interface FormFieldProps {
label: string;
type?: string;
placeholder?: string;
registration: UseFormRegisterReturn;
error?: string;
handleFocus?: () => void;
"data-testid"?: string;
label: string;
type?: string;
placeholder?: string;
registration: UseFormRegisterReturn;
error?: string;
handleFocus?: () => void;
"data-testid"?: string;
}
export default function FormField({
label,
type = "text",
placeholder,
registration,
error,
handleFocus,
"data-testid": testId,
label,
type = "text",
placeholder,
registration,
error,
handleFocus,
"data-testid": testId,
}: FormFieldProps) {
return (
<div className="form-control">
<label
htmlFor={registration.name}
className="field-label font-display text-base-content/90 font-medium"
>
{label}
</label>
<input
{...registration}
id={registration.name}
data-testid={testId}
type={type}
placeholder={placeholder}
className={`input input-bordered focus:input-primary ${
error ? "input-error" : ""
}`}
onFocus={handleFocus}
/>
{error && <p className="text-error">{error}</p>}
</div>
);
return (
<div className="form-control">
<label
htmlFor={registration.name}
className="field-label font-display text-neutral-content/80 font-medium"
>
{label}
</label>
<input
{...registration}
id={registration.name}
data-testid={testId}
type={type}
placeholder={placeholder}
className={`input input-bordered focus:input-primary ${error ? "input-error" : ""
}`}
onFocus={handleFocus}
/>
{error && <p className="text-error">{error}</p>}
</div>
);
}
+116 -117
View File
@@ -16,135 +16,134 @@ import { useAuth } from "../hooks/useAuth";
import { CryptoUtils } from "../utils/crypto";
const loginSchema = z.object({
email: z.email("Please enter a valid email"),
password: z.string().min(1, "Password is required"),
email: z.email("Please enter a valid email"),
password: z.string().min(1, "Password is required"),
});
type LoginInputs = z.infer<typeof loginSchema>;
export default function Login() {
const navigate = useNavigate();
const location = useLocation();
const [isLoading, setIsLoading] = useState(false);
const [apiError, setApiError] = useState<string | null>(null);
const { setAuthStore } = useAuth();
const [showWelcome, setShowWelcome] = useState(!!location.state?.firstTime);
const [saajanMessage, setSaajanMessage] = useState<string>(
"I was wondering when you'd return.",
);
const nextRoute = location.state?.redirectUrl || ROUTES.DRAWER;
const navigate = useNavigate();
const location = useLocation();
const [isLoading, setIsLoading] = useState(false);
const [apiError, setApiError] = useState<string | null>(null);
const { setAuthStore } = useAuth();
const [showWelcome, setShowWelcome] = useState(!!location.state?.firstTime);
const [saajanMessage, setSaajanMessage] = useState<string>(
"I was wondering when you'd return.",
);
const nextRoute = location.state?.redirectUrl || ROUTES.DRAWER;
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginInputs>({
resolver: zodResolver(loginSchema),
});
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginInputs>({
resolver: zodResolver(loginSchema),
});
const onSubmit = async (data: LoginInputs) => {
setIsLoading(true);
setApiError(null);
try {
// client side key derivation for e2e encryption
const { masterKey, authHash } = await CryptoUtils.deriveKeyBundle(
data.password,
data.email,
);
const onSubmit = async (data: LoginInputs) => {
setIsLoading(true);
setApiError(null);
try {
// client side key derivation for e2e encryption
const { masterKey, authHash } = await CryptoUtils.deriveKeyBundle(
data.password,
data.email,
);
// send just the authHash as the password to the server
const { data: authData } = await publicApi.post(endpoints.LOGIN, {
email: data.email,
password: authHash,
});
// send just the authHash as the password to the server
const { data: authData } = await publicApi.post(endpoints.LOGIN, {
email: data.email,
password: authHash,
});
const { data: userData } = await api.get(endpoints.ME, {
headers: { Authorization: `Bearer ${authData.access}` },
});
const { data: userData } = await api.get(endpoints.ME, {
headers: { Authorization: `Bearer ${authData.access}` },
});
await setAuthStore(authData.access, userData, masterKey);
await setAuthStore(authData.access, userData, masterKey);
navigate(nextRoute, { replace: true, state: location.state });
} catch (err) {
let message =
"Sorry, we're experiencing technical issues.\nPlease try again later.";
if (axios.isAxiosError(err) && err.response?.status !== 500) {
message = err.response?.data?.detail || err.response?.data?.message;
}
setApiError(message);
} finally {
setIsLoading(false);
}
};
return (
<div className="flex flex-col items-center">
{!showWelcome && <Saajan message={saajanMessage} position="top" />}
{showWelcome && <WelcomeModal setShowWelcome={setShowWelcome} />}
<div className="glass-card w-full max-w-sm p-2 transition-all duration-500 hover:shadow-2xl fade-zoom">
<form onSubmit={handleSubmit(onSubmit)} className="card-body gap-4">
<h1 className="flex items-center font-display text-2xl justify-center text-primary/80 tracking-tight">
&nbsp;&nbsp;Enter <Logo type="logo" scale={0.7} /> Archive
</h1>
{apiError && (
<div className="alert alert-error text-xs py-2 rounded-md">
<span data-testid="login-error-message">{apiError}</span>
</div>
)}
<FormField
label="Email"
type="email"
placeholder="f.kafka@wrongtrain.com"
data-testid="email-input"
registration={register("email")}
error={errors.email?.message}
handleFocus={() => setSaajanMessage("I remember you.")}
/>
<FormField
label="Password"
type="password"
placeholder="••••••••"
data-testid="password-input"
registration={register("password")}
error={errors.password?.message}
handleFocus={() =>
setSaajanMessage("The one thing I cannot know for you.")
navigate(nextRoute, { replace: true, state: location.state });
} catch (err) {
let message =
"Sorry, we're experiencing technical issues.\nPlease try again later.";
if (axios.isAxiosError(err) && err.response?.status !== 500) {
message = err.response?.data?.detail || err.response?.data?.message;
}
/>
setApiError(message);
} finally {
setIsLoading(false);
}
};
<div className="card-actions mt-4">
<button
type="submit"
name="login"
disabled={isLoading}
aria-label="Sign In"
data-testid="login-submit-btn"
className="btn btn-primary w-full shadow-lg"
>
{isLoading ? (
<span className="loading loading-spinner loading-sm" />
) : (
"Sign In"
)}
</button>
</div>
return (
<div className="flex flex-col items-center">
{!showWelcome && <Saajan message={saajanMessage} position="top" />}
{showWelcome && <WelcomeModal setShowWelcome={setShowWelcome} />}
<div className="glass-card w-full max-w-sm p-2 transition-all duration-500 hover:shadow-2xl fade-zoom">
<form onSubmit={handleSubmit(onSubmit)} className="card-body gap-4">
<h1 className="flex items-center font-display text-2xl justify-center text-primary/80 tracking-tight">
&nbsp;&nbsp;Enter <Logo type="logo" scale={0.7} /> Archive
</h1>
<div className="text-center text-sm font-medium text-base-content/70">
Don't have an account?{" "}
<button
type="button"
name="register"
onClick={() => navigate(ROUTES.ONBOARD)}
className="link link-primary no-underline hover:underline font-bold"
>
Register
</button>
</div>
</form>
</div>
</div>
);
{apiError && (
<div className="alert alert-error text-xs py-2 rounded-md">
<span data-testid="login-error-message">{apiError}</span>
</div>
)}
<FormField
label="Email"
type="email"
placeholder="f.kafka@wrongtrain.com"
data-testid="email-input"
registration={register("email")}
error={errors.email?.message}
handleFocus={() => setSaajanMessage("I remember you.")}
/>
<FormField
label="Password"
type="password"
placeholder="••••••••"
data-testid="password-input"
registration={register("password")}
error={errors.password?.message}
handleFocus={() =>
setSaajanMessage("The one thing I cannot know for you.")
}
/>
<div className="card-actions mt-4">
<button
type="submit"
name="login"
disabled={isLoading}
data-testid="login-submit-btn"
className="btn btn-primary w-full shadow-lg"
>
{isLoading ? (
<span className="loading loading-spinner loading-sm" />
) : (
"Continue"
)}
</button>
</div>
<div className="divider text-neutral my-0">or</div>
<div className="text-center text-sm font-medium text-neutral">
New to <Logo type="inline" />?{" "}
<button
type="button"
name="register"
onClick={() => navigate(ROUTES.ONBOARD)}
className="link link-primary"
>
Start here
</button>.
</div>
</form>
</div>
</div>
);
}
+156 -144
View File
@@ -14,158 +14,170 @@ import { ROUTES } from "../config/routes";
import { CryptoUtils } from "../utils/crypto";
const registerSchema = z
.object({
full_name: z.string().min(2, "Name must be at least 2 characters"),
email: z.email("Please enter a valid email"),
password: z.string().min(8, "Password must be at least 8 characters"),
confirm_password: z.string(),
})
.refine((data) => data.password === data.confirm_password, {
message: "Passwords don't match",
path: ["confirm_password"],
});
.object({
full_name: z.string().min(2, "Name must be at least 2 characters"),
email: z.email("Please enter a valid email"),
password: z.string().min(8, "Password must be at least 8 characters"),
confirm_password: z.string(),
})
.refine((data) => data.password === data.confirm_password, {
message: "Passwords don't match",
path: ["confirm_password"],
});
type RegisterInputs = z.infer<typeof registerSchema>;
export default function Register() {
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const [apiError, setApiError] = useState<string | null>(null);
const [saajanMessage, setSaajanMessage] = useState<string>(
"I didn't think I'd be here either.\nAnd yet, here we are.",
);
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const [apiError, setApiError] = useState<string | null>(null);
const [saajanMessage, setSaajanMessage] = useState<string>(
"I didn't think I'd be here either.\nAnd yet, here we are.",
);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegisterInputs>({
resolver: zodResolver(registerSchema),
});
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegisterInputs>({
resolver: zodResolver(registerSchema),
});
const onSubmit = async (data: RegisterInputs) => {
setSaajanMessage("Good. I'll remember that.");
setIsLoading(true);
setApiError(null);
try {
// we generate the key bundle here to get the authHash (password) to be haSHed and stored in the db.
const { authHash } = await CryptoUtils.deriveKeyBundle(
data.password,
data.email,
);
const onSubmit = async (data: RegisterInputs) => {
setSaajanMessage("Good. I'll remember that.");
setIsLoading(true);
setApiError(null);
try {
// we generate the key bundle here to get the authHash (password) to be haSHed and stored in the db.
const { authHash } = await CryptoUtils.deriveKeyBundle(
data.password,
data.email,
);
await publicApi.post(endpoints.REGISTER, {
full_name: data.full_name,
email: data.email,
password: authHash,
});
navigate(ROUTES.VERIFY_EMAIL, { replace: true });
} catch (err) {
let message = "Registration failed. Please try again.";
if (axios.isAxiosError(err)) {
message = err.response?.data?.message || message;
}
setApiError(message);
} finally {
setIsLoading(false);
}
};
await publicApi.post(endpoints.REGISTER, {
full_name: data.full_name,
email: data.email,
password: authHash,
});
navigate(ROUTES.VERIFY_EMAIL, { replace: true });
} catch (err) {
let message = "Registration failed. Please try again.";
if (axios.isAxiosError(err)) {
message = err.response?.data?.message || message;
}
setApiError(message);
} finally {
setIsLoading(false);
}
};
return (
<div className="flex flex-col">
<Saajan message={saajanMessage} position="right" />
<div className="glass-card w-full max-w-sm p-2 transition-all duration-500 hover:shadow-2xl fade-zoom">
<form onSubmit={handleSubmit(onSubmit)} className="card-body gap-4">
<div className="card-title font-display text-2xl justify-center text-primary/80 tracking-tight whitespace-nowrap">
Create a <Logo type="logo" scale={0.7} /> Account
</div>
return (
<div className="flex flex-col">
<Saajan message={saajanMessage} position="right" />
<div className="glass-card w-full max-w-sm p-2 transition-all duration-500 hover:shadow-2xl fade-zoom">
<form onSubmit={handleSubmit(onSubmit)} className="card-body gap-4">
<div className="card-title font-display text-2xl justify-center text-primary/80 tracking-tight whitespace-nowrap">
Create a <Logo type="logo" scale={0.7} /> Account
</div>
{apiError && (
<div className="alert alert-error text-xs py-2 rounded-md">
<span>{apiError}</span>
{apiError && (
<div className="alert alert-error text-xs py-2 rounded-md">
<span>{apiError}</span>
</div>
)}
<FormField
label="Pen Name"
placeholder="Word Smith"
data-testid="pen-name-input"
registration={register("full_name")}
error={errors.full_name?.message}
handleFocus={() =>
setSaajanMessage("Hello friend. What should I call you?")
}
/>
<FormField
label="Email"
type="email"
placeholder="f.kafka@wrongtrain.com"
data-testid="email-input"
registration={register("email")}
error={errors.email?.message}
handleFocus={() =>
setSaajanMessage(
"Where should I send your letters?\nNo empty lunchboxes, please.",
)
}
/>
<FormField
label="Password"
type="password"
placeholder="••••••••"
data-testid="password-input"
registration={register("password")}
error={errors.password?.message}
handleFocus={() =>
setSaajanMessage(
"Something only you know.\nI have one of those too.",
)
}
/>
<FormField
label="Confirm Password"
type="password"
placeholder="••••••••"
data-testid="confirm-password-input"
registration={register("confirm_password")}
error={errors.confirm_password?.message}
handleFocus={() =>
setSaajanMessage(
"Just once? Trust me, \nsome things are worth repeating twice.",
)
}
/>
<div className="alert alert-warning items-start text-left p-3 gap-2 rounded-md border-warning/20">
<InfoIcon size={20} weight="duotone" className="mt-0.5 shrink-0" />
<p className="text-sm font-semibold">
Choose a password you won't forget. <br />
Just like life,{" "}
<span className="underline decoration-2">there is no reset</span>{" "}
here. If you lose it, your letters cannot be recovered.
</p>
</div>
<div className="card-actions mt-4">
<button
type="submit"
disabled={isLoading}
aria-label="Register"
data-testid="register-submit-btn"
className="btn btn-primary w-full shadow-lg"
>
{isLoading ? (
<span className="loading loading-spinner loading-sm" />
) : (
"Begin"
)}
</button>
</div>
<div className="divider text-neutral my-0">or</div>
<div className="text-center text-sm font-medium text-neutral">
Been here before?{" "}
<button
type="button"
name="register"
onClick={() => navigate(ROUTES.LOGIN)}
className="link link-primary"
>
Continue where you left off
</button>.
</div>
</form>
</div>
)}
<FormField
label="Pen Name"
placeholder="Word Smith"
data-testid="pen-name-input"
registration={register("full_name")}
error={errors.full_name?.message}
handleFocus={() =>
setSaajanMessage("Hello friend. What should I call you?")
}
/>
<FormField
label="Email"
type="email"
placeholder="f.kafka@wrongtrain.com"
data-testid="email-input"
registration={register("email")}
error={errors.email?.message}
handleFocus={() =>
setSaajanMessage(
"Where should I send your letters?\nNo empty lunchboxes, please.",
)
}
/>
<FormField
label="Password"
type="password"
placeholder="••••••••"
data-testid="password-input"
registration={register("password")}
error={errors.password?.message}
handleFocus={() =>
setSaajanMessage(
"Something only you know.\nI have one of those too.",
)
}
/>
<FormField
label="Confirm Password"
type="password"
placeholder="••••••••"
data-testid="confirm-password-input"
registration={register("confirm_password")}
error={errors.confirm_password?.message}
handleFocus={() =>
setSaajanMessage(
"Just once? Trust me, \nsome things are worth repeating twice.",
)
}
/>
<div className="alert alert-warning items-start text-left p-3 gap-2 rounded-md border-warning/20">
<InfoIcon size={20} weight="duotone" className="mt-0.5 shrink-0" />
<p className="text-sm font-semibold">
Choose a password you won't forget. <br />
Just like life,{" "}
<span className="underline decoration-2">there is no reset</span>{" "}
here. If you lose it, your letters cannot be recovered.
</p>
</div>
<div className="card-actions mt-4">
<button
type="submit"
disabled={isLoading}
aria-label="Register"
data-testid="register-submit-btn"
className="btn btn-primary w-full shadow-lg"
>
{isLoading ? (
<span className="loading loading-spinner loading-sm" />
) : (
"Register"
)}
</button>
</div>
</form>
</div>
</div>
);
</div>
);
}