initial commit

This commit is contained in:
Giovanni Rezcjikov
2026-03-08 14:54:29 +03:00
commit f4e4fb21e3
75 changed files with 7407 additions and 0 deletions
@@ -0,0 +1,26 @@
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { pkceConfig } from "@/lib/cookie-config";
import crypto from "crypto";
export async function GET() {
const verifier = crypto.randomBytes(32).toString("base64url");
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
const state = crypto.randomBytes(16).toString("hex");
const store = await cookies();
store.set("pkce_verifier", verifier, pkceConfig);
store.set("oauth_state", state, { ...pkceConfig, path: "/api/callback" });
const params = new URLSearchParams({
client_id: process.env.CLIENT_ID!,
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
scope: "profile:read profile:edit profile:consent:read",
response_type: "code",
code_challenge: challenge,
code_challenge_method: "S256",
state,
});
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params.toString()}`);
}
@@ -0,0 +1,45 @@
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { setTokens, serverBasicAuth } from "@/actions/auth";
import { type NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const code = request.nextUrl.searchParams.get("code");
const returnedState = request.nextUrl.searchParams.get("state");
if (!code) redirect("/callback/error");
const store = await cookies();
const codeVerifier = store.get("pkce_verifier")?.value;
const savedState = store.get("oauth_state")?.value;
if (!codeVerifier || returnedState !== savedState) redirect("/callback/error");
store.delete("pkce_verifier");
store.delete("oauth_state");
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: await serverBasicAuth(),
},
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
code_verifier: codeVerifier,
}).toString(),
cache: "no-store",
});
if (!response.ok) redirect("/callback/error");
const data = await response.json();
await setTokens(data.access_token, data.refresh_token, data.expires_in);
} catch {
redirect("/callback/error");
}
redirect("/");
}
+111
View File
@@ -0,0 +1,111 @@
"use client"
import Header from "@/components/header";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { getSession, Approve } from "@/actions/oauth";
import { Check } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import Link from "next/link";
interface Session {
client_name: string;
scopes: string[];
redirect_uri: string;
}
export default function ConsentPage() {
const searchParams = useSearchParams();
const sessionToken = searchParams.get("session") || "";
const t = useTranslations("ConsentPage");
const [session, setSession] = useState<Session | null>(null);
const [error, setError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
getSession(sessionToken)
.then(data => {
if (!data) throw new Error();
setSession(data);
})
.catch(() => setError(t("invalidSession")));
}, []);
const handleDecision = async (allow: boolean) => {
setIsSubmitting(true);
if (allow) {
const result = await Approve(sessionToken, allow);
if (result) {
window.location.href = result;
} else {
setError(t("invalidSession"));
setIsSubmitting(false);
}
} else {
window.location.href = session?.redirect_uri || "/";
}
};
return (
<>
<Header />
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="w-full max-w-sm flex flex-col gap-6">
{error ? (
<div className="flex flex-col gap-6">
<p className="text-destructive">{error}</p>
<div className="flex gap-3">
<Link href={session?.redirect_uri || "/"}><Button>{t("toApp")}</Button></Link>
<Link href="/"><Button variant="outline">{t("toHome")}</Button></Link>
</div>
</div>
) : !session ? (
<>
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-2">
<Skeleton className="w-64 h-5" />
<Skeleton className="w-86 h-5" />
<Skeleton className="w-64 h-5" />
</div>
<div className="flex flex-col gap-2 my-4">
<Skeleton className="w-86 h-4" />
<Skeleton className="w-86 h-4" />
</div>
<div className="flex gap-3">
<Skeleton className="w-17 h-9" />
<Skeleton className="w-17 h-9" />
</div>
</div>
</>
) : (
<>
<div className="flex flex-col gap-2">
<h1 className="text-xl">{t("title", { service: session.client_name })}</h1>
<h2 className="text-lg">{t("subtitle", { service: session.client_name })}</h2>
</div>
<div className="flex flex-col gap-1">
{session.scopes.map(scope => (
<div key={scope} className="flex flex-row gap-3 items-center">
<Check size={18} />
<h3 className="text-base">{t(`scopes.${scope}`, { defaultValue: scope })}</h3>
</div>
))}
</div>
<div className="flex gap-3">
<Button onClick={() => handleDecision(true)} disabled={isSubmitting}>
{isSubmitting && <Spinner />}{t("allow")}
</Button>
<Button onClick={() => handleDecision(false)} disabled={isSubmitting} variant="outline">
{t("deny")}
</Button>
</div>
</>
)}
</div>
</div>
</>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+124
View File
@@ -0,0 +1,124 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
}
:root {
--radius: 0.8rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
+40
View File
@@ -0,0 +1,40 @@
import type { Metadata } from "next";
import { Golos_Text } from "next/font/google";
import "./globals.css";
import { NextIntlClientProvider } from "next-intl";
import { ThemeProvider } from "@/components/themeProvider";
import { Toaster } from "@/components/ui/sonner";
const golosText = Golos_Text({
variable: "--font-geist-sans",
weight: ["500"],
subsets: ["latin", "cyrillic"],
});
export const metadata: Metadata = {
title: "Kotosoft ID",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={`${golosText.className} antialiased selection:bg-black/10 dark:selection:bg-blue-300/20`}>
<NextIntlClientProvider>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
<Toaster richColors />
</NextIntlClientProvider>
</body>
</html>
);
}
+124
View File
@@ -0,0 +1,124 @@
"use client"
import { SessionLogin } from "@/actions/auth";
import Header from "@/components/header";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { useSearchParams, useRouter } from "next/navigation";
import Link from "next/link";
interface FormData {
email: string;
password: string;
}
export default function LoginPage() {
const searchParams = useSearchParams();
const router = useRouter();
const session = searchParams.get("session");
const t = useTranslations("LoginPage");
const [error, setError] = useState<string | null>(null);
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormData>();
useEffect(() => {
if (!session) {
window.location.href = "/api/auth/initiate";
}
}, [session]);
const onSubmit: SubmitHandler<FormData> = async (data) => {
setError(null);
const result = await SessionLogin(session!, data.email, data.password);
if (!result.success) {
if (result.expired) {
window.location.href = "/api/auth/initiate";
return;
}
setError(result.message ?? null);
return;
}
if (result.redirectURL) {
window.location.href = result.redirectURL;
} else {
router.push(`/consent?session=${session}`);
}
};
if (!session) return (
<div className="w-full min-h-svh flex items-center justify-center">
<Spinner className="size-6" />
</div>
);
return (
<>
<Header />
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="w-full max-w-sm flex flex-col gap-6">
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<div className="flex flex-col">
<h1 className="text-xl">{t("title")}</h1>
<h1 className="text-xl text-muted-foreground">{t("subtitle")}</h1>
</div>
<Field data-invalid={!!errors.email}>
<FieldLabel htmlFor="email">{t("email.title")}</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
disabled={isSubmitting}
aria-invalid={!!errors.email}
{...register("email", {
required: t("required"),
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t("email.invalid") },
})}
/>
{errors.email && <FieldError>{errors.email.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.password}>
<FieldLabel htmlFor="password">{t("password.title")}</FieldLabel>
<Input
id="password"
type="password"
disabled={isSubmitting}
aria-invalid={!!errors.password}
{...register("password", {
required: t("required"),
minLength: { value: 8, message: t("password.minLength") },
})}
/>
{errors.password && <FieldError>{errors.password.message}</FieldError>}
</Field>
<Field>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{t("login")}
</Button>
{error && <FieldError className="text-center">{error}</FieldError>}
</Field>
</FieldGroup>
</form>
<FieldDescription className="px-6 text-center">
{t.rich("noAccountNote", {
register: (chunks) => <Link href="/register">{chunks}</Link>
})}
</FieldDescription>
</div>
</div>
</>
);
}
+67
View File
@@ -0,0 +1,67 @@
"use client"
import Header from "@/components/header";
import { Skeleton } from "@/components/ui/skeleton";
import { useTranslations } from "next-intl";
import type { Consent, User } from "@/types";
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, UserIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { Logout } from "@/actions/auth";
import Profile from "./items/profile";
import Applications from "./items/applications";
interface Props {
userData: User | null;
consentsData: Consent[] | [];
}
export default function MeClient({ userData, consentsData }: Props) {
const t = useTranslations("MePage");
const [user, setUser] = useState(userData);
const [consents, setConsents] = useState(consentsData)
const [selectedItem, setSelectedItem] = useState(0);
const items = [
{"name": t("items.profile.title"), "icon": <UserIcon />, "component": <Profile user={user} setUser={setUser} />},
{"name": t("items.applications.title"), "icon": <AppWindowMacIcon />, "component": <Applications consents={consents} setConsents={setConsents} />},
{"name": t("items.positions.title"), "icon": <BriefcaseBusinessIcon />},
]
return (
<>
<Header />
<div className="bg-background flex min-h-svh flex-col gap-6">
<div className="px-8 lg:px-16 pt-30 pb-16">
{!user ? (
<div className="flex flex-col gap-2">
<Skeleton className="w-64 h-5" />
<Skeleton className="w-52 h-4" />
</div>
) : (
<div className="flex flex-col lg:flex-row gap-12">
<div className="flex flex-col gap-8">
<div className="flex flex-col">
<h2 className="text-lg">
{user.first_name} {user.second_name}
</h2>
<p className="text-muted-foreground text-base">{user.email}</p>
</div>
<div className="flex flex-col gap-0.5 lg:w-64">
{
items.map((item, index) => (
<Button variant="ghost" className={`justify-start -mx-4 ${selectedItem == index && "bg-muted"}`} key={index} onClick={() => setSelectedItem(index)}>{item.icon}<h3 className="text-sm">{item.name}</h3></Button>
))
}
<Button variant="ghost" className="justify-start -mx-4" onClick={async () => Logout()}><LogOutIcon /><h3 className="text-sm">{t("items.logout")}</h3></Button>
</div>
</div>
{items[selectedItem].component}
</div>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,41 @@
"use client"
import { useLocale, useTranslations } from "next-intl";
import type { Consent } from "@/types";
import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
import { Button } from "@/components/ui/button";
import { localeMap } from "@/types";
import { enUS } from "date-fns/locale";
import { format } from "date-fns";
interface Props {
consents: Consent[] | [];
setConsents: (consents: Consent[]) => void;
}
export default function Applications({ consents, setConsents }: Props) {
const t = useTranslations("MePage.items.applications");
const locale = useLocale();
const dateLocale = localeMap[locale as keyof typeof localeMap] ?? enUS;
return (
<div className="w-full lg:max-w-sm flex flex-col gap-4">
<h1 className="text-xl">{t("title")}</h1>
<div className="space-y-4">
{consents.map((consent) => (
<Item key={consent.client_id}>
<ItemContent>
<ItemTitle>{consent.client_name}</ItemTitle>
<ItemDescription>{t("authorized")} {format(consent.authorized_at, "PPP", { locale: dateLocale }) }</ItemDescription>
</ItemContent>
<ItemActions>
<Button disabled={!consent.isRevokable}>{t("revoke")}</Button>
</ItemActions>
</Item>
))}
</div>
</div>
);
}
@@ -0,0 +1,115 @@
"use client"
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import type { User } from "@/types";
import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { BirthdatePicker } from "@/components/ui/birthdate-picker";
import { UpdateUser } from "@/actions/auth";
interface Props {
user: User | null;
setUser: (user: User) => void;
}
interface FormData {
first_name: string;
second_name: string;
birth_date: string;
}
export default function Profile({ user, setUser }: Props) {
const t = useTranslations("MePage.items.profile");
const [error, setError] = useState<string | null>(null);
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<FormData>({
defaultValues: {
first_name: user?.first_name,
second_name: user?.second_name,
birth_date: user?.birth_date ?? "",
},
});
const onSubmit: SubmitHandler<FormData> = async (data) => {
setError(null);
try {
const response = await UpdateUser(data.first_name, data.second_name, data.birth_date);
if (response == null) setError(t("form.updateError"))
else setUser(response)
} catch (error) {
setError(t("form.updateError"))
}
};
return (
<div className="w-full lg:max-w-sm flex flex-col gap-4">
<h1 className="text-xl">{t("title")}</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Field data-invalid={!!errors.first_name}>
<FieldLabel htmlFor="first_name">{t("form.firstName.title")}</FieldLabel>
<Input
id="first_name"
type="text"
disabled={isSubmitting}
aria-invalid={!!errors.first_name}
{...register("first_name", {
required: t("form.required"),
minLength: { value: 2, message: t("form.firstName.minLength") },
maxLength: { value: 64, message: t("form.firstName.maxLength") },
})}
/>
{errors.first_name && <FieldError>{errors.first_name.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.second_name}>
<FieldLabel htmlFor="second_name">{t("form.secondName.title")}</FieldLabel>
<Input
id="second_name"
type="text"
disabled={isSubmitting}
aria-invalid={!!errors.second_name}
{...register("second_name", {
required: t("form.required"),
minLength: { value: 2, message: t("form.secondName.minLength") },
maxLength: { value: 64, message: t("form.secondName.maxLength") },
})}
/>
{errors.second_name && <FieldError>{errors.second_name.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.birth_date}>
<FieldLabel htmlFor="birth_date">{t("form.birthdate.title")}</FieldLabel>
<Controller
name="birth_date"
control={control}
render={({ field }) => (
<BirthdatePicker
value={field.value}
onChange={field.onChange}
disabled={isSubmitting}
aria-invalid={!!errors.birth_date}
/>
)}
/>
{errors.birth_date && <FieldError>{errors.birth_date.message}</FieldError>}
</Field>
<Field>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{t("form.save")}
</Button>
{error && <FieldError className="text-center">{error}</FieldError>}
</Field>
</FieldGroup>
</form>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { GetUser } from "@/actions/auth";
import { redirect } from "next/navigation";
import MeComponent from "./component";
import { getConsents } from "@/actions/consents";
export default async function Me() {
const user = await GetUser();
if (!user) {
redirect("/api/auth/initiate");
}
var consents = await getConsents();
return <MeComponent userData={user} consentsData={consents} />;
}
+26
View File
@@ -0,0 +1,26 @@
import { getSession } from "@/actions/oauth";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { redirect } from "next/navigation";
export default async function OAuthPage({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
try {
const session = (await searchParams).session as string | undefined;
if (!session) redirect("/oauth/error");
const data = await getSession(session);
if (!data) redirect("/oauth/error");
const isAuthenticated =
data.user_id && data.user_id !== "00000000-0000-0000-0000-000000000000";
redirect(isAuthenticated ? `/consent?session=${session}` : `/login?session=${session}`);
} catch (error) {
if (isRedirectError(error)) throw error;
console.error("OAuth page error:", error);
redirect("/oauth/error");
}
}
+8
View File
@@ -0,0 +1,8 @@
"use client"
export default function Home() {
return (
<>
</>
);
}
+193
View File
@@ -0,0 +1,193 @@
"use client"
import { Register } from "@/actions/auth";
import Header from "@/components/header";
import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm, SubmitHandler, Controller } from "react-hook-form";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Sex } from "@/types";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ArrowLeft, ArrowRight, Check } from "lucide-react";
import { toast } from "sonner";
interface FormData {
email: string;
password: string;
first_name: string;
second_name: string;
sex: Sex;
}
export default function RegisterPage() {
const router = useRouter();
const t = useTranslations("RegisterPage");
const [step, setStep] = useState<number>(0);
const [error, setError] = useState<string | null>(null);
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<FormData>();
const onSubmit: SubmitHandler<FormData> = async (data) => {
setError(null);
const result = await Register(data.email, data.password, data.first_name, data.second_name, data.sex);
if (!result.success) {
setError(result.message ?? null);
return;
}
toast(t("registeredSuccessfully"), { icon: <Check size={16} /> })
router.push(`/login`);
};
return (
<>
<Header />
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="w-full max-w-sm flex flex-col gap-6">
<form onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<div className="flex flex-col gap-1">
<h1 className="text-xl">{t("title")}</h1>
<h2 className="text-lg text-muted-foreground leading-6">{t("subtitle")}</h2>
</div>
{ step == 0 ? (
<>
<Field data-invalid={!!errors.email}>
<FieldLabel htmlFor="email">{t("email.title")}</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
disabled={isSubmitting}
aria-invalid={!!errors.email}
{...register("email", {
required: t("required"),
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t("email.invalid") },
})}
/>
{errors.email && <FieldError>{errors.email.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.password}>
<FieldLabel htmlFor="password">{t("password.title")}</FieldLabel>
<Input
id="password"
type="password"
autoComplete="current-password"
disabled={isSubmitting}
aria-invalid={!!errors.password}
{...register("password", {
required: t("required"),
minLength: { value: 8, message: t("password.minLength") },
})}
/>
{errors.password && <FieldError>{errors.password.message}</FieldError>}
</Field>
<Field>
<Button onClick={(e) => setStep(1)} variant="default" disabled={isSubmitting}>
{t("next")}
<ArrowRight />
</Button>
</Field>
</>) : (
<>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={!!errors.first_name}>
<FieldLabel htmlFor="first_name">{t("firstName.title")}</FieldLabel>
<Input
id="first_name"
type="text"
disabled={isSubmitting}
aria-invalid={!!errors.first_name}
{...register("first_name", {
required: t("required"),
minLength: { value: 2, message: t("firstName.minLength") },
maxLength: { value: 64, message: t("firstName.maxLength") },
})}
/>
{errors.first_name && <FieldError>{errors.first_name.message}</FieldError>}
</Field>
<Field data-invalid={!!errors.second_name}>
<FieldLabel htmlFor="second_name">{t("secondName.title")}</FieldLabel>
<Input
id="second_name"
type="text"
disabled={isSubmitting}
aria-invalid={!!errors.second_name}
{...register("second_name", {
required: t("required"),
minLength: { value: 2, message: t("secondName.minLength") },
maxLength: { value: 64, message: t("secondName.maxLength") },
})}
/>
{errors.second_name && <FieldError>{errors.second_name.message}</FieldError>}
</Field>
</div>
<Field data-invalid={!!errors.sex}>
<FieldLabel htmlFor="sex">{t("sex.title")}</FieldLabel>
<Controller
name="sex"
control={control}
rules={{
required: t("required"),
}}
render={({ field }) => (
<Select
disabled={isSubmitting}
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger aria-invalid={!!errors.sex}>
<SelectValue placeholder={t("sex.select")} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="MALE">{t("sex.male")}</SelectItem>
<SelectItem value="FEMALE">{t("sex.female")}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
)}
/>
{errors.sex && <FieldError>{errors.sex.message}</FieldError>}
</Field>
<div className="grid grid-cols-3 gap-4">
<Field className="col-span-1">
<Button onClick={(e) => {e.preventDefault(); setStep(0)}} variant="outline" disabled={isSubmitting}>
<ArrowLeft />
{t("back")}
</Button>
</Field>
<Field className="col-span-2">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Spinner />}
{t("register")}
</Button>
</Field>
</div>
{error && <FieldError className="text-center">{error}</FieldError>}
</>)
}
</FieldGroup>
</form>
<FieldDescription className="px-6 text-center">
{t.rich("hasAccountNote", {
login: (chunks) => <Link href="/login">{chunks}</Link>
})}
</FieldDescription>
</div>
</div>
</>
);
}