51 lines · 2.4 KBRaw
| 1 | import { Button, Input } from "@refs/design-system"; |
| 2 | import { Form, Link, redirect, useNavigation } from "react-router"; |
| 3 | import type { Route } from "./+types/login"; |
| 4 | import { AuthPage } from "../components/shell"; |
| 5 | import { failed, formText, gate, refs, sessionCookie } from "../lib/session"; |
| 6 | |
| 7 | export const meta: Route.MetaFunction = () => [{ title: "Sign in · refs" }]; |
| 8 | |
| 9 | function nextPath(value: string | null): string { |
| 10 | return value && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\") ? value : "/"; |
| 11 | } |
| 12 | |
| 13 | export 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 | |
| 20 | export 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 | |
| 28 | export 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 | <Link to="/forgot-password" className="-mt-2 self-end text-sm text-accent-text"> |
| 37 | Forgot password? |
| 38 | </Link> |
| 39 | <Button type="submit" variant="primary" size="lg" className="w-full justify-center" loading={submitting}> |
| 40 | Sign in |
| 41 | </Button> |
| 42 | <p className="m-0 text-center text-sm text-muted"> |
| 43 | No account?{" "} |
| 44 | <Link to="/signup" className="text-accent-text"> |
| 45 | Create one |
| 46 | </Link> |
| 47 | </p> |
| 48 | </Form> |
| 49 | </AuthPage> |
| 50 | ); |
| 51 | } |