From 66b4868c6f92f17a1e8f8746176fe708da626b05 Mon Sep 17 00:00:00 2001 From: Oliver Bryan <04oliverbryan@gmail.com> Date: Mon, 22 Dec 2025 06:33:58 +0000 Subject: [PATCH] login form component --- .../frontend/src/components/login-form.tsx | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 packages/frontend/src/components/login-form.tsx diff --git a/packages/frontend/src/components/login-form.tsx b/packages/frontend/src/components/login-form.tsx new file mode 100644 index 0000000..86219f9 --- /dev/null +++ b/packages/frontend/src/components/login-form.tsx @@ -0,0 +1,127 @@ +import { type ChangeEvent, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { cn, getAuthHeaders } from "@/lib/utils"; + +function Field({ + label = "label", + onChange = () => {}, + invalidMessage = "", + hidden = false, +}: { + label: string; + onChange?: (e: ChangeEvent) => void; + invalidMessage?: string; + hidden?: boolean; +}) { + return ( +
+
+ +
+ +
+ {invalidMessage !== "" ? ( + + ) : ( + + )} +
+
+ ); +} + +export default function LogInForm() { + const serverURL = import.meta.env.SERVER_URL?.trim() || "http://localhost:3000"; + + const [username, setUsername] = useState(""); + const [usernameInvalid, setUsernameInvalid] = useState(""); + const [password, setPassword] = useState(""); + const [passwordInvalid, setPasswordInvalid] = useState(""); + const [error, setError] = useState(""); + + const logIn = () => { + if (username === "" || password === "") { + if (username === "") { + setUsernameInvalid("Cannot be empty"); + } + if (password === "") { + setPasswordInvalid("Cannot be empty"); + } + return; + } + + fetch(`${serverURL}/auth/login`, { + method: "POST", + headers: { "Content-Type": "application/json", ...getAuthHeaders() }, + + body: JSON.stringify({ username, password }), + }) + .then(async (res) => { + if (res.status === 200) { + setError(""); + const data = await res.json(); + localStorage.setItem("token", data.token); + localStorage.setItem("user", data.user); + window.location.href = "/"; + } + // unauthorized + else if (res.status === 401) { + setError("Either the username or password is incorrect"); + } else { + setError("An unknown error occured."); + } + }) + .catch((err) => { + console.error(err); + setError(`${err.statusText}`); + }); + }; + + return ( +
+
+ { + if (e.target.value !== "") setUsernameInvalid(""); + else setUsernameInvalid("Cannot be empty"); + setUsername(e.target.value); + }} + invalidMessage={usernameInvalid} + /> + { + if (e.target.value !== "") setPasswordInvalid(""); + else setPasswordInvalid("Cannot be empty"); + setPassword(e.target.value); + }} + invalidMessage={passwordInvalid} + hidden={true} + /> + +
+
+ {error !== "" ? ( + + ) : ( + + )} +
+
+ ); +}