feat: citizenship applications

This commit is contained in:
Ivan Rezchikov
2026-06-23 19:03:10 +03:00
parent 58ec75c948
commit c60ab9e8f9
44 changed files with 1254 additions and 130 deletions
+34 -5
View File
@@ -1,12 +1,14 @@
"use client";
import { useRef, useTransition } from "react";
import { useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import Editor, { EditorData } from "@/components/editor";
import { savePageAction } from "@/lib/pages/actions";
import { validatePage } from "@/lib/pages/validation";
import { Block, Page, PageMeta, PageType } from "@/lib/pages/types";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
type Props = {
page: Page | null;
@@ -17,10 +19,11 @@ type Props = {
export default function EditPageClient({ page, pageType, initialBlocks = [] }: Props) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [fieldErrors, setFieldErrors] = useState<{ title?: string[]; slug?: string[] }>({});
const dataRef = useRef<EditorData>({
title: page?.title ?? "",
type: page?.type ?? "",
type: pageType,
slug: page?.slug ?? "",
location: (page?.meta as PageMeta)?.location ?? "",
tags: (page?.meta as PageMeta)?.tags ?? [],
@@ -30,7 +33,7 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
function handleSave(status: "DRAFT" | "PUBLISHED") {
startTransition(async () => {
const data = dataRef.current;
await savePageAction({
const payload = {
id: page?.id ?? null,
slug: data.slug || data.title.toLowerCase().replace(/\s+/g, "-"),
title: data.title,
@@ -38,8 +41,32 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
status,
blocks: data.blocks,
meta: { location: data.location, tags: data.tags },
});
router.push(`/${page?.type.toLowerCase()}/${data.slug}`);
};
const parsed = validatePage(payload);
if (!parsed.success) {
const errors: { title?: string[]; slug?: string[] } = {};
for (const msg of parsed.errors) {
if (msg.toLowerCase().includes("title")) {
(errors.title ??= []).push(msg);
} else if (msg.toLowerCase().includes("slug")) {
(errors.slug ??= []).push(msg);
}
}
setFieldErrors(errors);
toast.error(parsed.errors.join(", "));
return;
}
setFieldErrors({});
try {
await savePageAction(payload);
toast.success("Page saved");
router.push(`/${pageType.toLowerCase()}/${data.slug}`);
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to save page");
}
});
}
@@ -61,8 +88,10 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
page={page}
type={pageType}
initialBlocks={initialBlocks}
errors={fieldErrors}
onChange={(data) => {
dataRef.current = data;
setFieldErrors({});
}}
/>
</div>
+1 -1
View File
@@ -15,7 +15,7 @@ export default async function EditPage({ params }: { params: Promise<{ type: str
const pageType = type.toUpperCase() as PageType;
if (!PAGE_TYPES.includes(pageType)) notFound();
const page = await getPageBySlug(slug);
const page = await getPageBySlug(slug, pageType);
if (!page) notFound();
const blocks = page ? await getBlocksByPageId(page.id) : [];
+5 -4
View File
@@ -1,7 +1,7 @@
import Header from "@/components/header";
import Footer from "@/components/footer";
import { getPageBySlug, getBlocksByPageId } from "@/lib/pages/repository";
import { getCurrentUser, getUser } from "@/lib/user";
import { getCurrentUser, getUsers } from "@/lib/user";
import { notFound } from "next/navigation";
import { Block, PAGE_TYPES, PageMeta, PageType } from "@/lib/pages/types";
import { cn, formatDate } from "@/lib/utils";
@@ -140,15 +140,16 @@ export default async function Page({ params }: { params: Promise<{ type: string;
const pageType = type.toUpperCase() as PageType;
if (!PAGE_TYPES.includes(pageType)) notFound();
const page = await getPageBySlug(slug);
const page = await getPageBySlug(slug, pageType);
if (!page || (!user?.isAdmin && page.status == "ARCHIVED")) notFound();
const navlink = await getNavLinkByPageId(page.id);
const blocks = page ? await getBlocksByPageId(page.id) : [];
const createdBy = await getUser(page?.createdBy);
const updatedBy = await getUser(page?.updatedBy);
const users = await getUsers(page.createdBy, page.updatedBy);
const createdBy = users.find((u) => u.id === page.createdBy) ?? null;
const updatedBy = users.find((u) => u.id === page.updatedBy) ?? null;
const isNews = page.type === "NEWS";
const isArchived = page.status === "ARCHIVED";
@@ -0,0 +1,62 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { CitizenshipApplication } from "@/lib/citizenship/types";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { cn, formatDate } from "@/lib/utils";
import { CheckIcon, ClockFadingIcon, PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
export function ApplicationsDialog({ applications }: { applications: CitizenshipApplication[] }) {
return (
<Dialog>
<DialogTrigger asChild><Button variant="secondary">Citizenship applications</Button></DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle asChild><h3>Citizenship applications</h3></DialogTitle>
<DialogDescription>Here are your citizenship applications</DialogDescription>
<Accordion type="single" collapsible>
{applications.map((application, i) => (
<AccordionItem key={application.id} value={application.id}>
<AccordionTrigger><h3>Application №{i + 1}</h3></AccordionTrigger>
<AccordionContent>
<div className="flex flex-col gap-1">
<div className="flex flex-row gap-2 items-center text-muted-foreground">
<PlusIcon size={16} /><p>Created on {formatDate(application.createdAt)}</p>
</div>
<div className={cn("flex flex-row gap-2 items-center", application.status !== "PENDING" && "text-muted-foreground")}>
<ClockFadingIcon size={16} /><p>{application.status === "PENDING" ? "On review" : `Reviewed on ${formatDate(application.reviewedAt)}`}</p>
</div>
{application.status === "REJECTED" && (
<div className="flex flex-col gap-0.5 mt-2">
<div className="flex flex-row gap-2 items-center text-destructive">
<XIcon size={16} /><p>Rejected</p>
</div>
<p className="text-muted-foreground">{application.rejectionReason}</p>
</div>
)}
{application.status === "APPROVED" && (
<div className="flex flex-row gap-2 items-center mt-2">
<CheckIcon size={16} /><p>Approved</p>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
))}
</Accordion>
</DialogHeader>
</DialogContent>
</Dialog>
);
}
+291
View File
@@ -0,0 +1,291 @@
"use client";
import { useActionState, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Field,
FieldContent,
FieldDescription,
FieldGroup,
FieldLabel,
FieldLegend,
FieldSet,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import { submitCitizenshipApplication, type ApplicationState } from "@/lib/citizenship/actions";
import { EYE_COLORS } from "@/lib/citizenship/types";
import Link from "next/link";
import { Spinner } from "@/components/ui/spinner";
type Props = {
firstName: string;
secondName: string;
sex: string;
birthDate: Date | null;
};
const initialState: ApplicationState = { success: false, errors: [] };
function formatDate(d: Date | null): string {
if (!d) return "";
return d.toISOString().split("T")[0];
}
type AppType = "PREVIOUS_CITIZENSHIP" | "BORN_IN_TERRITORY" | "NATURALIZATION";
export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDate }: Props) {
const [appType, setAppType] = useState<AppType | "">("");
const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialState);
return (
<form action={formAction}>
<FieldGroup>
<FieldSet>
<FieldLegend>Personal information</FieldLegend>
<Alert className="border-amber-200 bg-amber-50 text-amber-900">
<InfoIcon />
<AlertTitle>Important notice</AlertTitle>
<AlertDescription>
Personal data is sourced from your account profile. Please ensure that all information is accurate.
If corrections are required, update your details in Kotosoft ID and synchronise your account.
</AlertDescription>
</Alert>
<FieldGroup>
<Field>
<FieldLabel htmlFor="surname">Surname</FieldLabel>
<Input
id="surname"
value={secondName}
readOnly
className="bg-muted text-muted-foreground"
/>
</Field>
<Field>
<FieldLabel htmlFor="givenNames">Given names</FieldLabel>
<Input
id="givenNames"
value={firstName}
readOnly
className="bg-muted text-muted-foreground"
/>
</Field>
<div className="grid grid-cols-2 gap-4">
<Field>
<FieldLabel htmlFor="sex">Sex</FieldLabel>
<Input
id="sex"
value={sex === "MALE" ? "Male" : "Female"}
readOnly
className="bg-muted text-muted-foreground"
/>
</Field>
<Field>
<FieldLabel htmlFor="birthDate">Date of birth</FieldLabel>
<Input
id="birthDate"
value={formatDate(birthDate)}
readOnly
className="bg-muted text-muted-foreground"
/>
</Field>
</div>
</FieldGroup>
</FieldSet>
<FieldSet>
<FieldLegend>Eligibility basis</FieldLegend>
<FieldDescription>
Select the basis on which you are applying for citizenship.
</FieldDescription>
<RadioGroup
name="applicationType"
value={appType}
onValueChange={(v) => setAppType(v as AppType)}
required
>
<FieldLabel htmlFor="prev-citizen">
<Field orientation="horizontal">
<RadioGroupItem value="PREVIOUS_CITIZENSHIP" id="prev-citizen" />
<FieldContent>
<span className="text-sm font-medium">
Previous citizenship holder
</span>
<FieldDescription>
I held citizenship of the Duspean Republic or the Country of
Reality on 31 March 2026.
</FieldDescription>
</FieldContent>
</Field>
</FieldLabel>
<FieldLabel htmlFor="born-territory">
<Field orientation="horizontal">
<RadioGroupItem value="BORN_IN_TERRITORY" id="born-territory" />
<FieldContent>
<span className="text-sm font-medium">Born in territory</span>
<FieldDescription>
I was born in the European Federation, the former Duspean
Republic, or the Country of Reality, and do not hold citizenship.
</FieldDescription>
</FieldContent>
</Field>
</FieldLabel>
<FieldLabel htmlFor="naturalization">
<Field orientation="horizontal">
<RadioGroupItem value="NATURALIZATION" id="naturalization" />
<FieldContent>
<span className="text-sm font-medium">Naturalisation</span>
<FieldDescription>
I am a foreign national seeking naturalisation.
</FieldDescription>
</FieldContent>
</Field>
</FieldLabel>
</RadioGroup>
</FieldSet>
{appType === "PREVIOUS_CITIZENSHIP" && (
<FieldSet>
<FieldLegend>Previous citizenship details</FieldLegend>
<FieldGroup>
<Field>
<FieldLabel htmlFor="previousCountry">Country</FieldLabel>
<Select name="previousCountry" defaultValue="">
<SelectTrigger id="previousCountry">
<SelectValue placeholder="Select country" />
</SelectTrigger>
<SelectContent>
<SelectItem value="DUS">Duspean Republic</SelectItem>
<SelectItem value="REA">Country of Reality</SelectItem>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel htmlFor="previousRegion">Region of issuance</FieldLabel>
<Input
id="previousRegion"
name="previousRegion"
placeholder="State, region, or territory"
required
/>
<FieldDescription>
The region or authority that issued your previous citizenship. The list of regions is <Link href="/page/regions">here</Link>.
</FieldDescription>
</Field>
</FieldGroup>
</FieldSet>
)}
{appType === "BORN_IN_TERRITORY" && (
<FieldSet>
<FieldLegend>Birth details</FieldLegend>
<FieldGroup>
<Field>
<FieldLabel htmlFor="birthRegion">Region of birth</FieldLabel>
<Input
id="birthRegion"
name="birthRegion"
placeholder="City, Region, Country"
required
/>
<FieldDescription>
The municipality, region, and country where you were born. The list of regions is <Link href="/page/regions">here</Link>.
</FieldDescription>
</Field>
</FieldGroup>
</FieldSet>
)}
{appType === "NATURALIZATION" && (
<FieldSet>
<FieldLegend>Naturalisation statement</FieldLegend>
<FieldGroup>
<Field>
<FieldLabel htmlFor="naturalizationReason">
Why do you wish to become a citizen of the European Federation?
</FieldLabel>
<Textarea
id="naturalizationReason"
name="naturalizationReason"
placeholder="Explain your motivation for seeking citizenship..."
rows={4}
required
/>
</Field>
</FieldGroup>
</FieldSet>
)}
<FieldSet>
<FieldLegend>Additional information</FieldLegend>
<FieldDescription>
Provide details required for your identity document.
</FieldDescription>
<FieldGroup>
<Field>
<FieldLabel htmlFor="address">Current address</FieldLabel>
<Input
id="address"
name="address"
placeholder="Street, City, Region"
required
/>
<FieldDescription>
Your current place of residence.
</FieldDescription>
</Field>
<div className="grid grid-cols-2 gap-4">
<Field>
<FieldLabel htmlFor="height">Height (in cm)</FieldLabel>
<Input
id="height"
type="number"
name="height"
min={60}
max={240}
required
/>
</Field>
<Field>
<FieldLabel htmlFor="eyeColor">Eye colour</FieldLabel>
<Select name="eyeColor" defaultValue="">
<SelectTrigger id="eyeColor">
<SelectValue placeholder="Select eye colour" />
</SelectTrigger>
<SelectContent>
{EYE_COLORS.map((color) => (
<SelectItem key={color} value={color}>
{color}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
</div>
</FieldGroup>
</FieldSet>
{state.errors.length > 0 && (
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-900">
<ul className="list-disc pl-4">
{state.errors.map((err, i) => (
<li key={i}>{err}</li>
))}
</ul>
</div>
)}
<Field orientation="horizontal">
<Button type="submit">{isPending && <Spinner />}Submit application</Button>
</Field>
</FieldGroup>
</form>
);
}
+39
View File
@@ -0,0 +1,39 @@
import Footer from "@/components/footer";
import Header from "@/components/header";
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import { AccountMenu } from "../../menu";
import { CitizenshipApplicationForm } from "./form";
import { getUserApplications } from "@/lib/citizenship/repository";
export default async function CitizenshipApplication() {
const user = await getCurrentUser();
if (!user) redirect("/");
const applications = await getUserApplications(user.id);
const canApply = applications.length === 0 || applications.every((a) => a.status === "REJECTED");
if (!canApply) redirect("/account/citizenship");
return (
<>
<Header />
<div className="flex flex-row py-16 gap-8">
<AccountMenu />
<div className="flex flex-col gap-8">
<div className="flex flex-col gap-6">
<h2>Citizenship application</h2>
<div className="w-96 flex flex-col gap-6">
<CitizenshipApplicationForm
firstName={user.firstName}
secondName={user.secondName}
sex={user.sex}
birthDate={user.birthDate}
/>
</div>
</div>
</div>
</div>
<Footer />
</>
);
}
+114
View File
@@ -0,0 +1,114 @@
import Footer from "@/components/footer";
import Header from "@/components/header";
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import { AccountMenu } from "../menu";
import { InfoIcon } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { ApplicationsDialog } from "./applicationsDialog";
import { getUserApplications } from "@/lib/citizenship/repository";
export default async function Citizenship() {
const user = await getCurrentUser();
if (!user) redirect("/");
const applications = await getUserApplications(user.id);
return (
<>
<Header />
<div className="flex flex-row py-16 gap-8">
<AccountMenu />
<div className="flex flex-col gap-8 max-w-lg">
<div className="flex flex-col gap-6 w-min">
<h2>Citizenship</h2>
<Alert className="border-amber-200 bg-amber-50 text-amber-900">
<InfoIcon />
<AlertTitle>You are not a citizen of the European Federation</AlertTitle>
<AlertDescription>
You currently hold non-citizen status. Certain civic services and
identity documents are available only to
citizens of the European Federation.
</AlertDescription>
</Alert>
<div className="flex flex-col gap-3">
<div className="flex flex-row gap-3 w-max">
<Link href="/page/citizenship"><Button variant="secondary">Learn more about citizenship</Button></Link>
<Link href="/account/citizenship/apply"><Button>Apply for the citizenship</Button></Link>
</div>
{applications.length > 0 && <ApplicationsDialog applications={applications} />}
</div>
<Accordion type="single" collapsible>
<AccordionItem value="eligibility">
<AccordionTrigger>
<h4>Who is eligible for citizenship?</h4>
</AccordionTrigger>
<AccordionContent>
Citizenship may be granted to persons born in the European
Federation, the former Duspean Republic, or the Country of Reality,
as well as to individuals who held citizenship of the Duspean
Republic or the Country of Reality on 31 March 2026.
<br />
<br />
Foreign nationals who demonstrate a commitment to the development,
prosperity, and values of the European Federation may also be
eligible for naturalisation under federal law.
</AccordionContent>
</AccordionItem>
<AccordionItem value="rights">
<AccordionTrigger>
<h4>What rights does citizenship provide?</h4>
</AccordionTrigger>
<AccordionContent>
Citizens enjoy all rights and protections guaranteed by the
Constitution and laws of the European Federation, including the
right to obtain federal identity documents, participate in federal
elections, and receive protection from federal authorities.
</AccordionContent>
</AccordionItem>
<AccordionItem value="documents">
<AccordionTrigger>
<h4>What documents are required?</h4>
</AccordionTrigger>
<AccordionContent>
Applicants may be asked to provide proof of
residence in the European Federation, evidence of eligibility, and any additional documents
required by the competent authority.
</AccordionContent>
</AccordionItem>
<AccordionItem value="processing">
<AccordionTrigger>
<h4>How long does the application process take?</h4>
</AccordionTrigger>
<AccordionContent>
Processing times vary depending on the complexity of the
application and the volume of requests currently under review.
Applicants can track the status of their application through their
account.
</AccordionContent>
</AccordionItem>
<AccordionItem value="dual">
<AccordionTrigger>
<h4>Is dual citizenship permitted?</h4>
</AccordionTrigger>
<AccordionContent>
The European Federation generally permits dual citizenship unless
otherwise restricted by federal law or international agreements.
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
</div>
<Footer />
</>
);
}
+1 -1
View File
@@ -5,7 +5,7 @@ import {
Dialog, DialogClose, DialogContent, DialogDescription,
DialogFooter, DialogHeader, DialogTitle, DialogTrigger,
} from "@/components/ui/dialog";
import deleteUserAction from "../actions/delete";
import { deleteUserAction } from "@/lib/user/actions";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
+1 -1
View File
@@ -3,7 +3,7 @@
import { useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import logout from "../actions/logout";
import { logout } from "@/lib/user/actions";
export function LogoutButton() {
const [isPending, startTransition] = useTransition();
+53
View File
@@ -0,0 +1,53 @@
"use client"
import { cn } from "@/lib/utils";
import { BookOpenTextIcon, SignatureIcon, UserIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
const menuItems = [
{
href: "/account",
label: "Profile",
icon: UserIcon,
},
{
href: "/account/citizenship",
label: "Citizenship",
icon: BookOpenTextIcon,
},
{
href: "/account/signature",
label: "Signature",
icon: SignatureIcon,
},
];
export function AccountMenu() {
const pathname = usePathname();
return (
<div className="flex flex-col w-56 gap-2 mx-16 shrink-0">
{menuItems.map((item) => {
const Icon = item.icon;
const active = pathname === item.href;
return (
<Link
href={item.href}
key={item.href}
className={cn(
"flex flex-row gap-2 items-center underline-offset-8 decoration-2 duration-200",
active
? "text-foreground underline mb-1.5"
: "text-muted-foreground hover:text-foreground hover:underline"
)}
>
<Icon size={16} />
<span>{item.label}</span>
</Link>
);
})}
</div>
);
}
+4 -16
View File
@@ -1,6 +1,5 @@
import Footer from "@/components/footer";
import Header from "@/components/header";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { getCurrentUser } from "@/lib/user";
import { formatDate } from "@/lib/utils";
@@ -8,6 +7,8 @@ import { BookOpenTextIcon, SignatureIcon, UserIcon } from "lucide-react";
import { redirect } from "next/navigation";
import { DeleteDialog } from "./deleteDialog";
import { LogoutButton } from "./logoutButton";
import { UpdateButton } from "./updateButton";
import { AccountMenu } from "./menu";
function ProfileField({ label, value }: { label: string; value: string }) {
return (
@@ -26,20 +27,7 @@ export default async function Account() {
<>
<Header />
<div className="flex flex-row py-16 gap-8">
<div className="flex flex-col w-56 gap-2 mx-16 shrink-0">
<div className="flex flex-row gap-2 items-center text-foreground underline underline-offset-8 decoration-2 mb-1.5">
<UserIcon size={16} />
<h4>Profile</h4>
</div>
<div className="flex flex-row gap-2 items-center text-muted-foreground hover:text-foreground hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">
<BookOpenTextIcon size={16} />
<h4>Citizenship</h4>
</div>
<div className="flex flex-row gap-2 items-center text-muted-foreground hover:text-foreground hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">
<SignatureIcon size={16} />
<h4>Signature</h4>
</div>
</div>
<AccountMenu />
<div className="flex flex-col gap-8 max-w-lg">
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-1">
@@ -61,7 +49,7 @@ export default async function Account() {
<h4>Update personal details</h4>
<p className="text-muted-foreground">Syncs your name, email, and birthday from Kotosoft ID</p>
</div>
<Button variant="secondary">Update</Button>
<UpdateButton />
</div>
<div className="flex flex-row items-center justify-between">
<div className="flex flex-col">
+30
View File
@@ -0,0 +1,30 @@
"use client"
import { useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "sonner";
import { updateUserAction } from "@/lib/user/actions";
export function UpdateButton() {
const [isPending, startTransition] = useTransition();
return (
<Button
variant="secondary"
disabled={isPending}
onClick={() =>
startTransition(async () => {
try {
await updateUserAction();
toast.success("Profile updated");
} catch {
toast.error("Failed to update profile. Your session may have expired. Try signing in again.");
}
})
}
>
{isPending && <Spinner />}Update
</Button>
);
}
-9
View File
@@ -1,9 +0,0 @@
"use server"
import { deleteUser } from "@/lib/user/repository"
import logout from "./logout";
export default async function deleteUserAction(userId: string ) {
await deleteUser(userId);
await logout();
}
-27
View File
@@ -1,27 +0,0 @@
"use server"
import { generatePkce, generateState } from "@/lib/auth/pkce";
import { pkceConfig } from "@/lib/cookieConfig";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export default async function login() {
const { verifier, challenge } = generatePkce();
const state = generateState();
const store = await cookies();
store.set("pkce_verifier", verifier, pkceConfig);
store.set("oauth_state", state, pkceConfig);
const params = new URLSearchParams({
client_id: process.env.KOTOSOFT_ID_CLIENT_ID!,
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
scope: "profile:read",
response_type: "code",
code_challenge: challenge,
code_challenge_method: "S256",
state,
});
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params}`);
}
-9
View File
@@ -1,9 +0,0 @@
"use server"
import { deleteSession } from "@/lib/auth/session";
import { redirect } from "next/navigation";
export default async function logout() {
await deleteSession();
redirect("/");
}
+31 -2
View File
@@ -5,7 +5,35 @@ import { createSession } from "@/lib/auth/session";
import { exchangeCode, fetchKotosoftUser } from "@/lib/kotosoft/client";
import { findOrCreateUser } from "@/lib/user/repository";
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
const RATE_LIMIT_WINDOW = 60_000;
const RATE_LIMIT_MAX = 10;
function checkRateLimit(ip: string): boolean {
const now = Date.now();
const entry = rateLimitMap.get(ip);
if (!entry || now > entry.resetAt) {
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
return true;
}
entry.count++;
return entry.count <= RATE_LIMIT_MAX;
}
export async function GET(request: NextRequest) {
const url = process.env.PUBLIC_URL;
if (url) {
const requestOrigin = request.nextUrl.origin;
if (requestOrigin !== url) {
return NextResponse.json({ message: "Access denied" }, { status: 403 });
}
}
const ip = request.headers.get("x-forwarded-for") ?? request.headers.get("x-real-ip") ?? "unknown";
if (!checkRateLimit(ip)) {
return NextResponse.json({ message: "Too many requests" }, { status: 429 });
}
const { searchParams } = request.nextUrl;
const code = searchParams.get("code");
const state = searchParams.get("state");
@@ -32,8 +60,9 @@ export async function GET(request: NextRequest) {
email: kotosoftUser.email,
firstName: kotosoftUser.first_name,
secondName: kotosoftUser.second_name,
sex: kotosoftUser.sex,
sex: kotosoftUser.sex as "MALE" | "FEMALE",
birthDate: kotosoftUser.birth_date,
isAdmin: false,
});
await createSession(user.id);
@@ -44,4 +73,4 @@ export async function GET(request: NextRequest) {
console.error("OAuth callback error:", e);
return NextResponse.redirect(new URL("/callback/error", request.url));
}
}
}
+38 -5
View File
@@ -1,15 +1,18 @@
"use client";
import { useRef, useTransition } from "react";
import { useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import Editor, { EditorData } from "@/components/editor";
import { savePageAction } from "@/lib/pages/actions";
import { validatePage } from "@/lib/pages/validation";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
export default function CreatePageClient() {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [fieldErrors, setFieldErrors] = useState<{ title?: string[]; slug?: string[] }>({});
const dataRef = useRef<EditorData>({
title: "",
type: "NEWS",
@@ -22,7 +25,7 @@ export default function CreatePageClient() {
function handleSave(status: "DRAFT" | "PUBLISHED") {
startTransition(async () => {
const data = dataRef.current;
await savePageAction({
const payload = {
id: null,
slug: data.slug || data.title.toLowerCase().replace(/\s+/g, "-"),
title: data.title,
@@ -30,8 +33,32 @@ export default function CreatePageClient() {
status,
blocks: data.blocks,
meta: { location: data.location, tags: data.tags },
});
router.push("/news");
};
const parsed = validatePage(payload);
if (!parsed.success) {
const errors: { title?: string[]; slug?: string[] } = {};
for (const msg of parsed.errors) {
if (msg.toLowerCase().includes("title")) {
(errors.title ??= []).push(msg);
} else if (msg.toLowerCase().includes("slug")) {
(errors.slug ??= []).push(msg);
}
}
setFieldErrors(errors);
toast.error(parsed.errors.join(", "));
return;
}
setFieldErrors({});
try {
await savePageAction(payload);
toast.success("Page saved");
router.push("/news");
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to save page");
}
});
}
@@ -54,7 +81,13 @@ export default function CreatePageClient() {
</Button>
</div>
</div>
<Editor onChange={(data) => { dataRef.current = data; }} />
<Editor
onChange={(data) => {
dataRef.current = data;
setFieldErrors({});
}}
errors={fieldErrors}
/>
</div>
);
}
+5 -1
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import localFont from "next/font/local"
import "./globals.css";
import { cn } from "@/lib/utils";
import { Toaster } from "@/components/ui/sonner";
const helvetica = localFont({
src: "../public/fonts/HelveticaNeue-Medium.otf",
@@ -23,7 +24,10 @@ export default function RootLayout({
lang="en"
className={cn("h-full", "antialiased", helvetica.className, "font-sans")}
>
<body className="min-h-full flex flex-col">{children}</body>
<body className="min-h-full flex flex-col">
{children}
<Toaster />
</body>
</html>
);
}
+6 -6
View File
@@ -16,25 +16,25 @@ export default async function Home() {
<div className="grid grid-cols-[2fr_1fr_1fr_1fr] gap-8">
<Link href="/page/citizenship">
<div className="flex items-end h-64 p-4 rounded-lg bg-primary text-primary-foreground">
<h1 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1>
<h1 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1>
</div>
</Link>
<div className="grid grid-rows-2 gap-8">
<Link href="/page/president">
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Learn more about the President</h2>
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Learn more about the President</h2>
</div>
</Link>
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Acknowledge with the Federal Government</h2>
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Acknowledge with the Federal Government</h2>
</div>
</div>
<div className="grid grid-rows-2 gap-8">
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Regions of the Federation</h2>
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Regions of the Federation</h2>
</div>
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Receive consular services abroad</h2>
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Receive consular services abroad</h2>
</div>
</div>
</div>
@@ -47,7 +47,7 @@ export default async function Home() {
)) : <h2 className="text-muted-foreground">There are no news yet...</h2>
}
</div>
<Link href="/news"><h3 className="w-max flex flex-row items-center gap-2 hover:gap-2.5 hover: duration-200 cursor-pointer">See all news<ArrowRightIcon size={20} /></h3></Link>
<Link href="/news"><h3 className="w-max flex flex-row items-center gap-2 hover:gap-2.5 hover:duration-200 cursor-pointer">See all news<ArrowRightIcon size={20} /></h3></Link>
</div>
</div>
<Footer />