-
Notifications
You must be signed in to change notification settings - Fork 0
Implement client confirmation endpoint and success page #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nasmans
wants to merge
1
commit into
main
Choose a base branch
from
codex/add-client-id-generation-function
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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} />; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}`; | ||
|
|
||
| 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' }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| </> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| </> | ||
| ); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The confirmation endpoint constructs
confirmationUrlfromx-forwarded-protoandhostwheneverNEXT_PUBLIC_APP_URL/APP_URLare 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 👍 / 👎.