Skip to content
refs
48 lines · 2.3 KBRaw
1import { Button, Input } from "@refs/design-system";
2import { Form, Link, redirect, useNavigation } from "react-router";
3import type { Route } from "./+types/login";
4import { AuthPage } from "../components/shell";
5import { failed, formText, gate, refs, sessionCookie } from "../lib/session";
6
7export const meta: Route.MetaFunction = () => [{ title: "Sign in · refs" }];
8
9function nextPath(value: string | null): string {
10 return value && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\") ? value : "/";
11}
12
13export function loader({ request, context }: Route.LoaderArgs) {
14 const { viewer } = refs(context);
15 const next = nextPath(new URL(request.url).searchParams.get("next"));
16 if (viewer.person) throw redirect(next);
17 return { org: "refs", next };
18}
19
20export async function action({ request, context }: Route.ActionArgs) {
21 const form = await request.formData();
22 const email = formText(form, "email");
23 const outcome = await gate(context).signIn({ email, password: String(form.get("password") ?? ""), ip: request.headers.get("cf-connecting-ip") ?? "unknown" });
24 if (!outcome.ok) return failed(outcome.problem, { email });
25 throw redirect(nextPath(formText(form, "next")), { headers: { "Set-Cookie": sessionCookie(outcome.value) } });
26}
27
28export default function Login({ loaderData, actionData }: Route.ComponentProps) {
29 const submitting = useNavigation().state === "submitting";
30 return (
31 <AuthPage subtitle={`Sign in to ${loaderData.org}`} error={actionData?.error}>
32 <Form key={JSON.stringify(actionData ?? null)} method="post" className="flex flex-col gap-4">
33 <input type="hidden" name="next" value={loaderData.next} />
34 <Input label="Email" name="email" type="email" size="lg" defaultValue={actionData?.email} autoComplete="username" required autoFocus />
35 <Input label="Password" name="password" type="password" size="lg" autoComplete="current-password" required />
36 <Button type="submit" variant="primary" size="lg" className="w-full justify-center" loading={submitting}>
37 Sign in
38 </Button>
39 <p className="m-0 text-center text-sm text-muted">
40 No account?{" "}
41 <Link to="/signup" className="text-accent-text">
42 Join the waitlist
43 </Link>
44 </p>
45 </Form>
46 </AuthPage>
47 );
48}