Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
node_modules
.next
out
.env
.env.local
.env.*.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.DS_Store
coverage
1 change: 1 addition & 0 deletions data/clients.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
5 changes: 5 additions & 0 deletions next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
7 changes: 7 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true
};

export default nextConfig;
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "web",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "echo \"No tests defined\""
},
"dependencies": {
"next": "14.1.0",
"qrcode": "^1.5.3",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@types/node": "20.11.19",
"@types/react": "18.2.47",
"@types/react-dom": "18.2.18",
"typescript": "5.3.3"
}
}
37 changes: 37 additions & 0 deletions src/lib/clients.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { promises as fs } from 'fs';
import path from 'path';
import type { ClientRecord } from '@/types/client';

const DATA_DIRECTORY = path.join(process.cwd(), 'data');
const CLIENTS_FILE = path.join(DATA_DIRECTORY, 'clients.json');

async function ensureDataFile() {
try {
await fs.access(CLIENTS_FILE);
} catch {
await fs.mkdir(DATA_DIRECTORY, { recursive: true });
await fs.writeFile(CLIENTS_FILE, JSON.stringify([], null, 2), 'utf8');
}
}

export async function readClients(): Promise<ClientRecord[]> {
await ensureDataFile();
const raw = await fs.readFile(CLIENTS_FILE, 'utf8');
return JSON.parse(raw) as ClientRecord[];
}

export async function writeClients(clients: ClientRecord[]): Promise<void> {
await ensureDataFile();
await fs.writeFile(CLIENTS_FILE, JSON.stringify(clients, null, 2), 'utf8');
}

export async function addClient(client: ClientRecord): Promise<void> {
const clients = await readClients();
clients.push(client);
await writeClients(clients);
}

export async function findClientById(id: string): Promise<ClientRecord | null> {
const clients = await readClients();
return clients.find((client) => client.id === id) ?? null;
}
6 changes: 6 additions & 0 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { AppProps } from 'next/app';
import '@/styles/globals.css';

export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
28 changes: 28 additions & 0 deletions src/pages/api/clients/[id].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import QRCode from 'qrcode';
import { findClientById } from '@/lib/clients';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
res.setHeader('Allow', 'GET');
return res.status(405).json({ success: false, message: 'Method Not Allowed' });
}

const { id } = req.query;
if (typeof id !== 'string') {
return res.status(400).json({ success: false, message: 'Invalid client identifier' });
}

const client = await findClientById(id);
if (!client) {
return res.status(404).json({ success: false, message: 'Client not found' });
}

const qrCode = await QRCode.toDataURL(client.id, {
errorCorrectionLevel: 'M',
margin: 2,
scale: 6
});

return res.status(200).json({ success: true, client, qrCode });
}
84 changes: 84 additions & 0 deletions src/pages/api/clients/confirm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import QRCode from 'qrcode';
import { generateClientId } from '@/utils/id';
import { addClient } from '@/lib/clients';
import { buildConfirmationEmail } from '@/utils/email';
import type { ClientInput, ClientRecord } from '@/types/client';

type ConfirmResponse =
| {
success: true;
client: ClientRecord;
qrCode: string;
confirmationUrl: string;
emailPreview: { subject: string; html: string; text: string };
}
| { success: false; message: string };

function isClientInput(payload: unknown): payload is ClientInput {
if (typeof payload !== 'object' || payload === null) {
return false;
}

const { firstName, lastName, email, gender, phone } = payload as Record<string, unknown>;

const isString = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0;

if (!isString(firstName) || !isString(lastName) || !isString(email)) {
return false;
}

if (gender !== 'M' && gender !== 'F') {
return false;
}

if (phone !== undefined && typeof phone !== 'string') {
return false;
}

return true;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse<ConfirmResponse>) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
return res.status(405).json({ success: false, message: 'Method Not Allowed' });
}

const payload = req.body;

if (!isClientInput(payload)) {
return res.status(400).json({ success: false, message: 'Invalid client payload' });
}

const clientId = generateClientId(payload.gender);
const client: ClientRecord = {
...payload,
id: clientId,
createdAt: new Date().toISOString()
};

try {
await addClient(client);
const qrCode = await QRCode.toDataURL(clientId, {
errorCorrectionLevel: 'M',
margin: 2,
scale: 6
});

const protocol = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';
const host = req.headers.host ?? 'localhost:3000';
const baseUrl = process.env.NEXT_PUBLIC_APP_URL ?? process.env.APP_URL ?? `${protocol}://${host}`;
const confirmationUrl = `${baseUrl.replace(/\/$/, '')}/registration/success?id=${clientId}`;
Comment on lines +69 to +72
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Build confirmation URL from untrusted request headers

The confirmation endpoint constructs confirmationUrl from x-forwarded-proto and host whenever NEXT_PUBLIC_APP_URL/APP_URL are absent. Both headers are fully controllable by the caller, so a crafted POST can cause the API (or any email that reuses the returned preview) to contain attacker-controlled links and schemes. This is a classic host-header injection issue; the URL should be derived from a trusted configuration value or validated against an allow-list before use.

Useful? React with 👍 / 👎.


const emailPreview = buildConfirmationEmail({
firstName: client.firstName,
confirmationUrl
});

return res.status(201).json({ success: true, client, qrCode, confirmationUrl, emailPreview });
} catch (error) {
console.error('Failed to confirm client', error);
return res.status(500).json({ success: false, message: 'Failed to confirm client' });
}
}
24 changes: 24 additions & 0 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Head from 'next/head';
import Link from 'next/link';
import styles from '@/styles/Home.module.css';

export default function Home() {
return (
<>
<Head>
<title>Client Registration Portal</title>
</Head>
<main className={styles.container}>
<section className={styles.hero}>
<h1>مرحباً بكم في بوابة تسجيل العملاء</h1>
<p>
ابدأ عملية التسجيل أو تحقق من رسالة التأكيد للوصول إلى بطاقة النجاح الجديدة.
</p>
<Link href="/registration/success?id=demo" className={styles.cta}>
عرض نموذج بطاقة النجاح
</Link>
</section>
</main>
</>
);
}
128 changes: 128 additions & 0 deletions src/pages/registration/success.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import styles from '@/styles/RegistrationSuccess.module.css';

interface SuccessPayload {
success: boolean;
client?: {
id: string;
firstName: string;
lastName: string;
email: string;
gender: 'M' | 'F';
phone?: string;
createdAt: string;
};
qrCode?: string;
message?: string;
}

export default function RegistrationSuccessPage() {
const router = useRouter();
const { id } = router.query;

const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [payload, setPayload] = useState<SuccessPayload | null>(null);

useEffect(() => {
if (!router.isReady) {
return;
}

if (typeof id !== 'string') {
setError('معرّف العميل غير صالح.');
setLoading(false);
return;
}

const controller = new AbortController();

fetch(`/api/clients/${id}`, { signal: controller.signal })
.then(async (response) => {
const data: SuccessPayload = await response.json();
if (!response.ok || !data.success) {
throw new Error(data.message ?? 'تعذّر تحميل بيانات العميل.');
}
setPayload(data);
setError(null);
})
.catch((err: Error) => {
setError(err.message);
setPayload(null);
})
.finally(() => {
setLoading(false);
});

return () => controller.abort();
}, [id, router.isReady]);

return (
<>
<Head>
<title>نجاح التسجيل</title>
</Head>
<main className={styles.page}>
{loading && <p className={styles.loading}>جاري تحميل تفاصيل العميل...</p>}
{!loading && error && <p className={styles.error}>{error}</p>}
{!loading && !error && payload?.client && payload.qrCode && (
<article className={styles.card}>
<header className={styles.header}>
<div className={styles.statusBadge}>تم التفعيل بنجاح</div>
<h1>مرحبا {payload.client.firstName}!</h1>
<p>
اكتملت عملية تأكيد تسجيلك. يمكنك مشاركة معرّف العميل الخاص بك أو حفظ رمز QR التالي
للوصول السريع إلى بياناتك.
</p>
</header>

<section className={styles.clientInfo}>
<div className={styles.infoBlock}>
<span>معرّف العميل</span>
<strong>{payload.client.id}</strong>
</div>
<div className={styles.infoBlock}>
<span>الاسم الكامل</span>
<strong>
{payload.client.firstName} {payload.client.lastName}
</strong>
</div>
<div className={styles.infoBlock}>
<span>البريد الإلكتروني</span>
<strong>{payload.client.email}</strong>
</div>
<div className={styles.infoBlock}>
<span>الجنس</span>
<strong>{payload.client.gender === 'M' ? 'ذكر' : 'أنثى'}</strong>
</div>
{payload.client.phone && (
<div className={styles.infoBlock}>
<span>رقم الجوال</span>
<strong>{payload.client.phone}</strong>
</div>
)}
<div className={styles.infoBlock}>
<span>تاريخ الإنشاء</span>
<strong>{new Date(payload.client.createdAt).toLocaleString('ar-SA')}</strong>
</div>
</section>

<div className={styles.qrWrapper}>
<img src={payload.qrCode} alt="رمز QR لمعرّف العميل" />
</div>

<footer className={styles.meta}>
<Link href="/" className={styles.backLink}>
العودة للواجهة الرئيسية
</Link>
<span>يمكنك حفظ هذه البطاقة أو مشاركتها مع فريق الدعم.</span>
</footer>
</article>
)}
</main>
</>
);
}
Loading