g1t/apps/web/app/routes/login.tsx
| 1 | import { Form, Link, redirect } from "react-router"; |
| 2 | |
| 3 | import type { Route } from "./+types/login"; |
| 4 | import { page } from "../lib/meta"; |
| 5 | import { AuthCard } from "../components/auth-card"; |
| 6 | import { Button, ErrorText, Field, Input } from "../components/ui"; |
| 7 | import { identity } from "../lib/services.server"; |
| 8 | import { |
| 9 | assertSameOrigin, |
| 10 | getViewer, |
| 11 | nextPath, |
| 12 | startSession, |
| 13 | } from "../lib/session.server"; |
| 14 | |
| 15 | export function meta(args: Route.MetaArgs) { |
| 16 | return page(args, { title: "Sign in · g1t" }); |
| 17 | } |
| 18 | |
| 19 | export function loader({ request, context }: Route.LoaderArgs) { |
| 20 | if (getViewer(context)) throw redirect(nextPath(request)); |
| 21 | return { next: nextPath(request) }; |
| 22 | } |
| 23 | |
| 24 | export async function action({ request }: Route.ActionArgs) { |
| 25 | assertSameOrigin(request); |
| 26 | const form = await request.formData(); |
| 27 | const result = await identity.signIn( |
| 28 | String(form.get("username") ?? "").trim(), |
| 29 | String(form.get("password") ?? ""), |
| 30 | ); |
| 31 | if (!result.ok) return { error: result.error.message }; |
| 32 | throw redirect(nextPath(request), { |
| 33 | headers: { "set-cookie": startSession(result.value.sessionToken) }, |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | export default function Login({ loaderData, actionData }: Route.ComponentProps) { |
| 38 | const registerUrl = |
| 39 | loaderData.next === "/" |
| 40 | ? "/register" |
| 41 | : `/register?next=${encodeURIComponent(loaderData.next)}`; |
| 42 | return ( |
| 43 | <AuthCard |
| 44 | title="Welcome back" |
| 45 | subtitle="Sign in to g1t" |
| 46 | footer={ |
| 47 | <> |
| 48 | New to g1t?{" "} |
| 49 | <Link to={registerUrl} className="text-fg underline underline-offset-4"> |
| 50 | Create an account |
| 51 | </Link> |
| 52 | </> |
| 53 | } |
| 54 | > |
| 55 | <Form method="post" className="space-y-4"> |
| 56 | <Field label="Username"> |
| 57 | <Input name="username" autoComplete="username" required autoFocus /> |
| 58 | </Field> |
| 59 | <Field label="Password"> |
| 60 | <Input |
| 61 | name="password" |
| 62 | type="password" |
| 63 | autoComplete="current-password" |
| 64 | required |
| 65 | /> |
| 66 | </Field> |
| 67 | <ErrorText>{actionData?.error}</ErrorText> |
| 68 | <div className="pt-2 *:w-full"> |
| 69 | <Button type="submit">Sign in</Button> |
| 70 | </div> |
| 71 | <p className="text-center text-sm"> |
| 72 | <Link to="/forgot" className="text-muted hover:text-fg"> |
| 73 | Forgot your password? |
| 74 | </Link> |
| 75 | </p> |
| 76 | </Form> |
| 77 | </AuthCard> |
| 78 | ); |
| 79 | } |