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
+201
View File
@@ -0,0 +1,201 @@
"use server"
import type { User } from "@/types";
import { getTranslations } from "next-intl/server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { cookieConfig } from "@/lib/cookie-config";
let refreshPromise: Promise<boolean> | null = null;
export async function serverBasicAuth() {
return (
"Basic " +
Buffer.from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`).toString("base64")
);
}
export async function setTokens(accessToken: string, refreshToken: string, ttl: number) {
const store = await cookies();
store.set("access_token", accessToken, { ...cookieConfig, path: "/", maxAge: ttl });
store.set("refresh_token", refreshToken, { ...cookieConfig, path: "/", maxAge: ttl * 7 });
}
export async function clearTokens() {
const store = await cookies();
store.delete("access_token");
store.delete("refresh_token");
}
async function tryRefresh(): Promise<boolean> {
if (refreshPromise) return refreshPromise;
refreshPromise = (async () => {
const store = await cookies();
const refreshToken = store.get("refresh_token")?.value;
if (!refreshToken) return false;
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: "refresh_token",
refresh_token: refreshToken,
}).toString(),
cache: "no-store",
});
if (!response.ok) return false;
const data = await response.json();
await setTokens(data.access_token, data.refresh_token, data.expires_in);
return true;
} catch {
return false;
} finally {
refreshPromise = null;
}
})();
return refreshPromise;
}
export async function SessionLogin(
session: string,
email: string,
password: string,
): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
const t = await getTranslations("errors");
if (!session || !email || !password) {
return { success: false, message: t("invalidCredentialsError") };
}
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ session, email, password }),
cache: "no-store",
});
const data = await response.json();
if (!response.ok) {
if (data.error === "invalid_grant") return { success: false, expired: true };
return { success: false, message: t("invalidCredentialsError") };
}
if (data.redirect_url) return { success: true, redirectURL: data.redirect_url };
return { success: true };
} catch {
return { success: false, message: t("serverError") };
}
}
export async function GetUser(): Promise<User | null> {
const store = await cookies();
const accessToken = store.get("access_token")?.value;
if (!accessToken) return null;
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me`, {
headers: { Authorization: `Bearer ${accessToken}` },
cache: "no-store",
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return null;
}
return GetUser();
}
if (!response.ok) return null;
return (await response.json()) as User;
} catch {
return null;
}
}
export async function UpdateUser(first_name: string, second_name: string, birth_date: string): Promise<User | null> {
const store = await cookies();
const accessToken = store.get("access_token")?.value;
if (!accessToken) return null;
let formattedDate: string | undefined;
if (birth_date) {
const datePart = birth_date.split("T")[0];
if (datePart) formattedDate = `${datePart}T00:00:00Z`;
}
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
first_name,
second_name,
...(formattedDate && { birth_date: formattedDate }),
})
});
if (response.status === 401) {
const refreshed = await tryRefresh();
if (!refreshed) {
await clearTokens();
return null;
}
return UpdateUser(first_name, second_name, birth_date);
}
if (!response.ok) return null;
return (await response.json()) as User;
} catch {
return null;
}
}
export async function Register(email: string, password: string, first_name: string, second_name: string, sex: string): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
const t = await getTranslations("errors");
if (!email || !password) return { success: false, message: t("allFieldsRequired") }
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/auth/register`, {
method: "POST",
headers: {
Authorization: await serverBasicAuth(),
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
first_name,
second_name,
sex
})
});
if (!response.ok) {
if (response.status == 409) return { success: false, message: t("emailAlreadyExistsError") };
return { success: false, message: t("serverError") };
}
return { success: true };
} catch {
return { success: false, message: t("serverError") };
}
}
export async function Logout() {
await clearTokens();
redirect("/login");
}
+52
View File
@@ -0,0 +1,52 @@
"use server"
import { Consent } from "@/types"
import { cookies } from "next/headers"
export async function getConsents() {
const store = await cookies()
const accessToken = store.get("access_token")?.value
const response = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/consents`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
)
if (!response.ok) return []
var consents = await response.json() as Consent[];
consents.forEach((consent: Consent) => {
if (consent.client_id == process.env.CLIENT_ID) {
consent.isRevokable == false
} else {
consent.isRevokable == true
}
});
return consents
}
export async function revokeConsent(clientId: string) {
const store = await cookies()
const accessToken = store.get("access_token")?.value
const response = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/applications/${clientId}`,
{
method: "DELETE",
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
)
if (!response.ok) {
return { success: false }
}
return { success: true }
}
+9
View File
@@ -0,0 +1,9 @@
"use server"
import { cookies } from "next/headers";
export async function changeLanguage(language: string) {
const store = await cookies();
store.set("locale", language);
}
+34
View File
@@ -0,0 +1,34 @@
"use server"
import type { OAuthSession } from "@/types";
export async function getSession(token: string): Promise<OAuthSession | null> {
if (!token) return null;
try {
const response = await fetch(
`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/${token}`,
{ cache: "no-store" }
);
if (!response.ok) return null;
return await response.json() as OAuthSession;
} catch {
return null;
}
}
export async function Approve(session: string, allow: boolean): Promise<string | null> {
if (!session) return null;
try {
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/approve`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ session, allow }),
cache: "no-store",
});
if (!response.ok) return null;
const data = await response.json();
return data.redirect_url ?? null;
} catch {
return null;
}
}
@@ -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>
</>
);
}
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}
@@ -0,0 +1,14 @@
import { ThemeToggler } from "./themeToggler";
import { LanguageToggler } from "./languageToggler";
export default function Header() {
return (
<header className="fixed top-0 left-0 right-0 flex flex-row items-center justify-between gap-6 px-3 py-2.5">
<div />
<div className="flex flex-row items-center gap-3">
<LanguageToggler />
<ThemeToggler />
</div>
</header>
)
}
@@ -0,0 +1,8 @@
import { changeLanguage } from "@/actions/language"
import { LanguageTogglerDropdown } from "./languageTogglerDropdown"
export function LanguageToggler() {
return (
<LanguageTogglerDropdown changeLanguage={changeLanguage} />
)
}
@@ -0,0 +1,38 @@
"use client"
import { Globe } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useTranslations } from "next-intl"
interface Props {
changeLanguage: (lang: string) => Promise<void>;
}
export function LanguageTogglerDropdown({ changeLanguage }: Props) {
const t = useTranslations();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button><Globe />{t("ChangeLanguage")}</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="mt-2" align="end">
<DropdownMenuItem onClick={() => changeLanguage("en")}>
English
</DropdownMenuItem>
<DropdownMenuItem onClick={() => changeLanguage("ru")}>
Русский
</DropdownMenuItem>
<DropdownMenuItem onClick={() => changeLanguage("it")}>
Italiano
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,11 @@
"use client"
import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
@@ -0,0 +1,44 @@
"use client"
import * as React from "react"
import { LaptopMinimal, Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useTranslations } from "next-intl"
export function ThemeToggler() {
const { setTheme } = useTheme();
const t = useTranslations("theme");
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="icon">
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="mt-2" align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun />
{t("light")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon />
{t("dark")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
<LaptopMinimal />
{t("system")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,64 @@
"use client"
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useLocale, useTranslations } from "next-intl";
import { forwardRef } from "react";
import { localeMap } from "@/types";
import { enUS } from "date-fns/locale";
interface BirthdatePickerProps {
value?: string;
onChange?: (value: string) => void;
disabled?: boolean;
"aria-invalid"?: boolean;
}
export const BirthdatePicker = forwardRef<HTMLButtonElement, BirthdatePickerProps>(
({ value, onChange, disabled, "aria-invalid": ariaInvalid }, ref) => {
const t = useTranslations("MePage.items.profile.form.birthdate");
const date = value ? new Date(value) : undefined;
const handleSelect = (selected: Date | undefined) => {
if (selected && onChange) {
onChange(format(selected, "yyyy-MM-dd"));
}
};
const locale = useLocale();
const dateLocale = localeMap[locale as keyof typeof localeMap] ?? enUS;
return (
<Popover>
<PopoverTrigger asChild>
<Button
ref={ref}
type="button"
variant="outline"
disabled={disabled}
aria-invalid={ariaInvalid}
data-empty={!date}
className="data-[empty=true]:text-muted-foreground w-full justify-start text-left font-normal"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP", { locale: dateLocale }) : <span>{t("pick")}</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={date}
onSelect={handleSelect}
captionLayout="dropdown"
disabled={{ after: new Date() }}
/>
</PopoverContent>
</Popover>
);
}
);
BirthdatePicker.displayName = "BirthdatePicker";
@@ -0,0 +1,64 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90 items-center",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
@@ -0,0 +1,222 @@
"use client"
import * as React from "react"
import {
DayPicker,
getDefaultClassNames,
type DayButton,
type Locale,
} from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
locale,
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
locale={locale}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString(locale?.code, { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative rounded-(--cell-radius)",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-(--cell-radius) flex items-center gap-1 text-sm [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-(--cell-radius) flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full rounded-(--cell-radius) h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius) group/day aspect-square select-none",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
defaultClassNames.day
),
range_start: cn(
"rounded-l-(--cell-radius) bg-muted relative after:bg-muted after:absolute after:inset-y-0 after:w-4 after:right-0 z-0 isolate",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn(
"rounded-r-(--cell-radius) bg-muted relative after:bg-muted after:absolute after:inset-y-0 after:w-4 after:left-0 z-0 isolate",
defaultClassNames.range_end
),
today: cn(
"bg-muted text-foreground rounded-(--cell-radius) data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon className={cn("size-4", className)} {...props} />
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: ({ ...props }) => (
<CalendarDayButton locale={locale} {...props} />
),
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
locale,
...props
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString(locale?.code)}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-foreground relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }
@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
@@ -0,0 +1,248 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}
@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }
+196
View File
@@ -0,0 +1,196 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
role="list"
data-slot="item-group"
className={cn(
"group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
className
)}
{...props}
/>
)
}
function ItemSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="item-separator"
orientation="horizontal"
className={cn("my-2", className)}
{...props}
/>
)
}
const itemVariants = cva(
"[a]:hover:bg-muted rounded-lg border text-sm w-full group/item focus-visible:border-ring focus-visible:ring-ring/50 flex items-center flex-wrap outline-none transition-colors duration-100 focus-visible:ring-[3px] [a]:transition-colors",
{
variants: {
variant: {
default: "border-transparent",
outline: "border-border",
muted: "bg-muted/50 border-transparent",
},
size: {
default: "gap-2.5 px-3 py-2.5",
sm: "gap-2.5 px-3 py-2.5",
xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Item({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div"
return (
<Comp
data-slot="item"
data-variant={variant}
data-size={size}
className={cn(itemVariants({ variant, size, className }))}
{...props}
/>
)
}
const itemMediaVariants = cva(
"gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start flex shrink-0 items-center justify-center [&_svg]:pointer-events-none",
{
variants: {
variant: {
default: "bg-transparent",
icon: "[&_svg:not([class*='size-'])]:size-4",
image:
"size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
},
},
defaultVariants: {
variant: "default",
},
}
)
function ItemMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(itemMediaVariants({ variant, className }))}
{...props}
/>
)
}
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-content"
className={cn(
"flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
className
)}
{...props}
/>
)
}
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-title"
className={cn(
"line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4",
className
)}
{...props}
/>
)
}
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="item-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary line-clamp-4 text-left text-sm leading-normal font-normal group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-actions"
className={cn("flex items-center gap-2", className)}
{...props}
/>
)
}
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-header"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-footer"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
}
@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
@@ -0,0 +1,89 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg p-2.5 text-sm shadow-md ring-1 outline-hidden duration-100",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-0.5 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverAnchor,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
}
@@ -0,0 +1,192 @@
"use client"
import * as React from "react"
import { Select as SelectPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
)
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-placeholder:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 flex w-fit items-center justify-between gap-1.5 rounded-lg border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
data-align-trigger={position === "item-aligned"}
className={cn("bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg shadow-md ring-1 duration-100 data-[align-trigger=true]:animate-none", position ==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
data-position={position}
className={cn(
"data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",
position === "popper" && ""
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-1.5 py-1 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronUpIcon
/>
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronDownIcon
/>
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}
@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import { Separator as SeparatorPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }
@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-muted animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }
@@ -0,0 +1,49 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: (
<CircleCheckIcon className="size-4" />
),
info: (
<InfoIcon className="size-4" />
),
warning: (
<TriangleAlertIcon className="size-4" />
),
error: (
<OctagonXIcon className="size-4" />
),
loading: (
<Loader2Icon className="size-4 animate-spin" />
),
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
toastOptions={{
classNames: {
toast: "cn-toast",
},
}}
{...props}
/>
)
}
export { Toaster }
@@ -0,0 +1,10 @@
import { cn } from "@/lib/utils"
import { Loader2Icon } from "lucide-react"
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return (
<Loader2Icon role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props} />
)
}
export { Spinner }
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
+12
View File
@@ -0,0 +1,12 @@
import { getRequestConfig } from "next-intl/server";
import { cookies } from "next/headers";
export default getRequestConfig(async () => {
const store = await cookies();
const locale = store.get("locale")?.value || 'en';
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default
};
});
+11
View File
@@ -0,0 +1,11 @@
export const cookieConfig = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
};
export const pkceConfig = {
...cookieConfig,
path: "/api/callback",
maxAge: 60 * 10,
};
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+112
View File
@@ -0,0 +1,112 @@
{
"ChangeLanguage": "Change language",
"LoginPage": {
"title": "Welcome to Kotosoft ID",
"subtitle": "Unified ID system of Dusiburg",
"email": {
"title": "Email",
"invalid": "Please enter a correct email"
},
"password": {
"title": "Password",
"minLength": "Password must have at least 8 symbols"
},
"required": "This field is required",
"login": "Login",
"noAccountNote": "You don't have a Kotosoft ID account? You can register <register>here</register>."
},
"RegisterPage":{
"title": "Sign up in Kotosoft ID",
"subtitle": "Create an account in the unified ID system of Dusiburg",
"email": {
"title": "Email",
"invalid": "Please enter a correct email"
},
"password": {
"title": "Password",
"minLength": "Password must have at least 8 symbols"
},
"firstName": {
"title": "Your first name",
"minLength": "First name must have at least 2 characters",
"maxLength": "First name must contain no more than 64 characters"
},
"secondName": {
"title": "Your last name",
"minLength": "Last name must have at least 2 characters",
"maxLength": "Last name must contain no more than 64 characters"
},
"sex": {
"title": "Sex",
"select": "Specify Your sex",
"male": "Male",
"female": "Female"
},
"required": "This field is required",
"next": "Next",
"back": "Back",
"register": "Sign in",
"hasAccountNote": "You already have a Kotosoft ID account? You can log in <login>here</login>."
},
"MePage": {
"loadError": "Something has gone wrong. It's impossible to load user.",
"items": {
"profile": {
"title": "Profile",
"form": {
"firstName": {
"title": "Your first name",
"minLength": "First name must have at least 2 characters",
"maxLength": "First name must contain no more than 64 characters"
},
"secondName": {
"title": "Your last name",
"minLength": "Last name must have at least 2 characters",
"maxLength": "Last name must contain no more than 64 characters"
},
"birthdate": {
"title": "Date of birth",
"pick": "Select Your date of birth"
},
"required": "This field is required",
"save": "Save",
"successfullyUpdated": "Your profile is updated successfully!",
"updateError": "An error occurred during the update. Please try again later."
}
},
"applications": {
"title": "Applications",
"authorized": "Autorized on",
"revoke": "Revoke"
},
"positions": {
"title": "Positions"
},
"logout": "Logout"
}
},
"ConsentPage": {
"title": "Access to {service}",
"subtitle": "{service} wants to access Your Kotosoft ID account to:",
"invalidSession": "This session is invalid. Please go back to Your application and try again.",
"scopes": {
"profile:read": "See information of Your profile",
"profile:edit": "Edit information of Your profile"
},
"allow": "Allow",
"deny": "Deny",
"toApp": "Back to application",
"toHome": "Back to home page"
},
"theme": {
"light": "Light",
"dark": "Dark",
"system": "System"
},
"errors": {
"serverError": "Server error. Please try again later.",
"invalidCredentialsError": "Incorrect email or password",
"emailAlreadyExistsError": "This email is already in use",
"allFieldsRequired": "Please fill in all the fields"
}
}
+112
View File
@@ -0,0 +1,112 @@
{
"ChangeLanguage": "Cambia lingua",
"LoginPage": {
"title": "Benvenuto in Kotosoft ID",
"subtitle": "Il sistema ID unificato di Kotosoft",
"email": {
"title": "Email",
"invalid": "Inserisci un indirizzo email valido"
},
"password": {
"title": "Password",
"minLength": "La password deve contenere almeno 8 caratteri"
},
"required": "Questo campo è obbligatorio",
"login": "Accedi",
"noAccountNote": "Non hai ancora un account Kotosoft ID? Registrati <register>qui</register>."
},
"RegisterPage": {
"title": "Registrati a Kotosoft ID",
"subtitle": "Crea un account nel sistema ID unificato di Kotosoft",
"email": {
"title": "Email",
"invalid": "Inserisci un indirizzo email valido"
},
"password": {
"title": "Password",
"minLength": "La password deve contenere almeno 8 caratteri"
},
"firstName": {
"title": "Il tuo nome",
"minLength": "Il nome deve contenere almeno 2 caratteri",
"maxLength": "Il nome deve contenere al massimo 64 caratteri"
},
"secondName": {
"title": "Il tuo cognome",
"minLength": "Il cognome deve contenere almeno 2 caratteri",
"maxLength": "Il cognome deve contenere al massimo 64 caratteri"
},
"sex": {
"title": "Sesso",
"select": "Scegli il tuo sesso",
"male": "Maschile",
"female": "Femminile"
},
"required": "Questo campo è obbligatorio",
"next": "Avanti",
"back": "Indietro",
"register": "Registrati",
"hasAccountNote": "Hai già un account Kotosoft ID? Accedi <login>qui</login>."
},
"MePage": {
"loadError": "Qualcosa è andato storto. Impossibile caricare l'utente.",
"items": {
"profile": {
"title": "Profilo",
"form": {
"firstName": {
"title": "Il tuo nome",
"minLength": "Il nome deve contenere almeno 2 caratteri",
"maxLength": "Il nome deve contenere al massimo 64 caratteri"
},
"secondName": {
"title": "Il tuo cognome",
"minLength": "Il cognome deve contenere almeno 2 caratteri",
"maxLength": "Il cognome deve contenere al massimo 64 caratteri"
},
"birthdate": {
"title": "Data di nascita",
"pick": "Seleziona la tua data di nascita"
},
"required": "Questo campo è obbligatorio",
"save": "Salva",
"successfullyUpdated": "Il tuo profilo è aggiornato con successo!",
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
}
},
"applications": {
"title": "Applicazioni",
"authorized": "Autorizzato il",
"revoke": "Revoca"
},
"positions": {
"title": "Posizioni"
},
"logout": "Esci"
}
},
"ConsentPage": {
"title": "Accesso a {service}",
"subtitle": "{service} vuole accedere al tuo account Kotosoft ID per:",
"invalidSession": "Questa sessione non è valida. Torna all'applicazione e riprova.",
"scopes": {
"profile:read": "Visualizzare le informazioni del tuo profilo",
"profile:edit": "Modificare le informazioni del tuo profilo"
},
"allow": "Consenti",
"deny": "Annulla",
"toApp": "Torna all'applicazione",
"toHome": "Torna alla home"
},
"theme": {
"light": "Chiaro",
"dark": "Scuro",
"system": "Sistema"
},
"errors": {
"serverError": "Errore del server. Riprova più tardi.",
"invalidCredentialsError": "Email o password non corretti",
"emailAlreadyExistsError": "Questa email è già in uso",
"allFieldsRequired": "Inserisci tutti i campi, per favore"
}
}
+112
View File
@@ -0,0 +1,112 @@
{
"ChangeLanguage": "Поменять язык",
"LoginPage": {
"title": "Приветствуем в Kotosoft ID",
"subtitle": "Единой ID системе Дусибурга",
"email": {
"title": "Почта",
"invalid": "Пожалуйста, напишите правильный адрес почты"
},
"password": {
"title": "Пароль",
"minLength": "Пароль должен содержать не менее 8 символов"
},
"required": "Это поле является обязательным",
"login": "Вход",
"noAccountNote": "У Вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
},
"RegisterPage":{
"title": "Регистрация в Kotosoft ID",
"subtitle": "Создайте аккаунт в Единой ID системе Дусибурга",
"email": {
"title": "Почта",
"invalid": "Пожалуйста, напишите правильный адрес почты"
},
"password": {
"title": "Пароль",
"minLength": "Пароль должен содержать не менее 8 символов"
},
"firstName": {
"title": "Ваше имя",
"minLength": "Имя должно содержать не менее 2 символов",
"maxLength": "Имя должно содержать не более 64 символов"
},
"secondName": {
"title": "Ваша фамилия",
"minLength": "Фамилия должна содержать не менее 2 символов",
"maxLength": "Фамилия должна содержать не более 64 символов"
},
"sex": {
"title": "Пол",
"select": "Выберите Ваш пол",
"male": "Мужской",
"female": "Женский"
},
"required": "Это поле является обязательным",
"next": "Дальше",
"back": "Назад",
"register": "Зарегистрироваться",
"hasAccountNote": "У Вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
},
"MePage": {
"loadError": "Что-то пошло не так. Не получилось загрузить пользователя.",
"items": {
"profile": {
"title": "Профиль",
"form": {
"firstName": {
"title": "Ваше имя",
"minLength": "Имя должно содержать не менее 2 символов",
"maxLength": "Имя должно содержать не более 64 символов"
},
"secondName": {
"title": "Ваша фамилия",
"minLength": "Фамилия должна содержать не менее 2 символов",
"maxLength": "Фамилия должна содержать не более 64 символов"
},
"birthdate": {
"title": "Дата рождения",
"pick": "Выберите Вашу дату рождения"
},
"required": "Это поле является обязательным",
"save": "Сохранить",
"successfullyUpdated": "Профиль успешно обновлён!",
"updateError": "Произошла ошибка при обновлении. Попробуйте ещё раз позже."
}
},
"applications": {
"title": "Приложения",
"authorized": "Авторизировано",
"revoke": "Отозвать"
},
"positions": {
"title": "Должности"
},
"logout": "Выйти"
}
},
"ConsentPage": {
"title": "Вход в {service}",
"subtitle": "{service} хочет получить доступ к Вашему аккаунту Kotosoft ID, чтобы:",
"invalidSession": "Эта сессия недействительна. Пожалуйста, вернитесь в своё приложение и попробуйте ещё раз.",
"scopes": {
"profile:read": "Видеть данные Вашего профиля",
"profile:edit": "Изменять данные в Вашем профиле"
},
"allow": "Разрешить",
"deny": "Запретить",
"toApp": "Назад в приложение",
"toHome": "На главную"
},
"theme": {
"light": "Светлая",
"dark": "Тёмная",
"system": "Как в системе"
},
"errors": {
"serverError": "Ошибка сервера. Пожалуйста, попробуйте ещё раз позже.",
"invalidCredentialsError": "Неправильный адрес почты или пароль",
"emailAlreadyExistsError": "Аккаунт с такой почтой уже существует",
"allFieldsRequired": "Пожалуйста, заполните все поля"
}
}
+10
View File
@@ -0,0 +1,10 @@
import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
const nextConfig: NextConfig = {
/* config options here */
};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);
+47
View File
@@ -0,0 +1,47 @@
{
"name": "kotosoft-id-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.575.0",
"next": "16.1.6",
"next-intl": "^4.8.3",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "19.2.3",
"react-day-picker": "^9.14.0",
"react-dom": "19.2.3",
"react-hook-form": "^7.71.2",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"shadcn": "^3.8.5",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
},
"ignoreScripts": [
"sharp",
"unrs-resolver"
],
"trustedDependencies": [
"sharp",
"unrs-resolver"
]
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const PUBLIC_PATHS = ["/login", "/register", "/callback", "/oauth/error", "/callback/error"];
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const hasRefreshToken = request.cookies.has("refresh_token");
const isPublicPath = PUBLIC_PATHS.includes(pathname);
const session = request.nextUrl.searchParams.get("session");
if (hasRefreshToken && session && pathname === "/login") {
const accessToken = request.cookies.get("access_token")?.value;
try {
await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/attach`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
},
body: JSON.stringify({ session }),
});
} catch (error) {
console.error("Failed to attach session:", error);
return NextResponse.redirect(new URL("/callback/error", request.url));
}
return NextResponse.redirect(new URL(`/consent?session=${session}`, request.url));
}
if (hasRefreshToken && (isPublicPath || pathname === "/")) {
return NextResponse.redirect(new URL("/me", request.url));
}
if (!hasRefreshToken && !isPublicPath && !session || (!hasRefreshToken && pathname === "/")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}
+39
View File
@@ -0,0 +1,39 @@
import { enUS, it, ru } from "date-fns/locale";
export enum Sex {
MALE = "MALE",
FEMALE = "FEMALE"
}
export interface User {
email: string;
first_name: string;
second_name: string;
birth_date: string;
sex: Sex;
}
export interface OAuthSession {
client_id: string;
client_name: string;
redirect_uri: string;
scopes: string[];
state: string;
user_id?: string;
}
export interface Consent {
client_id: string
client_name: string
scopes: string[]
authorized_at: string
last_used_at: string | null
isRevokable: boolean
}
export const localeMap = {
ru,
en: enUS,
it
};