Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x | import { NextResponse } from "next/server";
import QRCode from "qrcode";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import {
appLink,
ehdsOrigin,
PairingError,
startPairing,
} from "@/lib/app-pairing";
import { createRateLimiter } from "@/lib/rate-limit";
import { sessionUsername } from "@/lib/patient/session-username";
export const dynamic = "force-dynamic";
/** A patient starting pairings in a loop is a script, not a person. */
const limiter = createRateLimiter({
windowMs: 60_000,
perKey: 6,
inTotal: 120,
});
/**
* POST /api/patient/app-pairing
*
* Starts connecting the Klarbefund app (#473, ADR-049): asks Keycloak for a
* device authorization for the client `klarbefund-app` and answers with the
* QR code the phone scans, the same link for a phone that is already holding
* this page, and Keycloak's page where the patient approves. The code lives
* two minutes. Only a PATIENT pairs, and only for their own login.
*/
export async function POST(request: Request) {
const auth = await requireAuth(["PATIENT"]);
if (isAuthError(auth)) return auth;
const username = await sessionUsername();
Iif (!username) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
Iif (!limiter.allow(username)) {
return NextResponse.json(
{ error: "Too many pairings, try again in a minute" },
{ status: 429 },
);
}
try {
const pairing = await startPairing(username);
const link = appLink(pairing, ehdsOrigin(request));
const qrDataUri = await QRCode.toDataURL(link, {
margin: 1,
width: 320,
errorCorrectionLevel: "M",
});
return NextResponse.json({
pairingId: pairing.id,
appLink: link,
qrDataUri,
userCode: pairing.userCode,
verificationUri: pairing.verificationUri,
expiresAt: new Date(pairing.expiresAt).toISOString(),
});
} catch (err) {
const message =
err instanceof PairingError ? err.message : "Keycloak is unreachable";
console.error("POST /api/patient/app-pairing:", err);
return NextResponse.json({ error: message }, { status: 502 });
}
}
|