|
| 1 | +import { useMemo, useState } from "react"; |
| 2 | +import { useAuth } from "../auth/AuthContext.jsx"; |
| 3 | +import "./LoginPage.css"; |
| 4 | + |
| 5 | +function normalizeReturnTo(value) { |
| 6 | + if (!value || !value.startsWith("/") || value.startsWith("//")) return "/main"; |
| 7 | + return value; |
| 8 | +} |
| 9 | + |
| 10 | +export function LoginPage() { |
| 11 | + const { reload } = useAuth(); |
| 12 | + const params = new URLSearchParams(window.location.search); |
| 13 | + const returnTo = useMemo(() => normalizeReturnTo(params.get("returnTo")), [params]); |
| 14 | + const [email, setEmail] = useState(""); |
| 15 | + const [password, setPassword] = useState(""); |
| 16 | + const [error, setError] = useState(""); |
| 17 | + const [submitting, setSubmitting] = useState(false); |
| 18 | + |
| 19 | + async function handleSubmit(event) { |
| 20 | + event.preventDefault(); |
| 21 | + setSubmitting(true); |
| 22 | + setError(""); |
| 23 | + |
| 24 | + try { |
| 25 | + const response = await fetch("/api/auth/password/login", { |
| 26 | + method: "POST", |
| 27 | + credentials: "include", |
| 28 | + headers: { "Content-Type": "application/json" }, |
| 29 | + body: JSON.stringify({ email, password }), |
| 30 | + }); |
| 31 | + const data = await response.json(); |
| 32 | + if (!response.ok) throw new Error(data.error || "Failed to log in."); |
| 33 | + await reload(); |
| 34 | + window.location.href = returnTo; |
| 35 | + } catch (err) { |
| 36 | + setError(err.message); |
| 37 | + } finally { |
| 38 | + setSubmitting(false); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return ( |
| 43 | + <main className="login-page"> |
| 44 | + <section className="login-card"> |
| 45 | + <a className="login-card__back" href="/"> |
| 46 | + ← Back |
| 47 | + </a> |
| 48 | + <h1>Join Stack</h1> |
| 49 | + <p>Use your email and a password. If this email is new, we’ll create your account.</p> |
| 50 | + |
| 51 | + <form onSubmit={handleSubmit}> |
| 52 | + <label> |
| 53 | + Email |
| 54 | + <input |
| 55 | + type="email" |
| 56 | + value={email} |
| 57 | + onChange={(event) => setEmail(event.target.value)} |
| 58 | + placeholder="you@example.com" |
| 59 | + autoComplete="email" |
| 60 | + required |
| 61 | + /> |
| 62 | + </label> |
| 63 | + <label> |
| 64 | + Password |
| 65 | + <input |
| 66 | + type="password" |
| 67 | + value={password} |
| 68 | + onChange={(event) => setPassword(event.target.value)} |
| 69 | + placeholder="At least 6 characters" |
| 70 | + autoComplete="current-password" |
| 71 | + required |
| 72 | + /> |
| 73 | + </label> |
| 74 | + <button type="submit" disabled={submitting}> |
| 75 | + {submitting ? "Logging in..." : "Log in / Sign up"} |
| 76 | + </button> |
| 77 | + </form> |
| 78 | + |
| 79 | + {error ? <p className="login-card__error">{error}</p> : null} |
| 80 | + </section> |
| 81 | + </main> |
| 82 | + ); |
| 83 | +} |
0 commit comments