Files
deno-fresh/routes/sign-in.tsx
T

77 lines
1.7 KiB
TypeScript

import { z } from "zod";
import { backendSignIn } from "../backend/sign-in.ts";
import { SignInForm } from "../components/SignInForm.tsx";
import { define, isLoggedIn, setAuthCookie } from "../utils.ts";
const loginSchema = z.object({
email: z.string(),
password: z.string().min(8),
});
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);
}
return {
data: {
email: "",
error: undefined,
},
};
},
async POST(ctx) {
const formData = await ctx.req.formData();
const request = loginSchema.safeParse({
email: formData.get("email"),
password: formData.get("password"),
});
if (!request.success) {
return {
data: {
email: formData.get("email") as string,
error: request.error.issues[0].message,
},
};
}
const { email, password } = request.data;
// Super secure authorization method
if (!await backendSignIn(email, password)) {
return {
data: {
email,
},
};
}
const headers = new Headers();
setAuthCookie(ctx.req, headers);
const url = new URL(ctx.req.url);
url.pathname = "/dashboard";
headers.set("location", url.toString());
return new Response(null, {
status: 303,
headers,
});
},
});
export default define.page<typeof handler>(function SignInPage(ctx) {
const email = ctx.data.email || "";
const error = ctx.data.error;
return (
<div class="container mx-auto p-4 flex flex-col gap-4">
<h1>Sign in</h1>
<SignInForm email={email} error={error} />
</div>
);
});