Mehrere Domains: Zahlungs- und Anmelde-Rückleitungen gehen auf die aufgerufene Domain, weitere Domains über APP_ALIASES
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
parent
e376fa8877
commit
9f73828486
10 changed files with 64 additions and 26 deletions
|
|
@ -2,6 +2,8 @@
|
|||
DATABASE_URL="postgresql://sanamare:CHANGE_ME@db:5432/sanamare"
|
||||
# Öffentliche Adresse des Shops (für Zahlungs-Rückleitungen)
|
||||
APP_URL="https://sanamare.maaxxs-coding.de"
|
||||
# Weitere Domains, unter denen derselbe Shop erreichbar ist (kommagetrennt)
|
||||
APP_ALIASES=
|
||||
# Ordner für hochgeladene Bilder
|
||||
UPLOAD_DIR="/app/uploads"
|
||||
# Erster Inhaber-Zugang (nur beim ersten Seed)
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ services:
|
|||
environment:
|
||||
DATABASE_URL: postgresql://sanamare:${DB_PASSWORD}@db:5432/sanamare
|
||||
APP_URL: ${APP_URL:-https://sanamare.maaxxs-coding.de}
|
||||
# Weitere Domains für denselben Shop, kommagetrennt (z. B. https://sanamare.de)
|
||||
APP_ALIASES: ${APP_ALIASES:-}
|
||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@sanamare.de}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD in .env setzen}
|
||||
volumes:
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
"use server";
|
||||
import { requestOrigin } from "@/lib/social/config";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
|
|
@ -111,7 +112,8 @@ export async function placeOrder(_prev: FormState, formData: FormData): Promise<
|
|||
jar.set("sm_last_order", order.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 });
|
||||
|
||||
const def = getDefinition(payment.code);
|
||||
const appUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
|
||||
// Nach der Zahlung zurück auf die Domain, auf der bestellt wurde
|
||||
const appUrl = await requestOrigin();
|
||||
let target: string;
|
||||
try {
|
||||
if (def?.provider === "stripe") {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { notFound } from "next/navigation";
|
|||
import { requireAdmin } from "@/lib/auth";
|
||||
import { getCredentials, mask } from "@/lib/payments/credentials";
|
||||
import { getDhlConfig } from "@/lib/dhl";
|
||||
import { appUrl, callbackUrl, getLoginProviders } from "@/lib/social/config";
|
||||
import { callbackUrl, getLoginProviders, siteOrigins } from "@/lib/social/config";
|
||||
import { INTEGRATIONS, STRIPE_WEBHOOK_EVENTS, getStatuses, stripeWebhookUrl, type IntegrationKey, type TestResult } from "@/lib/integrations";
|
||||
import { dateFmt } from "@/lib/status";
|
||||
import { Field } from "@/components/Field";
|
||||
|
|
@ -202,10 +202,10 @@ async function GoogleWizard({ ok }: { ok: boolean }) {
|
|||
<OpenLink href="https://console.cloud.google.com/auth/audience">Zielgruppe</OpenLink>
|
||||
</Step>
|
||||
<Step n={3} title="OAuth-Client anlegen" done={ok && has}>
|
||||
<p>Neuen Client vom Typ „Webanwendung“ erstellen und diese zwei Werte eintragen:</p>
|
||||
<p>Neuen Client vom Typ „Webanwendung“ erstellen und diese Werte eintragen{siteOrigins().length > 1 ? " (bei mehreren Domains jede Zeile als eigenen Eintrag)" : ""}:</p>
|
||||
<OpenLink href="https://console.cloud.google.com/auth/clients/create">Client erstellen</OpenLink>
|
||||
<CopyValue label="Autorisierte JavaScript-Quelle" value={appUrl()} />
|
||||
<CopyValue label="Autorisierte Weiterleitungs-URI" value={callbackUrl("google")} />
|
||||
{siteOrigins().map((o) => <CopyValue key={o} label="Autorisierte JavaScript-Quelle" value={o} />)}
|
||||
{siteOrigins().map((o) => <CopyValue key={o} label="Autorisierte Weiterleitungs-URI" value={callbackUrl("google", o)} />)}
|
||||
</Step>
|
||||
<Step n={4} title="Client-ID und Secret einfügen" done={ok && has}>
|
||||
<p>Nach dem Erstellen zeigt Google beide Werte an.</p>
|
||||
|
|
@ -227,7 +227,6 @@ async function GoogleWizard({ ok }: { ok: boolean }) {
|
|||
async function AppleWizard({ ok }: { ok: boolean }) {
|
||||
const c = (await getLoginProviders()).apple;
|
||||
const has = Boolean(c.servicesId && c.teamId && c.keyId && c.privateKey);
|
||||
const domain = new URL(callbackUrl("apple")).host;
|
||||
return (
|
||||
<AdminForm action={saveApple} submitLabel="Speichern und testen">
|
||||
<Card>
|
||||
|
|
@ -245,8 +244,8 @@ async function AppleWizard({ ok }: { ok: boolean }) {
|
|||
<Step n={3} title="Services-ID anlegen" done={ok && has}>
|
||||
<p>Neue Services-ID anlegen, z. B. <code>de.sanamare.login</code>. Danach „Sign in with Apple“ ankreuzen, auf „Configure“ klicken, die App-ID aus Schritt 2 wählen und diese Werte eintragen:</p>
|
||||
<OpenLink href="https://developer.apple.com/account/resources/identifiers/add/serviceId">Services-ID anlegen</OpenLink>
|
||||
<CopyValue label="Domain" value={domain} />
|
||||
<CopyValue label="Return-URL" value={callbackUrl("apple")} />
|
||||
{siteOrigins().map((o) => <CopyValue key={o} label="Domain" value={new URL(o).host} />)}
|
||||
{siteOrigins().map((o) => <CopyValue key={o} label="Return-URL" value={callbackUrl("apple", o)} />)}
|
||||
<Field label="Services-ID" name="servicesId" defaultValue={c.servicesId} placeholder="de.sanamare.login" autoComplete="off" />
|
||||
</Step>
|
||||
<Step n={4} title="Schlüssel erstellen" done={ok && has}>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { createSession } from "@/lib/auth";
|
||||
import { appUrl, getLoginProviders, isConfigured } from "@/lib/social/config";
|
||||
import { getLoginProviders, isConfigured, requestOrigin, siteOrigins } from "@/lib/social/config";
|
||||
import { exchangeCode, findOrCreateUser, FLOW_COOKIE, SocialLoginError, type Flow } from "@/lib/social/oauth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
|
@ -25,10 +25,13 @@ async function handle(_req: Request, { params }: Ctx, q: URLSearchParams) {
|
|||
flow = null;
|
||||
}
|
||||
const admin = flow?.area === "admin";
|
||||
const here = await requestOrigin();
|
||||
if (flow && (!flow.origin || !siteOrigins().includes(flow.origin))) flow.origin = here;
|
||||
const origin = flow?.origin ?? here;
|
||||
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);
|
||||
return NextResponse.redirect(`${origin}${target}?fehler=${code}${extra}`, 303);
|
||||
};
|
||||
|
||||
// Abgebrochen (Google: access_denied, Apple: user_cancelled_authorize)
|
||||
|
|
@ -60,5 +63,5 @@ async function handle(_req: Request, { params }: Ctx, q: URLSearchParams) {
|
|||
|
||||
if (admin && !user.role) return fail("kein-admin");
|
||||
await createSession(user.id);
|
||||
return NextResponse.redirect(`${appUrl()}${flow.next || (admin ? "/admin" : "/konto")}`, 303);
|
||||
return NextResponse.redirect(`${origin}${flow.next || (admin ? "/admin" : "/konto")}`, 303);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { appUrl, getLoginProviders, isConfigured, type SocialProvider } from "@/lib/social/config";
|
||||
import { getLoginProviders, isConfigured, requestOrigin, type SocialProvider } from "@/lib/social/config";
|
||||
import { authorizeUrl, FLOW_COOKIE, newFlow } from "@/lib/social/oauth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
|
@ -11,14 +11,16 @@ export async function GET(req: Request, { params }: { params: Promise<{ provider
|
|||
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);
|
||||
// Zurück auf dieselbe Domain, auf der die Anmeldung beginnt (das Cookie gilt nur dort)
|
||||
const origin = await requestOrigin();
|
||||
if (provider !== "google" && provider !== "apple") return NextResponse.redirect(`${origin}${back}`, 303);
|
||||
const c = await getLoginProviders();
|
||||
if (!c[provider].enabled || !isConfigured(provider, c)) return NextResponse.redirect(`${appUrl()}${back}?fehler=aus`, 303);
|
||||
if (!c[provider].enabled || !isConfigured(provider, c)) return NextResponse.redirect(`${origin}${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://");
|
||||
const flow = newFlow(provider as SocialProvider, next, area, origin);
|
||||
const secure = origin.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,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { requestOrigin } from "@/lib/social/config";
|
||||
import { db } from "@/lib/db";
|
||||
import { markOrderPaid } from "@/lib/checkout";
|
||||
import { finishCheckoutSession } from "@/lib/checkout-finish";
|
||||
|
|
@ -8,7 +9,7 @@ import { capturePaypalOrder } from "@/lib/payments/paypal";
|
|||
export async function GET(req: NextRequest) {
|
||||
const orderId = req.nextUrl.searchParams.get("order") ?? "";
|
||||
const token = req.nextUrl.searchParams.get("token") ?? "";
|
||||
const appUrl = process.env.APP_URL ?? req.nextUrl.origin;
|
||||
const appUrl = await requestOrigin();
|
||||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||||
if (!order || order.paymentRef !== token) return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl));
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { requestOrigin } from "@/lib/social/config";
|
||||
import { db } from "@/lib/db";
|
||||
import { markOrderPaid } from "@/lib/checkout";
|
||||
import { finishCheckoutSession } from "@/lib/checkout-finish";
|
||||
|
|
@ -8,7 +9,7 @@ import { retrieveCheckoutSession } from "@/lib/payments/stripe";
|
|||
export async function GET(req: NextRequest) {
|
||||
const orderId = req.nextUrl.searchParams.get("order") ?? "";
|
||||
const sessionId = req.nextUrl.searchParams.get("session_id") ?? "";
|
||||
const appUrl = process.env.APP_URL ?? req.nextUrl.origin;
|
||||
const appUrl = await requestOrigin();
|
||||
const order = await db.order.findUnique({ where: { id: orderId } });
|
||||
if (!order || order.paymentRef !== sessionId) return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl));
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import "server-only";
|
||||
import { headers } from "next/headers";
|
||||
import { db } from "../db";
|
||||
|
||||
export type SocialProvider = "google" | "apple";
|
||||
|
|
@ -40,4 +41,29 @@ export async function getActiveProviders(): Promise<SocialProvider[]> {
|
|||
}
|
||||
|
||||
export const appUrl = () => (process.env.APP_URL ?? "https://sanamare.maaxxs-coding.de").replace(/\/$/, "");
|
||||
export const callbackUrl = (provider: SocialProvider) => `${appUrl()}/api/auth/${provider}/callback`;
|
||||
export const callbackUrl = (provider: SocialProvider, origin = appUrl()) => `${origin}/api/auth/${provider}/callback`;
|
||||
|
||||
/** Alle Adressen des Shops: APP_URL zuerst, dann weitere Domains aus APP_ALIASES (kommagetrennt). */
|
||||
export function siteOrigins() {
|
||||
return [process.env.APP_URL ?? appUrl(), ...(process.env.APP_ALIASES ?? "").split(",")]
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.flatMap((s) => {
|
||||
try {
|
||||
return [new URL(s.includes("://") ? s : `https://${s}`).origin];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})
|
||||
.filter((o, i, all) => all.indexOf(o) === i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Adresse, unter der der Kunde den Shop gerade aufruft, sofern sie zum Shop gehört.
|
||||
* Rückleitungen (Zahlung, Anmeldung) müssen dorthin zurück, sonst fehlen Warenkorb- und Anmelde-Cookies.
|
||||
*/
|
||||
export async function requestOrigin() {
|
||||
const h = await headers();
|
||||
const host = (h.get("x-forwarded-host") ?? h.get("host") ?? "").split(",")[0].trim().toLowerCase();
|
||||
return siteOrigins().find((o) => new URL(o).host === host) ?? appUrl();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,20 +5,20 @@ 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 };
|
||||
export type Flow = { provider: SocialProvider; state: string; nonce: string; verifier: string; next: string; area: string; origin?: 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 newFlow(provider: SocialProvider, next: string, area: string, origin: string): Flow {
|
||||
return { provider, state: random(), nonce: random(), verifier: random(), next, area, origin };
|
||||
}
|
||||
|
||||
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"),
|
||||
redirect_uri: callbackUrl("google", flow.origin),
|
||||
response_type: "code",
|
||||
scope: "openid email profile",
|
||||
state: flow.state,
|
||||
|
|
@ -32,7 +32,7 @@ export function authorizeUrl(flow: Flow, c: LoginProviders): string {
|
|||
// 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"),
|
||||
redirect_uri: callbackUrl("apple", flow.origin),
|
||||
response_type: "code",
|
||||
response_mode: "form_post",
|
||||
scope: "name email",
|
||||
|
|
@ -66,8 +66,8 @@ export type SocialProfile = { subject: string; email: string; emailVerified: boo
|
|||
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" });
|
||||
? new URLSearchParams({ code, client_id: c.google.clientId, client_secret: c.google.clientSecret, redirect_uri: callbackUrl("google", flow.origin), 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", flow.origin), 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" },
|
||||
|
|
|
|||
Loading…
Reference in a new issue