Anmeldung mit Google und Apple
Kunden und Team können sich zusätzlich mit Google oder Apple anmelden. Zugangsdaten werden im Admin unter Einstellungen → Anmeldung gepflegt, die Knöpfe erscheinen erst, wenn ein Anbieter eingerichtet und aktiv ist. Bestehende Konten werden über die bestätigte E-Mail-Adresse verknüpft. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
df2e3c3de8
commit
e0ab4f93f5
15 changed files with 462 additions and 3 deletions
20
prisma/migrations/20261019143000_social_login/migration.sql
Normal file
20
prisma/migrations/20261019143000_social_login/migration.sql
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
-- CreateTable
|
||||
CREATE TABLE "UserIdentity" (
|
||||
"id" TEXT NOT NULL,
|
||||
"provider" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL DEFAULT '',
|
||||
"userId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "UserIdentity_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "UserIdentity_userId_idx" ON "UserIdentity"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "UserIdentity_provider_subject_key" ON "UserIdentity"("provider", "subject");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "UserIdentity" ADD CONSTRAINT "UserIdentity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
|
@ -36,12 +36,29 @@ model User {
|
|||
newsletter Boolean @default(false)
|
||||
lastLoginAt DateTime?
|
||||
sessions Session[]
|
||||
identities UserIdentity[]
|
||||
orders Order[]
|
||||
addresses Address[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
// Verknüpfte Anmeldungen über Google oder Apple. Konten nur mit dieser Anmeldung haben passwordHash "".
|
||||
model UserIdentity {
|
||||
id String @id @default(cuid())
|
||||
// "google" oder "apple"
|
||||
provider String
|
||||
// Eindeutige Kennung beim Anbieter (sub)
|
||||
subject String
|
||||
email String @default("")
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([provider, subject])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
tokenHash String @unique
|
||||
|
|
|
|||
|
|
@ -2,17 +2,20 @@ import Link from "next/link";
|
|||
import { redirect } from "next/navigation";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { LoginForm } from "@/components/shop/AuthForms";
|
||||
import { SocialLogin, SocialLoginError } from "@/components/shop/SocialLogin";
|
||||
|
||||
export const metadata = { title: "Anmelden" };
|
||||
|
||||
export default async function LoginPage({ searchParams }: { searchParams: Promise<{ weiter?: string }> }) {
|
||||
const { weiter } = await searchParams;
|
||||
export default async function LoginPage({ searchParams }: { searchParams: Promise<{ weiter?: string; fehler?: string }> }) {
|
||||
const { weiter, fehler } = await searchParams;
|
||||
if (await getCurrentUser()) redirect(weiter ?? "/konto");
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-auth">
|
||||
<h1 className="display-lg sm-page__title">Anmelden</h1>
|
||||
<p className="body sm-page__lead">Schön, dass du wieder da bist.</p>
|
||||
<SocialLoginError code={fehler} />
|
||||
<SocialLogin next={weiter} />
|
||||
<LoginForm next={weiter} />
|
||||
<p className="body" style={{ marginTop: "var(--space-6)", textAlign: "center" }}>
|
||||
Noch kein Konto? <Link href={`/konto/registrieren${weiter ? `?weiter=${encodeURIComponent(weiter)}` : ""}`}>Jetzt erstellen</Link>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import Link from "next/link";
|
|||
import { redirect } from "next/navigation";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { RegisterForm } from "@/components/shop/AuthForms";
|
||||
import { SocialLogin } from "@/components/shop/SocialLogin";
|
||||
|
||||
export const metadata = { title: "Konto erstellen" };
|
||||
|
||||
|
|
@ -13,6 +14,7 @@ export default async function RegisterPage({ searchParams }: { searchParams: Pro
|
|||
<div className="sm-auth">
|
||||
<h1 className="display-lg sm-page__title">Konto erstellen</h1>
|
||||
<p className="body sm-page__lead">Bestellungen verfolgen und schneller bestellen.</p>
|
||||
<SocialLogin next={weiter} verb="fortfahren" />
|
||||
<RegisterForm next={weiter} email={email} />
|
||||
<p className="body" style={{ marginTop: "var(--space-6)", textAlign: "center" }}>
|
||||
Schon ein Konto? <Link href="/konto/anmelden">Anmelden</Link>
|
||||
|
|
|
|||
39
src/app/admin/(panel)/anmeldung/actions.ts
Normal file
39
src/app/admin/(panel)/anmeldung/actions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { assertPermission, audit } from "@/lib/auth";
|
||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||
import { getLoginProviders, isConfigured, saveLoginProviders, type LoginProviders } from "@/lib/social/config";
|
||||
import { isValidApplePrivateKey } from "@/lib/social/oauth";
|
||||
|
||||
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||
|
||||
export async function saveLoginSettings(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||
const user = await assertPermission("settings.edit");
|
||||
const current = await getLoginProviders();
|
||||
// Leere Geheimfelder behalten den gespeicherten Wert
|
||||
const keep = (v: string, old: string) => (v ? v : old);
|
||||
const privateKey = keep(str(fd, "applePrivateKey").replace(/\r\n/g, "\n"), current.apple.privateKey);
|
||||
if (privateKey && !isValidApplePrivateKey(privateKey))
|
||||
return fail("Der Apple-Schlüssel lässt sich nicht lesen. Füge den ganzen Inhalt der .p8-Datei ein, mit den Zeilen BEGIN und END.", { applePrivateKey: "Ungültiger Schlüssel" });
|
||||
|
||||
const next: LoginProviders = {
|
||||
google: {
|
||||
enabled: fd.get("googleEnabled") === "on",
|
||||
clientId: str(fd, "googleClientId"),
|
||||
clientSecret: fd.get("googleClear") === "on" ? "" : keep(str(fd, "googleClientSecret"), current.google.clientSecret),
|
||||
},
|
||||
apple: {
|
||||
enabled: fd.get("appleEnabled") === "on",
|
||||
servicesId: str(fd, "appleServicesId"),
|
||||
teamId: str(fd, "appleTeamId").toUpperCase(),
|
||||
keyId: str(fd, "appleKeyId").toUpperCase(),
|
||||
privateKey: fd.get("appleClear") === "on" ? "" : privateKey,
|
||||
},
|
||||
};
|
||||
if (next.google.enabled && !isConfigured("google", next)) return fail("Für Google brauchst du Client-ID und Client-Secret.");
|
||||
if (next.apple.enabled && !isConfigured("apple", next)) return fail("Für Apple brauchst du Services-ID, Team-ID, Key-ID und den Schlüssel.");
|
||||
await saveLoginProviders(next);
|
||||
await audit(user, "Anmeldung mit Google/Apple geändert", `Google: ${next.google.enabled ? "an" : "aus"}, Apple: ${next.apple.enabled ? "an" : "aus"}`);
|
||||
revalidatePath("/admin/anmeldung");
|
||||
return ok();
|
||||
}
|
||||
44
src/app/admin/(panel)/anmeldung/page.tsx
Normal file
44
src/app/admin/(panel)/anmeldung/page.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { requireAdmin } from "@/lib/auth";
|
||||
import { mask } from "@/lib/payments/credentials";
|
||||
import { callbackUrl, getLoginProviders, isConfigured } from "@/lib/social/config";
|
||||
import { Field, TextareaField } from "@/components/Field";
|
||||
import { AdminForm } from "@/components/admin/AdminForm";
|
||||
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
||||
import { saveLoginSettings } from "./actions";
|
||||
|
||||
export default async function LoginSettingsPage() {
|
||||
await requireAdmin("settings.edit");
|
||||
const c = await getLoginProviders();
|
||||
const status = (p: "google" | "apple") =>
|
||||
!isConfigured(p, c) ? <Pill tone="neutral">Nicht eingerichtet</Pill> : c[p].enabled ? <Pill tone="success">Aktiv</Pill> : <Pill tone="gold">Aus</Pill>;
|
||||
const domain = new URL(callbackUrl("apple")).host;
|
||||
return (
|
||||
<div className="ad-wrap ad-wrap--narrow">
|
||||
<PageHead title="Anmeldung" lead="Kunden und Team können sich zusätzlich mit Google oder Apple anmelden. Gibt es zur E-Mail-Adresse schon ein Konto, wird es verknüpft." />
|
||||
<AdminForm action={saveLoginSettings}>
|
||||
<Card title="Google" lead="„Mit Google anmelden“ auf den Anmelde- und Registrierungsseiten." action={status("google")}>
|
||||
<Switch name="googleEnabled" label="Im Shop anbieten" defaultChecked={c.google.enabled} />
|
||||
<Field label="Client-ID" name="googleClientId" defaultValue={c.google.clientId} placeholder="…apps.googleusercontent.com" />
|
||||
<Field label="Client-Secret" name="googleClientSecret" type="password" autoComplete="off" placeholder={c.google.clientSecret ? mask(c.google.clientSecret) : "GOCSPX-…"} hint={c.google.clientSecret ? "Leer lassen, um das gespeicherte Secret zu behalten." : undefined} />
|
||||
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
|
||||
In der Google Cloud Console unter APIs & Dienste → Anmeldedaten eine OAuth-Client-ID vom Typ „Webanwendung“ anlegen. Als autorisierte Weiterleitungs-URI eintragen: <code>{callbackUrl("google")}</code>
|
||||
</div>
|
||||
{c.google.clientSecret && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="googleClear" /><span className="sm-check__text">Google-Verbindung entfernen</span></label>}
|
||||
</Card>
|
||||
<Card title="Apple" lead="„Mit Apple anmelden“. Braucht ein Apple-Developer-Konto." action={status("apple")}>
|
||||
<Switch name="appleEnabled" label="Im Shop anbieten" defaultChecked={c.apple.enabled} />
|
||||
<Field label="Services-ID" name="appleServicesId" defaultValue={c.apple.servicesId} placeholder="de.sanamare.login" hint="Die Kennung der Services-ID, nicht die der App." />
|
||||
<div className="sm-form-row">
|
||||
<Field label="Team-ID" name="appleTeamId" defaultValue={c.apple.teamId} placeholder="ABCDE12345" />
|
||||
<Field label="Key-ID" name="appleKeyId" defaultValue={c.apple.keyId} placeholder="XYZ987WVU6" />
|
||||
</div>
|
||||
<TextareaField label="Schlüssel (.p8-Datei)" name="applePrivateKey" rows={4} placeholder={c.apple.privateKey ? "Gespeichert. Leer lassen, um ihn zu behalten." : "-----BEGIN PRIVATE KEY-----\n…\n-----END PRIVATE KEY-----"} hint="Den ganzen Inhalt der heruntergeladenen .p8-Datei einfügen." />
|
||||
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
|
||||
Im Apple-Developer-Bereich unter Certificates, Identifiers & Profiles: eine Services-ID mit „Sign in with Apple“ anlegen, als Domain <code>{domain}</code> und als Return-URL <code>{callbackUrl("apple")}</code> eintragen. Danach unter Keys einen Schlüssel mit „Sign in with Apple“ erstellen und die .p8-Datei herunterladen.
|
||||
</div>
|
||||
{c.apple.privateKey && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="appleClear" /><span className="sm-check__text">Apple-Verbindung entfernen</span></label>}
|
||||
</Card>
|
||||
</AdminForm>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -2,11 +2,13 @@ import { redirect } from "next/navigation";
|
|||
import "@/styles/admin.css";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { LoginForm } from "@/components/shop/AuthForms";
|
||||
import { SocialLogin, SocialLoginError } from "@/components/shop/SocialLogin";
|
||||
|
||||
export const metadata = { title: "Admin – Anmelden", robots: { index: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminLogin() {
|
||||
export default async function AdminLogin({ searchParams }: { searchParams: Promise<{ fehler?: string }> }) {
|
||||
const { fehler } = await searchParams;
|
||||
const user = await getCurrentUser();
|
||||
if (user?.role) redirect("/admin");
|
||||
return (
|
||||
|
|
@ -18,6 +20,8 @@ export default async function AdminLogin() {
|
|||
<div className="ad-card__body">
|
||||
<h1 className="display-sm" style={{ marginBottom: "var(--space-2)" }}>Verwaltung</h1>
|
||||
<p className="body-sm ad-muted" style={{ marginTop: 0, marginBottom: "var(--space-5)" }}>Melde dich mit deinem Team-Zugang an.</p>
|
||||
<SocialLoginError code={fehler} />
|
||||
<SocialLogin area="admin" />
|
||||
<LoginForm area="admin" />
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
64
src/app/api/auth/[provider]/callback/route.ts
Normal file
64
src/app/api/auth/[provider]/callback/route.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { createSession } from "@/lib/auth";
|
||||
import { appUrl, getLoginProviders, isConfigured } from "@/lib/social/config";
|
||||
import { exchangeCode, findOrCreateUser, FLOW_COOKIE, SocialLoginError, type Flow } from "@/lib/social/oauth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Google kommt per GET zurück, Apple per POST (form_post)
|
||||
export const GET = (req: Request, ctx: Ctx) => handle(req, ctx, new URL(req.url).searchParams);
|
||||
export const POST = async (req: Request, ctx: Ctx) => handle(req, ctx, new URLSearchParams([...(await req.formData()).entries()].map(([k, v]) => [k, String(v)])));
|
||||
|
||||
type Ctx = { params: Promise<{ provider: string }> };
|
||||
|
||||
async function handle(_req: Request, { params }: Ctx, q: URLSearchParams) {
|
||||
const { provider } = await params;
|
||||
const jar = await cookies();
|
||||
const raw = jar.get(FLOW_COOKIE)?.value;
|
||||
jar.delete({ name: FLOW_COOKIE, path: "/api/auth" });
|
||||
|
||||
let flow: Flow | null = null;
|
||||
try {
|
||||
flow = raw ? (JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as Flow) : null;
|
||||
} catch {
|
||||
flow = null;
|
||||
}
|
||||
const admin = flow?.area === "admin";
|
||||
const fail = (code: string) => {
|
||||
const target = admin ? "/admin/login" : "/konto/anmelden";
|
||||
const extra = !admin && flow?.next ? `&weiter=${encodeURIComponent(flow.next)}` : "";
|
||||
return NextResponse.redirect(`${appUrl()}${target}?fehler=${code}${extra}`, 303);
|
||||
};
|
||||
|
||||
// Abgebrochen (Google: access_denied, Apple: user_cancelled_authorize)
|
||||
if (q.get("error")) return fail("abgebrochen");
|
||||
if (!flow || flow.provider !== provider || !q.get("state") || q.get("state") !== flow.state) return fail("abgelaufen");
|
||||
const code = q.get("code");
|
||||
if (!code) return fail("abgebrochen");
|
||||
|
||||
const c = await getLoginProviders();
|
||||
if (!c[flow.provider].enabled || !isConfigured(flow.provider, c)) return fail("aus");
|
||||
|
||||
let user;
|
||||
try {
|
||||
const profile = await exchangeCode(flow, code, c);
|
||||
// Apple schickt den Namen nur beim ersten Mal, und zwar außerhalb des Tokens
|
||||
if (flow.provider === "apple" && q.get("user")) {
|
||||
try {
|
||||
const u = JSON.parse(q.get("user") ?? "{}");
|
||||
profile.firstName ||= String(u?.name?.firstName ?? "");
|
||||
profile.lastName ||= String(u?.name?.lastName ?? "");
|
||||
} catch {}
|
||||
}
|
||||
user = await findOrCreateUser(flow.provider, profile);
|
||||
} catch (e) {
|
||||
if (e instanceof SocialLoginError) return fail(e.code);
|
||||
console.error(`Anmeldung mit ${flow.provider} fehlgeschlagen:`, e);
|
||||
return fail("fehler");
|
||||
}
|
||||
|
||||
if (admin && !user.role) return fail("kein-admin");
|
||||
await createSession(user.id);
|
||||
return NextResponse.redirect(`${appUrl()}${flow.next || (admin ? "/admin" : "/konto")}`, 303);
|
||||
}
|
||||
31
src/app/api/auth/[provider]/route.ts
Normal file
31
src/app/api/auth/[provider]/route.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { appUrl, getLoginProviders, isConfigured, type SocialProvider } from "@/lib/social/config";
|
||||
import { authorizeUrl, FLOW_COOKIE, newFlow } from "@/lib/social/oauth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Startet die Anmeldung: /api/auth/google?weiter=/kasse oder /api/auth/apple?area=admin
|
||||
export async function GET(req: Request, { params }: { params: Promise<{ provider: string }> }) {
|
||||
const { provider } = await params;
|
||||
const url = new URL(req.url);
|
||||
const area = url.searchParams.get("area") === "admin" ? "admin" : "";
|
||||
const back = area ? "/admin/login" : "/konto/anmelden";
|
||||
if (provider !== "google" && provider !== "apple") return NextResponse.redirect(`${appUrl()}${back}`, 303);
|
||||
const c = await getLoginProviders();
|
||||
if (!c[provider].enabled || !isConfigured(provider, c)) return NextResponse.redirect(`${appUrl()}${back}?fehler=aus`, 303);
|
||||
|
||||
const weiter = url.searchParams.get("weiter") ?? "";
|
||||
const next = weiter.startsWith("/") && !weiter.startsWith("//") ? weiter : "";
|
||||
const flow = newFlow(provider as SocialProvider, next, area);
|
||||
const secure = appUrl().startsWith("https://");
|
||||
// Apple kommt per POST von appleid.apple.com zurück, das Cookie muss deshalb auch seitenübergreifend mitkommen
|
||||
(await cookies()).set(FLOW_COOKIE, Buffer.from(JSON.stringify(flow)).toString("base64url"), {
|
||||
httpOnly: true,
|
||||
secure,
|
||||
sameSite: secure ? "none" : "lax",
|
||||
path: "/api/auth",
|
||||
maxAge: 600,
|
||||
});
|
||||
return NextResponse.redirect(authorizeUrl(flow, c), 303);
|
||||
}
|
||||
|
|
@ -37,6 +37,7 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
|||
{ href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" },
|
||||
{ href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" },
|
||||
{ href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" },
|
||||
{ href: "/admin/anmeldung", label: "Anmeldung", icon: "lock", permission: "settings.edit" },
|
||||
{ href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" },
|
||||
{ href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" },
|
||||
{ href: "/admin/protokoll", label: "Protokoll", icon: "history", permission: "audit.view" },
|
||||
|
|
|
|||
52
src/components/shop/SocialLogin.tsx
Normal file
52
src/components/shop/SocialLogin.tsx
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { getActiveProviders } from "@/lib/social/config";
|
||||
import { Alert } from "./Blocks";
|
||||
|
||||
const ERRORS: Record<string, string> = {
|
||||
abgebrochen: "Die Anmeldung wurde abgebrochen.",
|
||||
abgelaufen: "Die Anmeldung hat zu lange gedauert. Bitte versuch es noch einmal.",
|
||||
aus: "Diese Anmeldung ist gerade nicht verfügbar.",
|
||||
"no-email": "Der Anbieter hat uns keine E-Mail-Adresse übermittelt. Bitte melde dich mit E-Mail und Passwort an.",
|
||||
unverified: "Zu dieser E-Mail-Adresse gibt es schon ein Konto. Bitte melde dich mit deinem Passwort an.",
|
||||
inactive: "Dieses Konto ist gesperrt.",
|
||||
"kein-admin": "Dieses Konto hat keinen Zugang zum Admin-Bereich.",
|
||||
fehler: "Die Anmeldung hat nicht geklappt. Bitte versuch es noch einmal.",
|
||||
};
|
||||
|
||||
export function SocialLoginError({ code }: { code?: string }) {
|
||||
if (!code) return null;
|
||||
return <div style={{ marginBottom: "var(--space-4)" }}><Alert kind="danger" title={ERRORS[code] ?? ERRORS.fehler} /></div>;
|
||||
}
|
||||
|
||||
/** Knöpfe „Mit Google / Apple anmelden“. Erscheinen nur, wenn der Anbieter im Admin eingerichtet ist. */
|
||||
export async function SocialLogin({ next, area, verb = "anmelden" }: { next?: string; area?: "admin"; verb?: "anmelden" | "fortfahren" }) {
|
||||
const providers = await getActiveProviders();
|
||||
if (providers.length === 0) return null;
|
||||
const q = new URLSearchParams();
|
||||
if (next) q.set("weiter", next);
|
||||
if (area) q.set("area", area);
|
||||
const qs = q.size ? `?${q}` : "";
|
||||
return (
|
||||
<div className="sm-social">
|
||||
{providers.includes("google") && (
|
||||
<a className="sm-btn sm-btn--secondary sm-btn--lg sm-btn--block sm-social__btn" href={`/api/auth/google${qs}`}>
|
||||
<svg viewBox="0 0 48 48" width="20" height="20" aria-hidden="true">
|
||||
<path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
|
||||
<path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
|
||||
<path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
|
||||
<path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
|
||||
</svg>
|
||||
Mit Google {verb}
|
||||
</a>
|
||||
)}
|
||||
{providers.includes("apple") && (
|
||||
<a className="sm-btn sm-btn--primary sm-btn--lg sm-btn--block sm-social__btn sm-social__btn--apple" href={`/api/auth/apple${qs}`}>
|
||||
<svg viewBox="0 0 814 1000" width="18" height="18" aria-hidden="true" fill="currentColor">
|
||||
<path d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z" />
|
||||
</svg>
|
||||
Mit Apple {verb}
|
||||
</a>
|
||||
)}
|
||||
<div className="sm-social__or"><span>oder mit E-Mail</span></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ export async function login(_prev: AuthState, formData: FormData): Promise<AuthS
|
|||
const a = attempts.get(email);
|
||||
if (a && a.until > Date.now()) return { error: "Zu viele Versuche. Bitte warte eine Minute." };
|
||||
const user = await db.user.findUnique({ where: { email }, include: { role: true } });
|
||||
if (user?.active && !user.passwordHash) return { error: "Dieses Konto nutzt die Anmeldung mit Google oder Apple." };
|
||||
if (!user || !user.active || !(await verifyPassword(password, user.passwordHash))) {
|
||||
const n = (a?.n ?? 0) + 1;
|
||||
attempts.set(email, { n, until: n >= 5 ? Date.now() + 60_000 : 0 });
|
||||
|
|
|
|||
43
src/lib/social/config.ts
Normal file
43
src/lib/social/config.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import "server-only";
|
||||
import { db } from "../db";
|
||||
|
||||
export type SocialProvider = "google" | "apple";
|
||||
|
||||
export type LoginProviders = {
|
||||
google: { enabled: boolean; clientId: string; clientSecret: string };
|
||||
apple: { enabled: boolean; servicesId: string; teamId: string; keyId: string; privateKey: string };
|
||||
};
|
||||
|
||||
const DEFAULTS: LoginProviders = {
|
||||
google: { enabled: false, clientId: "", clientSecret: "" },
|
||||
apple: { enabled: false, servicesId: "", teamId: "", keyId: "", privateKey: "" },
|
||||
};
|
||||
|
||||
const KEY = "login_providers";
|
||||
|
||||
export async function getLoginProviders(): Promise<LoginProviders> {
|
||||
const row = await db.setting.findUnique({ where: { key: KEY } });
|
||||
const value = (row?.value ?? {}) as Partial<LoginProviders>;
|
||||
return {
|
||||
google: { ...DEFAULTS.google, ...(value.google ?? {}) },
|
||||
apple: { ...DEFAULTS.apple, ...(value.apple ?? {}) },
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveLoginProviders(value: LoginProviders) {
|
||||
await db.setting.upsert({ where: { key: KEY }, create: { key: KEY, value }, update: { value } });
|
||||
}
|
||||
|
||||
export function isConfigured(provider: SocialProvider, c: LoginProviders) {
|
||||
if (provider === "google") return Boolean(c.google.clientId && c.google.clientSecret);
|
||||
return Boolean(c.apple.servicesId && c.apple.teamId && c.apple.keyId && c.apple.privateKey);
|
||||
}
|
||||
|
||||
/** Anbieter, deren Knöpfe im Shop erscheinen: eingeschaltet und vollständig eingerichtet. */
|
||||
export async function getActiveProviders(): Promise<SocialProvider[]> {
|
||||
const c = await getLoginProviders();
|
||||
return (["google", "apple"] as const).filter((p) => c[p].enabled && isConfigured(p, c));
|
||||
}
|
||||
|
||||
export const appUrl = () => (process.env.APP_URL ?? "https://sanamare.maaxxs-coding.de").replace(/\/$/, "");
|
||||
export const callbackUrl = (provider: SocialProvider) => `${appUrl()}/api/auth/${provider}/callback`;
|
||||
130
src/lib/social/oauth.ts
Normal file
130
src/lib/social/oauth.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import "server-only";
|
||||
import { createHash, createPrivateKey, randomBytes, sign } from "node:crypto";
|
||||
import { db } from "../db";
|
||||
import { callbackUrl, type LoginProviders, type SocialProvider } from "./config";
|
||||
|
||||
// Zwischenspeicher für den Weg zum Anbieter und zurück (state, nonce, PKCE, Ziel)
|
||||
export const FLOW_COOKIE = "sm_oauth";
|
||||
export type Flow = { provider: SocialProvider; state: string; nonce: string; verifier: string; next: string; area: string };
|
||||
|
||||
const b64url = (b: Buffer | string) => Buffer.from(b).toString("base64url");
|
||||
const random = () => randomBytes(32).toString("base64url");
|
||||
|
||||
export function newFlow(provider: SocialProvider, next: string, area: string): Flow {
|
||||
return { provider, state: random(), nonce: random(), verifier: random(), next, area };
|
||||
}
|
||||
|
||||
export function authorizeUrl(flow: Flow, c: LoginProviders): string {
|
||||
if (flow.provider === "google") {
|
||||
const q = new URLSearchParams({
|
||||
client_id: c.google.clientId,
|
||||
redirect_uri: callbackUrl("google"),
|
||||
response_type: "code",
|
||||
scope: "openid email profile",
|
||||
state: flow.state,
|
||||
nonce: flow.nonce,
|
||||
code_challenge: b64url(createHash("sha256").update(flow.verifier).digest()),
|
||||
code_challenge_method: "S256",
|
||||
prompt: "select_account",
|
||||
});
|
||||
return `https://accounts.google.com/o/oauth2/v2/auth?${q}`;
|
||||
}
|
||||
// Apple schickt Name und E-Mail nur per form_post zurück
|
||||
const q = new URLSearchParams({
|
||||
client_id: c.apple.servicesId,
|
||||
redirect_uri: callbackUrl("apple"),
|
||||
response_type: "code",
|
||||
response_mode: "form_post",
|
||||
scope: "name email",
|
||||
state: flow.state,
|
||||
nonce: flow.nonce,
|
||||
});
|
||||
return `https://appleid.apple.com/auth/authorize?${q}`;
|
||||
}
|
||||
|
||||
/** Prüft, ob der eingefügte .p8-Schlüssel von Apple lesbar ist. */
|
||||
export function isValidApplePrivateKey(pem: string) {
|
||||
try {
|
||||
return createPrivateKey(pem).asymmetricKeyType === "ec";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Apple verlangt als Client-Secret ein mit dem .p8-Schlüssel signiertes JWT (ES256). */
|
||||
function appleClientSecret(c: LoginProviders["apple"]) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const header = b64url(JSON.stringify({ alg: "ES256", kid: c.keyId }));
|
||||
const claims = b64url(JSON.stringify({ iss: c.teamId, iat: now, exp: now + 300, aud: "https://appleid.apple.com", sub: c.servicesId }));
|
||||
const signature = sign("sha256", Buffer.from(`${header}.${claims}`), { key: createPrivateKey(c.privateKey), dsaEncoding: "ieee-p1363" });
|
||||
return `${header}.${claims}.${b64url(signature)}`;
|
||||
}
|
||||
|
||||
export type SocialProfile = { subject: string; email: string; emailVerified: boolean; firstName: string; lastName: string };
|
||||
|
||||
/** Tauscht den Code gegen ein ID-Token und liest daraus das Profil. */
|
||||
export async function exchangeCode(flow: Flow, code: string, c: LoginProviders): Promise<SocialProfile> {
|
||||
const google = flow.provider === "google";
|
||||
const body = google
|
||||
? new URLSearchParams({ code, client_id: c.google.clientId, client_secret: c.google.clientSecret, redirect_uri: callbackUrl("google"), grant_type: "authorization_code", code_verifier: flow.verifier })
|
||||
: new URLSearchParams({ code, client_id: c.apple.servicesId, client_secret: appleClientSecret(c.apple), redirect_uri: callbackUrl("apple"), grant_type: "authorization_code" });
|
||||
const res = await fetch(google ? "https://oauth2.googleapis.com/token" : "https://appleid.apple.com/auth/token", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
||||
body,
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || typeof data.id_token !== "string") throw new Error(`Token-Abruf fehlgeschlagen: ${data.error_description ?? data.error ?? res.status}`);
|
||||
|
||||
// Das Token kommt direkt per TLS vom Anbieter, deshalb reicht die Prüfung der Angaben (OpenID Connect Core 3.1.3.7)
|
||||
const claims = JSON.parse(Buffer.from(data.id_token.split(".")[1] ?? "", "base64url").toString("utf8"));
|
||||
const issuers = google ? ["https://accounts.google.com", "accounts.google.com"] : ["https://appleid.apple.com"];
|
||||
const audience = google ? c.google.clientId : c.apple.servicesId;
|
||||
const aud: string[] = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
||||
if (!issuers.includes(claims.iss) || !aud.includes(audience)) throw new Error("ID-Token gehört nicht zu diesem Shop.");
|
||||
if (typeof claims.exp !== "number" || claims.exp * 1000 < Date.now()) throw new Error("ID-Token ist abgelaufen.");
|
||||
if (claims.nonce !== flow.nonce) throw new Error("ID-Token passt nicht zur Anmeldung.");
|
||||
if (!claims.sub) throw new Error("ID-Token ohne Kennung.");
|
||||
|
||||
return {
|
||||
subject: String(claims.sub),
|
||||
email: String(claims.email ?? "").trim().toLowerCase(),
|
||||
emailVerified: claims.email_verified === true || claims.email_verified === "true",
|
||||
firstName: String(claims.given_name ?? ""),
|
||||
lastName: String(claims.family_name ?? ""),
|
||||
};
|
||||
}
|
||||
|
||||
export class SocialLoginError extends Error {
|
||||
constructor(public code: "no-email" | "inactive" | "unverified") {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
/** Findet das passende Konto, verknüpft es per E-Mail-Adresse oder legt ein neues Kundenkonto an. */
|
||||
export async function findOrCreateUser(provider: SocialProvider, p: SocialProfile) {
|
||||
const identity = await db.userIdentity.findUnique({ where: { provider_subject: { provider, subject: p.subject } }, include: { user: true } });
|
||||
let user = identity?.user ?? null;
|
||||
|
||||
if (!user) {
|
||||
if (!p.email) throw new SocialLoginError("no-email");
|
||||
const existing = await db.user.findUnique({ where: { email: p.email } });
|
||||
if (existing) {
|
||||
// Nur mit bestätigter Adresse verknüpfen, sonst könnte jemand fremde Konten übernehmen
|
||||
if (!p.emailVerified) throw new SocialLoginError("unverified");
|
||||
user = existing;
|
||||
} else {
|
||||
user = await db.user.create({ data: { email: p.email, firstName: p.firstName, lastName: p.lastName, passwordHash: "" } });
|
||||
await db.order.updateMany({ where: { email: user.email, userId: null }, data: { userId: user.id } });
|
||||
}
|
||||
await db.userIdentity.create({ data: { provider, subject: p.subject, email: p.email, userId: user.id } });
|
||||
}
|
||||
|
||||
if (!user.active) throw new SocialLoginError("inactive");
|
||||
// Apple nennt den Namen nur beim allerersten Mal, fehlende Angaben ergänzen
|
||||
if ((!user.firstName && p.firstName) || (!user.lastName && p.lastName)) {
|
||||
user = await db.user.update({ where: { id: user.id }, data: { firstName: user.firstName || p.firstName, lastName: user.lastName || p.lastName } });
|
||||
}
|
||||
return db.user.findUniqueOrThrow({ where: { id: user.id }, include: { role: true } });
|
||||
}
|
||||
|
|
@ -85,3 +85,11 @@ h1, h2, h3 { margin: 0; }
|
|||
.sm-pdp__sizes input:disabled + label.sm-pdp__size { color: var(--ink-subtle); border-color: var(--line); text-decoration: line-through; cursor: not-allowed; background: var(--surface); }
|
||||
.sm-pdp__thumb img { aspect-ratio: var(--product-image-ratio); object-fit: cover; width: 100%; }
|
||||
@media (max-width: 1023px) { .sm-pdp__buy { position: static; } .sm-pdp__cta .sm-btn--primary { min-height: var(--control-height-lg); } }
|
||||
|
||||
/* Anmeldung mit Google / Apple */
|
||||
.sm-social { display: grid; gap: var(--space-3); margin-bottom: var(--space-5); }
|
||||
.sm-social__btn { gap: var(--space-3); text-decoration: none; }
|
||||
.sm-social__btn--apple { background: #000; border-color: #000; color: #fff; }
|
||||
.sm-social__btn--apple:hover { background: #1f1f1f; border-color: #1f1f1f; }
|
||||
.sm-social__or { display: flex; align-items: center; gap: var(--space-3); margin-top: var(--space-2); color: var(--ink-muted); font-size: 14px; }
|
||||
.sm-social__or::before, .sm-social__or::after { content: ""; flex: 1; border-top: var(--hairline) solid var(--line); }
|
||||
|
|
|
|||
Loading…
Reference in a new issue