working prototype

This commit is contained in:
2025-08-10 23:26:33 +02:00
parent 169a407703
commit bb3ad1e4b9
8 changed files with 792 additions and 328 deletions
+115
View File
@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from "next/server";
type MerchantUserResponse = {
firstName: string;
lastName: string;
documentPhoto: string;
age: number;
};
type ProblemDetails = {
type: string;
title: string;
detail: string;
status: number;
};
async function fetchOidcToken(): Promise<string> {
const configUrl = process.env.BANKID_OIDC_CONFIG;
if (!configUrl) throw new Error("BANKID_OIDC_CONFIG not set");
// fetch OIDC config
const configRes = await fetch(configUrl);
if (!configRes.ok) throw new Error("Failed to fetch OIDC config");
const config = await configRes.json();
const tokenEndpoint = config.token_endpoint;
if (!tokenEndpoint) throw new Error("No token_endpoint in OIDC config");
// prepare client credentials
const clientId = process.env.BANKID_CLIENT_ID;
const clientSecret = process.env.BANKID_CLIENT_SECRET;
if (!clientId || !clientSecret) throw new Error("Client credentials not set");
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
// there are other scopes, but we don't seem to have access to more than the age + picture
params.append("scope", "vis-leg/identity_picture_age");
params.append("client_id", clientId);
params.append("client_secret", clientSecret);
// request token
const tokenRes = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params.toString(),
});
if (!tokenRes.ok) {
const errorText = await tokenRes.text();
console.error("Failed to fetch OIDC token. Response:", errorText);
throw new Error("Failed to fetch OIDC token");
}
const tokenData = await tokenRes.json();
if (!tokenData.access_token)
throw new Error("No access_token in token response");
console.log("Got a token from", tokenEndpoint);
return tokenData.access_token;
}
export async function POST(req: NextRequest) {
try {
const token = await fetchOidcToken();
const apiBase = process.env.ID_CARD_API_BASE_URL;
if (!apiBase) throw new Error("ID_CARD_API_BASE_URL not set");
const sessionUrl = apiBase + "/api/merchant/session";
// parse sessionId from request body, handle missing/invalid JSON
let body: any;
try {
body = await req.json();
} catch {
return NextResponse.json(
{ error: "missing or invalid JSON body" },
{ status: 400 }
);
}
const { sessionId } = body || {};
if (!sessionId || typeof sessionId !== "string") {
return NextResponse.json(
{ error: "missing or invalid sessionId" },
{ status: 400 }
);
}
const payload = { sessionId };
console.log("sending payload:", payload);
const sessionRes = await fetch(sessionUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const status = sessionRes.status;
const sessionData = await sessionRes.json();
console.log("session response:", sessionData);
if (status === 200) {
return NextResponse.json(sessionData as MerchantUserResponse, { status });
} else if ([400, 401, 410, 500].includes(status)) {
return NextResponse.json(sessionData as ProblemDetails, { status });
} else {
return NextResponse.json(
{ error: "Unexpected response from merchant session endpoint" },
{ status: 500 }
);
}
} catch (err: any) {
return NextResponse.json({ error: err.message }, { status: 500 });
}
}
+2 -2
View File
@@ -13,8 +13,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "Oldeneuf",
description: "ID-sjekk via BankID",
};
export default function RootLayout({
+103 -95
View File
@@ -1,103 +1,111 @@
"use client";
import { useState, useRef } from "react";
import Image from "next/image";
import Scanner from "@/components/Scanner";
import {
useMutation,
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query";
export default function Home() {
type SessionResponse = {
firstName: string;
lastName: string;
nnin: string;
documentPhoto: string;
age: number;
phoneNumber: string;
};
function SessionInfo({ session }: { session: SessionResponse }) {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<div className="max-w-md mx-auto mt-6 p-6 rounded-xl shadow-lg border border-gray-200 bg-gradient-to-br from-gray-50 to-gray-200 space-y-4">
<div className="flex flex-col items-center">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
src={`data:image/jpeg;base64,${session.documentPhoto}`}
alt="Document"
width={200}
height={261}
className="w-40 h-50 object-cover rounded-lg mb-4 border border-gray-300 shadow"
unoptimized
/>
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
src/app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
{(session.firstName || session.lastName) && (
<div className="text-xl font-bold text-gray-800">
{[session.firstName, session.lastName].filter(Boolean).join(" ")}
</div>
)}
{typeof session.age === "number" && (
<div className="text-3xl font-extrabold text-blue-700 mt-2">
{session.age} år
</div>
)}
</div>
</div>
);
}
async function lookupSession(sessionId: string) {
const res = await fetch("/api/lookup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId }),
});
return res.json();
}
function HomeInner() {
const [session, setSession] = useState<SessionResponse | null>(null);
const [scannedCodes, setScannedCodes] = useState<Set<string>>(new Set());
const pendingCodeRef = useRef<string | null>(null);
const mutation = useMutation({
mutationFn: lookupSession,
onSuccess: (data, variables) => {
console.log("Got lookup result:", data);
if (data && typeof data.age === "number") {
setSession(data);
setScannedCodes((prev) => new Set(prev).add(variables));
}
pendingCodeRef.current = null;
},
onError: () => {
pendingCodeRef.current = null;
},
});
const handleScan = (decodedText: string) => {
if (!decodedText.startsWith("VisLeg-")) {
window.alert("Ugyldig QR-kode");
return;
}
if (
scannedCodes.has(decodedText) ||
mutation.isPending ||
pendingCodeRef.current === decodedText
) {
// Already scanned or lookup in progress for this code
return;
}
pendingCodeRef.current = decodedText;
mutation.mutate(decodedText);
};
return (
<div>
<Scanner onScan={handleScan} />
{session && <SessionInfo session={session} />}
</div>
);
}
// Provide react-query context
const queryClient = new QueryClient();
export default function Home() {
return (
<QueryClientProvider client={queryClient}>
<HomeInner />
</QueryClientProvider>
);
}
+308
View File
@@ -0,0 +1,308 @@
"use client";
import { useEffect, useRef, useState } from "react";
import QrScanner from "qr-scanner";
interface ScannerProps {
onScan: (decodedText: string) => void;
}
interface Camera {
id: string;
label: string;
}
export default function Scanner({ onScan }: ScannerProps) {
const videoRef = useRef<HTMLVideoElement>(null);
const scannerRef = useRef<QrScanner | null>(null);
const [isScanning, setIsScanning] = useState(false);
const [hasCamera, setHasCamera] = useState<boolean | null>(null);
const [cameras, setCameras] = useState<Camera[]>([]);
const [selectedCamera, setSelectedCamera] = useState("environment");
const [hasFlash, setHasFlash] = useState(false);
const [isFlashOn, setIsFlashOn] = useState(false);
const [error, setError] = useState<string>("");
const [highlightStyle, setHighlightStyle] = useState("default-style");
const [showScanRegion, setShowScanRegion] = useState(false);
const handleScanResult = (result: QrScanner.ScanResult) => {
onScan(result.data);
setError("");
};
const handleScanError = (error: string | Error) => {
setError(error.toString());
};
const updateFlashAvailability = async () => {
if (scannerRef.current) {
const flashAvailable = await scannerRef.current.hasFlash();
setHasFlash(flashAvailable);
}
};
const initializeScanner = async () => {
if (!videoRef.current) return;
try {
scannerRef.current = new QrScanner(videoRef.current, handleScanResult, {
onDecodeError: handleScanError,
highlightScanRegion: true,
highlightCodeOutline: true,
});
await scannerRef.current.start();
setIsScanning(true);
await updateFlashAvailability();
// expects both light and dark QR codes
scannerRef.current.setInversionMode("both");
const availableCameras = await QrScanner.listCameras(true);
setCameras(availableCameras);
} catch (err) {
setError(`Failed to initialize scanner: ${err}`);
}
};
const startScanner = async () => {
if (scannerRef.current) {
try {
await scannerRef.current.start();
setIsScanning(true);
} catch (err) {
setError(`Failed to start scanner: ${err}`);
}
} else {
await initializeScanner();
}
};
const stopScanner = () => {
if (scannerRef.current) {
scannerRef.current.stop();
setIsScanning(false);
}
};
const toggleFlash = async () => {
if (scannerRef.current && hasFlash) {
try {
await scannerRef.current.toggleFlash();
setIsFlashOn(scannerRef.current.isFlashOn());
} catch (err) {
setError(`Failed to toggle flash: ${err}`);
}
}
};
const handleCameraChange = async (cameraId: string) => {
if (scannerRef.current) {
try {
await scannerRef.current.setCamera(cameraId);
setSelectedCamera(cameraId);
await updateFlashAvailability();
} catch (err) {
setError(`Failed to change camera: ${err}`);
}
}
};
useEffect(() => {
QrScanner.hasCamera().then(setHasCamera);
return () => {
if (scannerRef.current) {
scannerRef.current.destroy();
}
};
}, []);
useEffect(() => {
if (scannerRef.current && scannerRef.current.$canvas) {
scannerRef.current.$canvas.style.display = showScanRegion
? "block"
: "none";
}
}, [showScanRegion]);
const getVideoContainerClass = () => {
// on mobile portrait, fill top 50% of screen, no margin top/left/right
const baseClass = "relative w-full max-w-md mx-auto";
return `${baseClass} video-container-responsive`;
};
return (
<div className="w-full max-w-2xl mx-auto">
<div className={getVideoContainerClass()}>
<video
ref={videoRef}
className="w-full h-auto rounded-lg border-2 border-gray-300"
playsInline
muted
/>
</div>
<div className="p-4 space-y-4">
<div className="text-center">
{/* Video Container */}
{/* Controls */}
<div className="mt-4 space-y-4">
{/* Start/Stop Toggle Button */}
<div className="flex gap-2 justify-center">
<button
onClick={isScanning ? stopScanner : startScanner}
className={`px-4 py-2 text-white rounded-lg transition-colors ${
isScanning
? "bg-red-500 hover:bg-red-600"
: "bg-green-500 hover:bg-green-600"
}`}
>
{isScanning ? "Stop Scanner" : "Start Scanner"}
</button>
</div>
{/* Flash Toggle */}
{/* {hasFlash && (
<button
onClick={toggleFlash}
className="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors"
>
📸 Flash: {isFlashOn ? "on" : "off"}
</button>
)} */}
</div>
<div style={{ display: "none" }}>
{/* Settings */}
<div className="mt-6 space-y-4 text-left">
{/* Camera Selection */}
{cameras.length > 0 && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Camera:
</label>
<select
value={selectedCamera}
onChange={(e) => handleCameraChange(e.target.value)}
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="environment">
Environment Facing (Back Camera)
</option>
<option value="user">User Facing (Front Camera)</option>
{cameras.map((camera) => (
<option key={camera.id} value={camera.id}>
{camera.label}
</option>
))}
</select>
</div>
)}
{/* Highlight Style */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Highlight Style:
</label>
<select
value={highlightStyle}
onChange={(e) => setHighlightStyle(e.target.value)}
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="default-style">Default style</option>
<option value="example-style-1">Custom style 1</option>
<option value="example-style-2">Custom style 2</option>
</select>
</div>
{/* Show Scan Region */}
<div className="flex items-center">
<input
id="show-scan-region"
type="checkbox"
checked={showScanRegion}
onChange={(e) => setShowScanRegion(e.target.checked)}
className="mr-2 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
/>
<label
htmlFor="show-scan-region"
className="text-sm font-medium text-gray-700"
>
Show scan region canvas
</label>
</div>
</div>
{/* Status Information */}
<div className="mt-6 space-y-2 text-sm text-gray-600">
<div>
<span className="font-medium">Device has camera:</span>{" "}
{hasCamera !== null
? hasCamera
? "Yes"
: "No"
: "Checking..."}
</div>
<div>
<span className="font-medium">Camera has flash:</span>{" "}
{hasFlash ? "Yes" : "No"}
</div>
{error && (
<div className="text-red-600 font-medium">
<span className="font-medium">Error:</span> {error}
</div>
)}
</div>
</div>
</div>
</div>
<style jsx>{`
/* Responsive video container for mobile portrait */
@media (max-width: 768px) and (orientation: portrait) {
.video-container-responsive {
width: 100vw !important;
max-width: 100vw !important;
margin-left: 0 !important;
margin-right: 0 !important;
margin-top: 0 !important;
height: 50vh !important;
background: #000;
border-radius: 0 !important;
display: flex;
align-items: stretch;
justify-content: stretch;
}
.video-container-responsive video {
width: 100vw !important;
height: 50vh !important;
object-fit: cover;
border-radius: 0 !important;
border: none !important;
display: block;
}
}
:global(.scanner-style-1 .scan-region-highlight-svg),
:global(.scanner-style-1 .code-outline-highlight) {
stroke: #64a2f3 !important;
}
:global(.scanner-style-2 .scan-region-highlight) {
border-radius: 30px;
outline: rgba(0, 0, 0, 0.25) solid 50vmax;
}
:global(.scanner-style-2 .scan-region-highlight-svg) {
display: none;
}
:global(.scanner-style-2 .code-outline-highlight) {
stroke: rgba(255, 255, 255, 0.5) !important;
stroke-width: 15 !important;
stroke-dasharray: none !important;
}
`}</style>
</div>
);
}