Spaces:
Running

explication / js /auth.js
quantilimited's picture
Switch the shop from Stripe to PayPal
cecfe55
Raw History Blame Contribute Delete
24.3 kB
import { html, useState } from "./runtime.js";
import { useCloud, money, planPeriod, DEVELOPER_EMAIL } from "./cloud.js";
import { Notice, Pill, Icon } from "./components.js";
function Shell({ children }) {
return html`<main class="page narrow">${children}</main>`;
}
// ---------------------------------------------------------------------------
// Sign in / create account
// ---------------------------------------------------------------------------
export function SignIn({ onDone }) {
const cloud = useCloud();
const [mode, setMode] = useState("signin");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [error, setError] = useState("");
const [showCode, setShowCode] = useState(false);
const [code, setCode] = useState("");
if (!cloud.configured) {
return html`<${Shell}>
<div class="eyebrow">Account</div>
<h1 class="page-title">Explication has no accounts yet.</h1>
<p class="subtitle">Logins run on Supabase. Connect a Supabase project and this page becomes a normal sign-in screen.</p>
<div class="card" style=${{ marginTop: "16px" }}>
<${Notice} kind="warn">No Supabase project is connected to this copy of the site.<//>
<div class="row" style=${{ marginTop: "12px" }}>
<a class="btn primary small" href="#/connect">Connect Supabase</a>
<span class="tiny faint">${DEVELOPER_EMAIL} can do this.</span>
</div>
</div>
<//>`;
}
if (cloud.user) {
return html`<${Account} onDone=${onDone} />`;
}
const submit = async (event) => {
event.preventDefault();
setError("");
setMessage("");
setBusy(true);
try {
if (mode === "signin") await cloud.signIn(email.trim(), password);
else {
const result = await cloud.signUp(email.trim(), password);
if (result && result.session) setMessage("Account created. You are signed in.");
else setMessage("Account created. Check your email — the link signs you straight in, or paste the six-digit code below.");
}
} catch (err) {
setError(err && err.message ? err.message : "That did not work.");
}
setBusy(false);
};
const sendLink = async () => {
setError("");
setMessage("");
if (!email.trim()) {
setError("Type your email first.");
return;
}
setBusy(true);
try {
await cloud.magicLink(email.trim());
setMessage("A sign-in link is on its way to " + email.trim() + ".");
} catch (err) {
setError(err && err.message ? err.message : "The link could not be sent.");
}
setBusy(false);
};
const forgot = async () => {
setError("");
setMessage("");
if (!email.trim()) {
setError("Type your email first, then press Forgot password.");
return;
}
setBusy(true);
try {
await cloud.resetPassword(email.trim());
setMessage("If " + email.trim() + " has an account, a reset link is on its way. It signs you in so you can choose a new password.");
} catch (err) {
setError(err && err.message ? err.message : "The reset email could not be sent.");
}
setBusy(false);
};
const submitCode = async (event) => {
event.preventDefault();
setError("");
setMessage("");
if (!email.trim()) {
setError("Type your email first, then the code.");
return;
}
if (!/^\d{6}$/.test(code.trim())) {
setError("The code is six digits.");
return;
}
setBusy(true);
try {
await cloud.verifyCode(email.trim(), code.trim());
setMessage("Code accepted. You're signed in.");
} catch (err) {
setError(err && err.message ? err.message : "That code did not work.");
}
setBusy(false);
};
return html`<${Shell}>
<div class="eyebrow">Account</div>
<h1 class="page-title">${mode === "signin" ? "Welcome back." : "Make an account."}</h1>
<p class="subtitle">
An account keeps your plan, your model budget and any downloads you own. Your writing still stays in this browser.
</p>
<div class="card" style=${{ marginTop: "18px", maxWidth: "440px" }}>
<div class="row" style=${{ marginBottom: "12px" }}>
<button class=${"btn small " + (mode === "signin" ? "primary" : "ghost")} onClick=${() => setMode("signin")}>Sign in</button>
<button class=${"btn small " + (mode === "signup" ? "primary" : "ghost")} onClick=${() => setMode("signup")}>Create account</button>
</div>
<form onSubmit=${submit} class="stack">
<div class="field">
<label>Email</label>
<input class="input" type="email" value=${email} onInput=${(e) => setEmail(e.target.value)} autocomplete="email" placeholder="you@example.com" required />
</div>
<div class="field">
<label>Password</label>
<input class="input" type="password" value=${password} onInput=${(e) => setPassword(e.target.value)} autocomplete=${mode === "signin" ? "current-password" : "new-password"} placeholder="At least 6 characters" required />
</div>
${mode === "signin" && html`<div class="row" style=${{ justifyContent: "flex-end", marginTop: "-4px" }}>
<button class="btn link small" type="button" onClick=${forgot} disabled=${busy}>Forgot password?</button>
</div>`}
${error && html`<${Notice} kind="error">${error}<//>`}
${message && html`<${Notice} kind="info">${message}<//>`}
<button class="btn primary" type="submit" disabled=${busy}>
${busy ? html`<span class="spin"></span>` : html`<${Icon} name="lock" size=${13} />`} ${mode === "signin" ? "Sign in" : "Create account"}
</button>
</form>
<div class="divider"></div>
<div class="row between wrap">
<span class="tiny faint">No password? Send a one-time link instead.</span>
<button class="btn small" onClick=${sendLink} disabled=${busy}>Email me a link</button>
</div>
<div class="divider"></div>
<div class="row between wrap">
<span class="tiny faint">Got a six-digit code in the email?</span>
<button class="btn small" onClick=${() => setShowCode(!showCode)}>${showCode ? "Hide" : "Use a code"}</button>
</div>
${showCode && html`<form onSubmit=${submitCode} class="stack" style=${{ marginTop: "10px" }}>
<div class="field">
<label>Six-digit code</label>
<input class="input" type="text" inputmode="numeric" maxlength="6" value=${code} onInput=${(e) => setCode(e.target.value.replace(/[^0-9]/g, ""))} placeholder="123456" autocomplete="one-time-code" />
</div>
<button class="btn primary" type="submit" disabled=${busy}>Verify code</button>
</form>`}
</div>
<p class="tiny faint" style=${{ marginTop: "12px" }}>
Plans and purchases are attached to this account. You can use every marking tool without one.
</p>
<//>`;
}
// ---------------------------------------------------------------------------
// Account / plan
// ---------------------------------------------------------------------------
function BudgetBar({ budget, plan }) {
if (!plan) return null;
if (!plan.cost_limit_cents) {
return html` <div class="tiny faint" style=${{ marginTop: "6px" }}>
This pack is all offline: download the models and they are yours, with no allowance to run down.
</div>`;
}
const pct = budget.limit ? Math.min(100, Math.round((budget.spent / budget.limit) * 100)) : 0;
return html`<div style=${{ marginTop: "8px" }}>
<div class="row between tiny">
<span class="muted">Included AI this period</span>
<span class="faint">${100 - pct}% left</span>
</div>
<div class="bar" style=${{ marginTop: "5px" }}><i style=${{ width: pct + "%" }}></i></div>
<div class="tiny faint" style=${{ marginTop: "4px" }}>Your included AI tops up with your plan. Offline models and your own key never touch it.</div>
</div>`;
}
export function Account({ onDone }) {
const cloud = useCloud();
const [busy, setBusy] = useState(false);
if (!cloud.user) {
return html`<${SignIn} />`;
}
const plan = cloud.plan;
const signedOut = async () => {
setBusy(true);
await cloud.signOut();
setBusy(false);
if (onDone) onDone();
};
return html`<${Shell}>
<div class="row between" style=${{ alignItems: "flex-start" }}>
<div>
<div class="eyebrow">Account</div>
<h1 class="page-title">${cloud.user.email}</h1>
<p class="subtitle">${cloud.isDev ? "This address is the developer account for this site." : "Your plan, budget and downloads live here."}</p>
</div>
<button class="btn small" onClick=${signedOut} disabled=${busy}>Sign out</button>
</div>
<div class="section-head"><h2 class="section-title">Your plan</h2>
<a class="btn link small" href="#/pricing">${plan ? "Change plan" : "See plans"}</a>
</div>
<div class="card">
${plan
? html`<div class="row between wrap">
<div>
<div class="row"><span style=${{ fontWeight: 600, fontSize: "15px" }}>${plan.name}</span>
<${Pill} tone=${plan.kind === "subscription" ? "green" : "neutral"}>${plan.kind === "one_time" ? "One-off" : "Subscription"}<//>
</div>
<div class="tiny faint" style=${{ marginTop: "2px" }}>${money(plan.price_cents, plan.currency)} ${planPeriod(plan)}</div>
</div>
<span class="tiny faint">${cloud.entitlement && cloud.entitlement.expires_at ? "Renews " + new Date(cloud.entitlement.expires_at).toLocaleDateString("en-GB") : "Active"}</span>
</div>
<${BudgetBar} budget=${cloud.budget} plan=${plan} />`
: html`<div class="row between wrap">
<div>
<div style=${{ fontWeight: 600 }}>No plan yet</div>
<div class="tiny faint" style=${{ marginTop: "2px" }}>Rule-based marking, chat setup and BYOK work without one.</div>
</div>
<a class="btn primary small" href="#/pricing">Choose a plan</a>
</div>`}
</div>
<div class="section-head"><h2 class="section-title">Bring your own key</h2></div>
<div class="card">
<div class="row between wrap">
<div style=${{ maxWidth: "520px" }}>
<div style=${{ fontWeight: 600 }}>Your provider, your bill</div>
<div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
Add an OpenAI-compatible endpoint in Settings and every hosted feature runs on your own key. It never touches your included allowance, so you can keep going as long as you like.
</div>
</div>
<a class="btn small" href="#/settings">Open Settings</a>
</div>
</div>
${cloud.isDev &&
html`<div class="section-head"><h2 class="section-title">Developer</h2></div>
<div class="card">
<div class="row between wrap">
<div style=${{ maxWidth: "520px" }}>
<div style=${{ fontWeight: 600 }}>Developer console</div>
<div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>Plans and prices, PayPal, models and keys, page wording, and who has access.</div>
</div>
<a class="btn primary small" href="#/developer">Open developer console</a>
</div>
</div>`}
<//>`;
}
// ---------------------------------------------------------------------------
// Landing screens for email links
// ---------------------------------------------------------------------------
const WELCOME_COPY = {
signup: {
eyebrow: "Account confirmed",
title: "You're in.",
body: "Your email is confirmed and you're signed in. Your plan, budget and downloads stay with this account."
},
magiclink: {
eyebrow: "Signed in",
title: "You're signed in.",
body: "The link worked — no password needed."
},
email_change: {
eyebrow: "Address updated",
title: "That's your new address.",
body: "Your sign-in address has changed, and you're already signed in with it."
},
session: {
eyebrow: "Signed in",
title: "You're in.",
body: "The link worked and you're signed in."
}
};
function CentredCard({ children }) {
return html`<div class="card" style=${{ maxWidth: "460px", margin: "7vh auto 0", textAlign: "center", padding: "28px 26px" }}>${children}</div>`;
}
function Tick({ tone = "good" }) {
const good = tone === "good";
return html`<div style=${{
width: "56px", height: "56px", borderRadius: "50%",
background: good ? "var(--accent-soft)" : "var(--warning-soft)",
color: good ? "var(--accent-deep)" : "#7d4a1f",
display: "grid", placeItems: "center", margin: "0 auto 14px"
}}><${Icon} name=${good ? "check" : "x"} size=${26} stroke=${2.2} /></div>`;
}
function Waiting() {
return html`<${CentredCard}>
<span class="spin" style=${{ margin: "0 auto 14px" }}></span>
<div style=${{ fontWeight: 600, fontSize: "15px" }}>Signing you in…</div>
<p class="tiny faint" style=${{ marginTop: "4px" }}>Reading the link and setting up your session.</p>
<//>`;
}
// Where a confirmed sign-up, magic link or email change lands.
export function Welcome({ kind, onDone }) {
const cloud = useCloud();
const copy = WELCOME_COPY[kind] || WELCOME_COPY.magiclink;
if (!cloud.ready) {
return html`<${Shell}><${Waiting} /><//>`;
}
if (!cloud.configured) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} tone="bad" />
<h1 class="page-title" style=${{ fontSize: "26px" }}>No accounts yet.</h1>
<p class="subtitle">This copy of the site has no Supabase project, so there is no account to confirm.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<a class="btn primary" href="#/connect">Connect Supabase</a>
</div>
<//>
<//>`;
}
if (!cloud.user) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} tone="bad" />
<h1 class="page-title" style=${{ fontSize: "26px" }}>That link didn't sign you in.</h1>
<p class="subtitle">Email links work once and expire after an hour. Sign in with your password, or send yourself a fresh one from the sign-in page.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<button class="btn primary" onClick=${onDone}>Go to sign in</button>
</div>
<//>
<//>`;
}
return html`<${Shell}>
<${CentredCard}>
<${Tick} />
<div class="eyebrow">${copy.eyebrow}</div>
<h1 class="page-title" style=${{ fontSize: "30px", marginTop: "4px" }}>${copy.title}</h1>
<p class="subtitle">${copy.body}</p>
<p class="tiny faint" style=${{ marginTop: "8px" }}>Signed in as ${cloud.user.email}</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<button class="btn primary" onClick=${onDone}>Start marking</button>
</div>
<p class="tiny faint" style=${{ marginTop: "14px" }}><a href="#/pricing">See the plans</a></p>
<//>
<//>`;
}
// Where a password-reset or invite link lands. The link has already signed the
// person in; this screen is the missing step that sets the password.
export function NewPassword({ kind, onDone }) {
const cloud = useCloud();
const [password, setPassword] = useState("");
const [again, setAgain] = useState("");
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState("");
const submit = async (event) => {
event.preventDefault();
setError("");
if (password.length < 6) {
setError("Use at least six characters.");
return;
}
if (password !== again) {
setError("The two passwords don't match.");
return;
}
setBusy(true);
try {
await cloud.updatePassword(password);
setDone(true);
} catch (err) {
setError(err && err.message ? err.message : "The password could not be changed.");
}
setBusy(false);
};
if (!cloud.ready) {
return html`<${Shell}><${Waiting} /><//>`;
}
if (!cloud.configured) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} tone="bad" />
<h1 class="page-title" style=${{ fontSize: "26px" }}>No accounts yet.</h1>
<p class="subtitle">This copy of the site has no Supabase project, so there is no password to change.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<a class="btn primary" href="#/connect">Connect Supabase</a>
</div>
<//>
<//>`;
}
if (!cloud.user) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} tone="bad" />
<h1 class="page-title" style=${{ fontSize: "26px" }}>This link has expired.</h1>
<p class="subtitle">Password links work once and last an hour. Ask for a new one from the sign-in page.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<button class="btn primary" onClick=${onDone}>Back to sign in</button>
</div>
<//>
<//>`;
}
if (done) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} />
<div class="eyebrow">Password changed</div>
<h1 class="page-title" style=${{ fontSize: "28px", marginTop: "4px" }}>You're all set.</h1>
<p class="subtitle">Use your new password the next time you sign in.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<button class="btn primary" onClick=${onDone}>Go to my account</button>
</div>
<//>
<//>`;
}
return html`<${Shell}>
<${CentredCard}>
<div class="eyebrow">${kind === "invite" ? "Welcome" : "Password reset"}</div>
<h1 class="page-title" style=${{ fontSize: "28px", marginTop: "4px" }}>${kind === "invite" ? "Choose a password." : "Choose a new password."}</h1>
<p class="subtitle">${kind === "invite" ? "Set a password for " + cloud.user.email + " and you're in." : "You're signed in as " + cloud.user.email + ". Pick something you'll remember."}</p>
<form onSubmit=${submit} class="stack" style=${{ marginTop: "16px", textAlign: "left" }}>
<div class="field">
<label>New password</label>
<input class="input" type="password" value=${password} onInput=${(e) => setPassword(e.target.value)} autocomplete="new-password" placeholder="At least 6 characters" required />
</div>
<div class="field">
<label>One more time</label>
<input class="input" type="password" value=${again} onInput=${(e) => setAgain(e.target.value)} autocomplete="new-password" placeholder="Same password" required />
</div>
${error && html`<${Notice} kind="error">${error}<//>`}
<button class="btn primary" type="submit" disabled=${busy}>
${busy ? html`<span class="spin"></span>` : html`<${Icon} name="lock" size=${13} />`} Save password
</button>
</form>
<//>
<//>`;
}
// When Supabase itself reports the link is bad or used.
export function LinkProblem({ onDone }) {
return html`<${Shell}>
<${CentredCard}>
<${Tick} tone="bad" />
<h1 class="page-title" style=${{ fontSize: "26px" }}>That link has expired.</h1>
<p class="subtitle">Email links work once and last an hour. Ask for a fresh one from the sign-in page — it takes a moment.</p>
<div class="row" style=${{ justifyContent: "center", marginTop: "16px" }}>
<button class="btn primary" onClick=${onDone}>Back to sign in</button>
</div>
<//>
<//>`;
}
// ---------------------------------------------------------------------------
// Connect Supabase
// ---------------------------------------------------------------------------
export function Connect() {
const cloud = useCloud();
const [url, setUrl] = useState(cloud.configured ? cloud.config.url : "");
const [anonKey, setAnonKey] = useState(cloud.configured ? cloud.config.anonKey : "");
const [error, setError] = useState("");
const [done, setDone] = useState(false);
const [copied, setCopied] = useState(false);
const connect = async (event) => {
event.preventDefault();
setError("");
const clean = url.trim().replace(/\/+$/, "");
if (!/^https?:\/\/.+/.test(clean)) {
setError("The project URL looks like https://yourproject.supabase.co");
return;
}
if (anonKey.trim().length < 20) {
setError("Paste the anon public key from Supabase → Project Settings → API.");
return;
}
cloud.connect({ url: clean, anonKey: anonKey.trim() });
setDone(true);
};
const copySchema = async () => {
try {
const res = await fetch("supabase/schema.sql");
const text = await res.text();
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2400);
} catch {
setError("Could not copy the schema. Open supabase/schema.sql in the folder instead.");
}
};
if (done || (cloud.configured && !error)) {
return html`<${Shell}>
<div class="eyebrow">Connected</div>
<h1 class="page-title">Supabase is connected.</h1>
<p class="subtitle">
This browser now reads accounts, plans, models and page wording from ${cloud.config.url}.
</p>
<div class="card" style=${{ marginTop: "16px" }}>
<div class="row" style=${{ marginBottom: "8px" }}><${Pill} tone="green">Connected</${Pill}><span class="tiny faint mono">${cloud.config.url}</span></div>
<${Notice} kind="info">
Two things left in the Supabase dashboard: run the SQL in <span class="mono">supabase/schema.sql</span> in the SQL editor, then paste the same URL and key into <span class="mono">js/config.js</span> so every visitor gets them automatically.
<//>
<div class="row wrap" style=${{ marginTop: "10px" }}>
<button class="btn small" onClick=${copySchema}>${copied ? "Copied" : "Copy schema SQL"}</button>
<a class="btn small primary" href="SETUP.html" target="_blank" rel="noreferrer">Open the picture guide</a>
<a class="btn small" href="#/pricing">See the plans page</a>
<a class="btn small" href="#/developer">Developer console</a>
</div>
</div>
<p class="tiny faint" style=${{ marginTop: "12px" }}>
This setup screen disappears from the site once a project is connected. It stays available in Developer → Supabase.
</p>
<//>`;
}
return html`<${Shell}>
<div class="eyebrow">Setup</div>
<h1 class="page-title">Connect Supabase.</h1>
<p class="subtitle">
Supabase holds the accounts, the plans, the shared page wording and the model budgets. Create a free project, then paste two values from Project Settings → API.
</p>
<div class="card" style=${{ marginTop: "16px", maxWidth: "560px" }}>
<form class="stack" onSubmit=${connect}>
<div class="field">
<label>Project URL</label>
<input class="input" value=${url} onInput=${(e) => setUrl(e.target.value)} placeholder="https://abcdefgh.supabase.co" />
</div>
<div class="field">
<label>Anon public key</label>
<textarea class="textarea plain" style=${{ minHeight: "84px" }} value=${anonKey} onInput=${(e) => setAnonKey(e.target.value)} placeholder="eyJhbGciOi…"></textarea>
</div>
${error && html`<${Notice} kind="error">${error}<//>`}
<button class="btn primary" type="submit">Connect this site</button>
</form>
<div class="divider"></div>
<div class="tiny faint" style=${{ lineHeight: 1.6 }}>
Only the anon public key goes in the browser. It is safe to publish: row-level security in the schema stops anyone but ${DEVELOPER_EMAIL} from changing plans, models or wording. Never paste the service_role key here.
</div>
</div>
<p class="tiny faint" style=${{ marginTop: "12px" }}>
Full instructions: <a href="SETUP.html" target="_blank" rel="noreferrer">the picture guide</a>.
</p>
<//>`;
}