feat: refactoring, soem work on forms

This commit is contained in:
2026-09-13 23:17:37 +02:00
parent fa07d4cc0b
commit 0dbbe5361a
17 changed files with 260 additions and 116 deletions
+11
View File
@@ -16,5 +16,16 @@
},
"files.associations": {
"*.css": "tailwindcss"
},
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/.DS_Store": true,
"**/Thumbs.db": true,
"**/.cursor": true,
"**/.vscode": true,
"**/_fresh": true,
"**/node_modules": true
}
}
+7 -1
View File
@@ -7,7 +7,6 @@ const loggedOutLinks = [
const loggedInLinks = [
{ href: "/", label: "Home" },
{ href: "/dashboard", label: "Dashboard" },
{ href: "/sign-out", label: "Sign out" },
];
export interface Props {
@@ -29,6 +28,13 @@ export default function Header(props: Props) {
<a href={l.href}>{l.label}</a>
</li>
))}
{props.loggedIn && (
<li>
<form method="post" action="/sign-out">
<button type="submit">Sign out</button>
</form>
</li>
)}
</ul>
</div>
</div>
+67
View File
@@ -0,0 +1,67 @@
import { useRef, useState } from "preact/hooks";
const mismatchMessage = "Passwords do not match.";
export default function PasswordConfirmationFields() {
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const confirmInput = useRef<HTMLInputElement>(null);
const passwordsDoNotMatch = passwordConfirm.length > 0 &&
password !== passwordConfirm;
function updatePassword(value: string) {
setPassword(value);
const confirmation = confirmInput.current;
if (confirmation) {
confirmation.setCustomValidity(
confirmation.value && value !== confirmation.value
? mismatchMessage
: "",
);
}
}
function updatePasswordConfirm(value: string) {
setPasswordConfirm(value);
confirmInput.current?.setCustomValidity(
value && password !== value ? mismatchMessage : "",
);
}
return (
<div class="grid grid-cols-2 gap-4">
<input
type="password"
name="password"
placeholder="Password"
class="input min-w-0 flex-1"
autocomplete="new-password"
minLength={8}
required
value={password}
onInput={(event) => updatePassword(event.currentTarget.value)}
/>
<div class="min-w-0 flex-1">
<input
ref={confirmInput}
type="password"
name="passwordConfirm"
placeholder="Confirm"
class="input w-full"
autocomplete="new-password"
minLength={8}
required
value={passwordConfirm}
aria-invalid={passwordsDoNotMatch}
aria-describedby="password-confirm-error"
onInput={(event) => updatePasswordConfirm(event.currentTarget.value)}
/>
{passwordsDoNotMatch && (
<p id="password-confirm-error" class="mt-1 text-sm text-error">
{mismatchMessage}
</p>
)}
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { deleteCookie, getCookies, setCookie } from "@std/http/cookie";
export function setAuthCookie(
headers: Headers,
) {
setCookie(headers, {
name: "auth",
value: "ok",
maxAge: 60 * 60,
sameSite: "Lax",
path: "/",
secure: true,
httpOnly: true,
});
}
export function unsetAuthCookie(headers: Headers) {
deleteCookie(headers, "auth", {
path: "/",
});
}
export function isLoggedIn(req: Request): boolean {
const cookies = getCookies(req.headers);
const authCookie = cookies["auth"];
return authCookie === "ok";
}
+9
View File
@@ -0,0 +1,9 @@
import { define } from "../../utils.ts";
export default define.middleware((ctx) => {
if (!ctx.state.loggedIn) {
return ctx.redirect("/sign-in", 303);
}
return ctx.next();
});
+10
View File
@@ -0,0 +1,10 @@
import Headline from "../../components/Headline.tsx";
import { define } from "../../utils.ts";
export default define.page(function Dashboard() {
return (
<div class="container mx-auto p-4">
<Headline>Dashboard</Headline>
</div>
);
});
@@ -1,13 +1,12 @@
import { define, unsetAuthCookie } from "../utils.ts";
import { unsetAuthCookie } from "../../lib/auth.ts";
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
POST(ctx) {
const headers = new Headers();
unsetAuthCookie(headers);
const url = new URL(ctx.req.url);
url.pathname = "/";
headers.set("location", url.toString());
headers.set("location", new URL("/", ctx.req.url).toString());
return new Response(null, {
status: 303,
headers,
+9
View File
@@ -0,0 +1,9 @@
import { define } from "../../utils.ts";
export default define.middleware((ctx) => {
if (ctx.state.loggedIn) {
return ctx.redirect("/dashboard", 303);
}
return ctx.next();
});
@@ -1,8 +1,9 @@
import { z } from "zod";
import { backendSignIn } from "../backend/sign-in.ts";
import Headline from "../components/Headline.tsx";
import { SignInForm } from "../components/SignInForm.tsx";
import { define, isLoggedIn, setAuthCookie } from "../utils.ts";
import { backendSignIn } from "../../backend/sign-in.ts";
import Headline from "../../components/Headline.tsx";
import { SignInForm } from "../../components/SignInForm.tsx";
import { setAuthCookie } from "../../lib/auth.ts";
import { define } from "../../utils.ts";
const loginSchema = z.object({
email: z.string(),
@@ -10,13 +11,7 @@ const loginSchema = z.object({
});
export const handler = define.handlers({
GET(ctx) {
if (isLoggedIn(ctx.req)) {
const url = new URL(ctx.req.url);
url.pathname = "/dashboard";
return Response.redirect(url, 303);
}
GET(_ctx) {
return {
data: {
email: "",
@@ -52,7 +47,7 @@ export const handler = define.handlers({
}
const headers = new Headers();
setAuthCookie(ctx.req, headers);
setAuthCookie(headers);
const url = new URL(ctx.req.url);
url.pathname = "/dashboard";
+97
View File
@@ -0,0 +1,97 @@
import { z } from "zod";
import Headline from "../../components/Headline.tsx";
import PasswordConfirmationFields from "../../islands/PasswordConfirmationFields.tsx";
import { define } from "../../utils.ts";
const signUpSchema = z.object({
email: z.email("Please enter a valid email address.").trim(),
firstName: z.string().trim().min(1, "Please enter your first name."),
lastName: z.string().trim().min(1, "Please enter your last name."),
password: z.string().min(8, "Password must be at least 8 characters long."),
passwordConfirm: z.string(),
}).refine((data) => data.password === data.passwordConfirm, {
message: "Passwords do not match.",
path: ["passwordConfirm"],
});
const emptyForm = {
email: "",
firstName: "",
lastName: "",
error: undefined as string | undefined,
};
export const handler = define.handlers({
GET() {
return { data: emptyForm };
},
async POST(ctx) {
const formData = await ctx.req.formData();
const result = signUpSchema.safeParse({
email: formData.get("email"),
firstName: formData.get("firstName"),
lastName: formData.get("lastName"),
password: formData.get("password"),
passwordConfirm: formData.get("passwordConfirm"),
});
if (!result.success) {
return {
data: {
email: formData.get("email")?.toString() ?? "",
firstName: formData.get("firstName")?.toString() ?? "",
lastName: formData.get("lastName")?.toString() ?? "",
error: result.error.issues[0].message,
},
};
}
const { passwordConfirm: _passwordConfirm, ...registration } = result.data;
// Use registration to register user
void registration;
return ctx.redirect("/sign-up", 303);
},
});
export default define.page<typeof handler>(function SignUpPage(ctx) {
const { email, firstName, lastName, error } = ctx.data;
return (
<form method="post" class="container mx-auto p-4 flex flex-col gap-4">
<Headline>Sign up</Headline>
{error && <p class="text-error" role="alert">{error}</p>}
<input
type="email"
name="email"
placeholder="E-Mail"
class="input w-full"
value={email}
required
/>
<div class="flex flex-row gap-4">
<input
type="text"
name="firstName"
placeholder="First name"
class="input min-w-0 flex-1"
value={firstName}
required
/>
<input
type="text"
name="lastName"
placeholder="Last name"
class="input min-w-0 flex-1"
value={lastName}
required
/>
</div>
<PasswordConfirmationFields />
<button type="submit" class="btn btn-primary self-start">
Sign up
</button>
</form>
);
});
@@ -1,7 +1,7 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import Counter from "../islands/Counter.tsx";
import { define } from "../utils.ts";
import Counter from "../../islands/Counter.tsx";
import { define } from "../../utils.ts";
export default define.page(function Home(ctx) {
const count = useSignal(3);
+2 -3
View File
@@ -1,9 +1,8 @@
import Header from "../components/Header.tsx";
import { define, isLoggedIn } from "../utils.ts";
import { define } from "../utils.ts";
export default define.page(function App(ctx) {
const Component = ctx.Component;
const loggedIn = isLoggedIn(ctx.req);
return (
<html data-theme="light">
@@ -13,7 +12,7 @@ export default define.page(function App(ctx) {
<title>Deno Fresh Dummy</title>
</head>
<body>
<Header loggedIn={loggedIn} />
<Header loggedIn={ctx.state.loggedIn} />
<Component />
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
import { isLoggedIn } from "../lib/auth.ts";
import { define } from "../utils.ts";
export default define.middleware((ctx) => {
ctx.state.loggedIn = isLoggedIn(ctx.req);
return ctx.next();
});
-10
View File
@@ -1,10 +0,0 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
-23
View File
@@ -1,23 +0,0 @@
import Headline from "../components/Headline.tsx";
import { define, isLoggedIn } from "../utils.ts";
export const handler = define.handlers({
GET(ctx) {
console.log("ASDF");
if (!isLoggedIn(ctx.req)) {
const url = new URL(ctx.req.url);
url.pathname = "/sign-in";
return Response.redirect(url, 303);
}
return { data: {} };
},
});
export default define.page<typeof handler>(function Dashboard(_ctx) {
return (
<div class="container mx-auto p-4">
<Headline>Dashboard</Headline>
</div>
);
});
-33
View File
@@ -1,33 +0,0 @@
import Headline from "../components/Headline.tsx";
import { define } from "../utils.ts";
export default define.page(function SignUpPage(ctx) {
return (
<form class="container mx-auto p-4 flex flex-col gap-4">
<Headline>Sign up</Headline>
<input
type="email"
name="email"
placeholder="E-Mail"
class="input w-full"
/>
<div class="flex flex-row gap-4">
<input
type="text"
name="firstName"
placeholder="First name"
class="input w-full"
/>
<input
type="text"
name="lastName"
placeholder="Last name"
class="input w-full"
/>
</div>
<button type="submit" class="btn btn-primary self-start">
Sign up
</button>
</form>
);
});
+1 -27
View File
@@ -1,36 +1,10 @@
import { deleteCookie, getCookies, setCookie } from "@std/http/cookie";
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
loggedIn: boolean;
}
export const define = createDefine<State>();
export function setAuthCookie(
req: Request,
headers: Headers,
) {
const url = new URL(req.url);
setCookie(headers, {
name: "auth",
value: "ok",
maxAge: 60 * 60,
sameSite: "Lax",
domain: url.hostname,
path: "/",
secure: true,
});
}
export function unsetAuthCookie(headers: Headers) {
deleteCookie(headers, "auth");
}
export function isLoggedIn(req: Request): boolean {
const cookies = getCookies(req.headers);
const authCookie = cookies["auth"];
return authCookie === "ok";
}