v2: fixed oauth errors, oauth clients native control added
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
"use server"
|
||||
|
||||
import type { CreatedOAuthClient, OAuthClient } from "@/types";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { tryRefresh, clearTokens } from "@/actions/auth";
|
||||
|
||||
interface CreateClientPayload {
|
||||
name: string;
|
||||
redirect_uris: string[];
|
||||
grant_types: string[];
|
||||
scopes: string[];
|
||||
}
|
||||
|
||||
interface UpdateClientPayload {
|
||||
name: string;
|
||||
redirect_uris: string[];
|
||||
scopes: string[];
|
||||
}
|
||||
|
||||
export async function fetchOAuthClients(): Promise<OAuthClient[] | []> {
|
||||
const store = await cookies();
|
||||
const accessToken = store.get("access_token")?.value;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients`, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await tryRefresh();
|
||||
if (!refreshed) {
|
||||
await clearTokens();
|
||||
return [];
|
||||
}
|
||||
return fetchOAuthClients();
|
||||
}
|
||||
|
||||
if (!response.ok) return [];
|
||||
return (await response.json()) as OAuthClient[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function createClient(
|
||||
payload: CreateClientPayload
|
||||
): Promise<{ success: boolean; client?: CreatedOAuthClient; message?: string }> {
|
||||
const t = await getTranslations("errors");
|
||||
const store = await cookies();
|
||||
const accessToken = store.get("access_token")?.value;
|
||||
|
||||
if (!payload.name || payload.redirect_uris.length === 0) {
|
||||
return { success: false, message: t("allFieldsRequired") };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await tryRefresh();
|
||||
if (!refreshed) {
|
||||
await clearTokens();
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
return createClient(payload);
|
||||
}
|
||||
|
||||
if (response.status === 400) return { success: false, message: t("invalidInputError") };
|
||||
if (!response.ok) return { success: false, message: t("serverError") };
|
||||
|
||||
const client = (await response.json()) as CreatedOAuthClient;
|
||||
return { success: true, client };
|
||||
} catch {
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateClient(
|
||||
id: string,
|
||||
payload: UpdateClientPayload
|
||||
): Promise<{ success: boolean; client?: OAuthClient; message?: string }> {
|
||||
const t = await getTranslations("errors");
|
||||
const store = await cookies();
|
||||
const accessToken = store.get("access_token")?.value;
|
||||
|
||||
if (!id || !payload.name || payload.redirect_uris.length === 0) {
|
||||
return { success: false, message: t("allFieldsRequired") };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await tryRefresh();
|
||||
if (!refreshed) {
|
||||
await clearTokens();
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
return updateClient(id, payload);
|
||||
}
|
||||
|
||||
if (response.status === 400) return { success: false, message: t("invalidInputError") };
|
||||
if (response.status === 404) return { success: false, message: t("notFoundError") };
|
||||
if (!response.ok) return { success: false, message: t("serverError") };
|
||||
|
||||
const client = (await response.json()) as OAuthClient;
|
||||
return { success: true, client };
|
||||
} catch {
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteClient(id: string): Promise<{ success: boolean; message?: string }> {
|
||||
const t = await getTranslations("errors");
|
||||
const store = await cookies();
|
||||
const accessToken = store.get("access_token")?.value;
|
||||
|
||||
if (!id) return { success: false, message: t("serverError") };
|
||||
|
||||
try {
|
||||
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/clients/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
const refreshed = await tryRefresh();
|
||||
if (!refreshed) {
|
||||
await clearTokens();
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
return deleteClient(id);
|
||||
}
|
||||
|
||||
if (!response.ok) return { success: false, message: t("serverError") };
|
||||
return { success: true };
|
||||
} catch {
|
||||
return { success: false, message: t("serverError") };
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
import { Consent } from "@/types"
|
||||
import { cookies } from "next/headers"
|
||||
|
||||
export async function fetchConsents() {
|
||||
const store = await cookies()
|
||||
const accessToken = store.get("access_token")?.value
|
||||
export async function fetchConsents(): Promise<Consent[] | []> {
|
||||
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`,
|
||||
@@ -14,16 +14,16 @@ export async function fetchConsents() {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
if (!response.ok) return []
|
||||
if (!response.ok) return [];
|
||||
|
||||
const consents = await response.json() as Consent[]
|
||||
const consents = await response.json() as Consent[];
|
||||
consents?.forEach((consent: Consent) => {
|
||||
consent.isRevokable = consent.client_id !== process.env.CLIENT_ID
|
||||
})
|
||||
});
|
||||
|
||||
return consents
|
||||
return consents;
|
||||
}
|
||||
|
||||
export async function revokeConsent(clientId: string) {
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
"use server"
|
||||
|
||||
import type { AdminUser, Permission, Position } from "@/types"
|
||||
import { cookies } from "next/headers"
|
||||
|
||||
async function getAccessToken(): Promise<string | null> {
|
||||
const store = await cookies()
|
||||
return store.get("access_token")?.value ?? null
|
||||
}
|
||||
|
||||
async function getAuthHeaders(locale?: string): Promise<HeadersInit> {
|
||||
const token = await getAccessToken()
|
||||
return token
|
||||
? {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Accept-Language": locale ?? "en",
|
||||
}
|
||||
: {}
|
||||
}
|
||||
|
||||
async function handleJsonResponse<T>(response: Response): Promise<T | null> {
|
||||
if (!response.ok) return null
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async function handleSuccessResponse(response: Response): Promise<{ success: boolean }> {
|
||||
return { success: response.ok }
|
||||
}
|
||||
|
||||
export async function fetchMyPositions(locale?: string): Promise<Position[]> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return []
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/positions`,
|
||||
{ headers: await getAuthHeaders(locale), cache: "no-store" }
|
||||
)
|
||||
|
||||
return (await handleJsonResponse<Position[]>(res)) ?? []
|
||||
}
|
||||
|
||||
export async function fetchAllPositions(locale?: string): Promise<Position[] | null> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return null
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`,
|
||||
{ headers: await getAuthHeaders(locale), cache: "no-store" }
|
||||
)
|
||||
|
||||
if (response.status === 403) return null
|
||||
return await handleJsonResponse<Position[]>(response)
|
||||
}
|
||||
|
||||
export async function savePosition(
|
||||
code: string,
|
||||
name: string,
|
||||
locale: string,
|
||||
description?: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
|
||||
method: "POST",
|
||||
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function fetchAllPermissions(locale?: string): Promise<Permission[]> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return []
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
|
||||
headers: await getAuthHeaders(locale),
|
||||
cache: "no-store",
|
||||
})
|
||||
|
||||
return (await handleJsonResponse<Permission[]>(res)) ?? []
|
||||
}
|
||||
|
||||
export async function fetchAdminUsers(locale?: string): Promise<AdminUser[] | null> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return null
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users`, {
|
||||
headers: await getAuthHeaders(locale),
|
||||
cache: "no-store",
|
||||
})
|
||||
|
||||
if (res.status === 403) return []
|
||||
return await handleJsonResponse<AdminUser[]>(res)
|
||||
}
|
||||
|
||||
export async function addPermission(code: string, description?: string, locale?: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions`, {
|
||||
method: "POST",
|
||||
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code, ...(description ? { description } : {}) }),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function editPermission(code: string, description?: string, locale?: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
|
||||
method: "PUT",
|
||||
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...(description ? { description } : {}) }),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function removePermission(code: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/permissions/${code}`, {
|
||||
method: "DELETE",
|
||||
headers: await getAuthHeaders(),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
function diffPermissions(oldP: string[], newP: string[]) {
|
||||
const oldSet = new Set(oldP)
|
||||
const newSet = new Set(newP)
|
||||
|
||||
const toAdd = newP.filter(p => !oldSet.has(p))
|
||||
const toRemove = oldP.filter(p => !newSet.has(p))
|
||||
|
||||
return { toAdd, toRemove }
|
||||
}
|
||||
|
||||
export async function syncPositionPermissions(
|
||||
positionCode: string,
|
||||
oldPermissions: string[],
|
||||
newPermissions: string[]
|
||||
) {
|
||||
const { toAdd, toRemove } = diffPermissions(oldPermissions, newPermissions)
|
||||
|
||||
await Promise.all([
|
||||
...toAdd.map(p => attachPermissionToPosition(positionCode, p)),
|
||||
...toRemove.map(p => detachPermissionFromPosition(positionCode, p)),
|
||||
])
|
||||
}
|
||||
|
||||
export async function attachPermissionToPosition(
|
||||
positionCode: string,
|
||||
permissionCode: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ permission_code: permissionCode }),
|
||||
}
|
||||
)
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function detachPermissionFromPosition(
|
||||
positionCode: string,
|
||||
permissionCode: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${positionCode}/permissions/${permissionCode}`,
|
||||
{ method: "DELETE", headers: await getAuthHeaders() }
|
||||
)
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function assignPositionToUser(
|
||||
userId: string,
|
||||
positionCode: string,
|
||||
validFrom?: string,
|
||||
validTo?: string
|
||||
): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { ...(await getAuthHeaders()), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
position_code: positionCode,
|
||||
...(validFrom ? { valid_from: validFrom } : {}),
|
||||
...(validTo ? { valid_to: validTo } : {}),
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function revokePositionFromUser(userId: string, positionCode: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/users/${userId}/positions/${positionCode}`,
|
||||
{ method: "DELETE", headers: await getAuthHeaders() }
|
||||
)
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function addPosition(code: string, name: string, description?: string, locale?: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions`, {
|
||||
method: "POST",
|
||||
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code, name, ...(description ? { description } : {}) }),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function editPosition(code: string, name: string, description?: string, locale?: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
|
||||
method: "PUT",
|
||||
headers: { ...(await getAuthHeaders(locale)), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, ...(description ? { description } : {}) }),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
|
||||
export async function deletePosition(code: string): Promise<{ success: boolean }> {
|
||||
const token = await getAccessToken()
|
||||
if (!token) return { success: false }
|
||||
|
||||
const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/admin/positions/${code}`, {
|
||||
method: "DELETE",
|
||||
headers: await getAuthHeaders(),
|
||||
})
|
||||
|
||||
return handleSuccessResponse(res)
|
||||
}
|
||||
@@ -2,109 +2,38 @@
|
||||
|
||||
import Header from "@/components/header";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import type { AdminUser, Consent, Permission, Position, User } from "@/types";
|
||||
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, ShieldIcon, UserIcon } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Consent, OAuthClient, User } from "@/types";
|
||||
import { AppWindowMacIcon, KeyIcon, LogOutIcon, UserIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Logout } from "@/actions/auth";
|
||||
import { fetchAdminUsers, fetchAllPermissions, fetchAllPositions } from "@/actions/positions";
|
||||
import Profile from "./items/profile";
|
||||
import Applications from "./items/applications";
|
||||
import Positions from "./items/positions";
|
||||
import Admin from "./items/admin";
|
||||
import Consents from "./items/consents";
|
||||
import Applications from "./items/applications/applications";
|
||||
|
||||
interface Props {
|
||||
userData: User | null;
|
||||
consentsData: Consent[] | null;
|
||||
permissionsData: Permission[] | null;
|
||||
positionsData: Position[] | null;
|
||||
adminUsersData: AdminUser[] | null;
|
||||
canManagePositions: boolean;
|
||||
canAssignPositions: boolean;
|
||||
canRevokePositions: boolean;
|
||||
canAccessAdmin: boolean;
|
||||
clientsData: OAuthClient[] | [];
|
||||
}
|
||||
|
||||
export default function MeClient({
|
||||
userData,
|
||||
consentsData,
|
||||
permissionsData,
|
||||
positionsData,
|
||||
adminUsersData,
|
||||
canManagePositions,
|
||||
canAssignPositions,
|
||||
canRevokePositions,
|
||||
canAccessAdmin,
|
||||
}: Props) {
|
||||
export default function MeClient({ userData, consentsData, clientsData }: Props) {
|
||||
const t = useTranslations("MePage");
|
||||
const locale = useLocale()
|
||||
const hydratedRef = useRef(false)
|
||||
|
||||
const [user, setUser] = useState(userData);
|
||||
const [consents, setConsents] = useState(consentsData);
|
||||
const [permissions, setPermissions] = useState(permissionsData);
|
||||
const [positions, setPositions] = useState(positionsData);
|
||||
const [adminUsers, setAdminUsers] = useState(adminUsersData);
|
||||
const [selectedItem, setSelectedItem] = useState(0);
|
||||
|
||||
|
||||
const baseItems = useMemo(() => [
|
||||
const items = useMemo(() => [
|
||||
{ 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 />, component: <Positions /> },
|
||||
], [t, user, consents])
|
||||
{ name: t("items.consents.title"), icon: <KeyIcon />, component: <Consents consents={consents} setConsents={setConsents} /> },
|
||||
...(user?.is_admin ? [
|
||||
{ name: t("items.applications.title"), icon: <AppWindowMacIcon />, component: <Applications clientsData={clientsData} /> }
|
||||
] : [])
|
||||
], [t, user, consents, clientsData]);
|
||||
|
||||
const adminItem = useMemo(() => canAccessAdmin
|
||||
? [{
|
||||
name: t("items.admin.title"),
|
||||
icon: <ShieldIcon />,
|
||||
component: (
|
||||
<Admin
|
||||
permissions={permissions}
|
||||
setPermissions={setPermissions}
|
||||
positions={positions}
|
||||
setPositions={setPositions}
|
||||
users={adminUsers}
|
||||
setUsers={setAdminUsers}
|
||||
canManagePositions={canManagePositions}
|
||||
canAssignPositions={canAssignPositions}
|
||||
canRevokePositions={canRevokePositions}
|
||||
/>
|
||||
),
|
||||
}]
|
||||
: [], [
|
||||
canAccessAdmin,
|
||||
t,
|
||||
permissions,
|
||||
positions,
|
||||
adminUsers,
|
||||
canManagePositions,
|
||||
canAssignPositions,
|
||||
canRevokePositions,
|
||||
]);
|
||||
|
||||
|
||||
const items = useMemo(() => [...baseItems, ...adminItem], [baseItems, adminItem])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hydratedRef.current) {
|
||||
hydratedRef.current = true
|
||||
return
|
||||
}
|
||||
if (!canAccessAdmin) return
|
||||
|
||||
if (canManagePositions) {
|
||||
fetchAllPermissions(locale).then((data) => setPermissions(data))
|
||||
}
|
||||
if (canManagePositions || canAssignPositions || canRevokePositions) {
|
||||
fetchAllPositions(locale).then((data) => setPositions(data))
|
||||
}
|
||||
if (canAssignPositions || canRevokePositions) {
|
||||
fetchAdminUsers(locale).then((data) => setAdminUsers(data ?? []))
|
||||
}
|
||||
}, [locale, canAccessAdmin, canManagePositions, canAssignPositions, canRevokePositions])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import type { AdminUser, Permission, Position } from "@/types"
|
||||
import Permissions from "./admin/permissions"
|
||||
import Positions from "./admin/positions";
|
||||
import UserPositions from "./admin/userPositions";
|
||||
|
||||
interface Props {
|
||||
permissions: Permission[] | null;
|
||||
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
|
||||
|
||||
positions: Position[] | null;
|
||||
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
|
||||
users: AdminUser[] | null;
|
||||
setUsers: React.Dispatch<React.SetStateAction<AdminUser[] | null>>;
|
||||
canManagePositions: boolean;
|
||||
canAssignPositions: boolean;
|
||||
canRevokePositions: boolean;
|
||||
}
|
||||
|
||||
export default function Admin({
|
||||
permissions,
|
||||
setPermissions,
|
||||
positions,
|
||||
setPositions,
|
||||
users,
|
||||
setUsers,
|
||||
canManagePositions,
|
||||
canAssignPositions,
|
||||
canRevokePositions,
|
||||
}: Props) {
|
||||
const t = useTranslations("MePage.items.admin")
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-xl flex flex-col gap-6">
|
||||
<h1 className="text-xl">{t("title")}</h1>
|
||||
<div className="space-y-8">
|
||||
{canManagePositions && (
|
||||
<>
|
||||
<Permissions permissions={permissions} setPermissions={setPermissions} />
|
||||
<Positions positions={positions} setPositions={setPositions} permissions={permissions} />
|
||||
</>
|
||||
)}
|
||||
{(canAssignPositions || canRevokePositions) && (
|
||||
<UserPositions
|
||||
users={users}
|
||||
setUsers={setUsers}
|
||||
positions={positions}
|
||||
canAssignPositions={canAssignPositions}
|
||||
canRevokePositions={canRevokePositions}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react";
|
||||
import { useForm, SubmitHandler } from "react-hook-form";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { addPermission, editPermission } from "@/actions/positions";
|
||||
import { toast } from "sonner";
|
||||
import { Check, X } from "lucide-react";
|
||||
import type { Permission } from "@/types";
|
||||
|
||||
interface CreateProps {
|
||||
mode: "create";
|
||||
trigger: React.ReactNode;
|
||||
onSuccess: (permission: Permission) => void;
|
||||
}
|
||||
|
||||
interface EditProps {
|
||||
mode: "edit";
|
||||
permission: Permission;
|
||||
trigger: React.ReactNode;
|
||||
onSuccess: (permission: Permission) => void;
|
||||
}
|
||||
|
||||
type Props = CreateProps | EditProps;
|
||||
|
||||
interface FormData {
|
||||
code: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export function PermissionDialog(props: Props) {
|
||||
const t = useTranslations("MePage.items.admin.permissions")
|
||||
const locale = useLocale()
|
||||
const isEdit = props.mode === "edit"
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||
defaultValues: isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" },
|
||||
})
|
||||
|
||||
function handleOpenChange(o: boolean) {
|
||||
setOpen(o)
|
||||
if (!o) reset(isEdit ? { code: props.permission.code, description: props.permission.description ?? "" } : { code: "", description: "" })
|
||||
}
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
const result = isEdit
|
||||
? await editPermission((props as EditProps).permission.code, data.description || undefined, locale)
|
||||
: await addPermission(data.code, data.description || undefined, locale)
|
||||
|
||||
if (!result.success) {
|
||||
toast(isEdit ? t("edit.error") : t("create.error"), { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
const updated: Permission = isEdit
|
||||
? { ...(props as EditProps).permission, description: data.description }
|
||||
: { id: crypto.randomUUID(), code: data.code, name: data.code, description: data.description, created_at: new Date().toISOString() }
|
||||
|
||||
toast(isEdit ? t("edit.success") : t("create.success"), { icon: <Check size={16} /> })
|
||||
props.onSuccess(updated)
|
||||
reset()
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.code}>
|
||||
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
|
||||
<Input
|
||||
id="code"
|
||||
disabled={isEdit || isSubmitting}
|
||||
aria-invalid={!!errors.code}
|
||||
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
|
||||
/>
|
||||
{errors.code && <FieldError>{errors.code.message}</FieldError>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
|
||||
<Input id="description" disabled={isSubmitting} {...register("description")} />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter className="mt-4">
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline" type="button">{isEdit ? t("edit.cancel") : t("create.cancel")}</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
{isEdit ? t("edit.save") : t("create.save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react";
|
||||
import { useForm, SubmitHandler } from "react-hook-form";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { addPosition, editPosition, syncPositionPermissions } from "@/actions/positions";
|
||||
import { toast } from "sonner";
|
||||
import { Check, X } from "lucide-react";
|
||||
import type { Permission, Position } from "@/types";
|
||||
|
||||
interface CreateProps {
|
||||
mode: "create";
|
||||
trigger: React.ReactNode;
|
||||
onSuccess: (position: Position) => void;
|
||||
allPermissions: Permission[] | null;
|
||||
}
|
||||
|
||||
interface EditProps {
|
||||
mode: "edit";
|
||||
position: Position;
|
||||
trigger: React.ReactNode;
|
||||
onSuccess: (position: Position) => void;
|
||||
allPermissions: Permission[] | null;
|
||||
}
|
||||
|
||||
type Props = CreateProps | EditProps;
|
||||
|
||||
interface FormData {
|
||||
code: string;
|
||||
name: string;
|
||||
description: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
function addPermissionToForm(current: string[], value: string): string[] {
|
||||
if (current.includes(value)) return current
|
||||
return [...current, value]
|
||||
}
|
||||
|
||||
function removePermissionFromForm(current: string[], value: string): string[] {
|
||||
return current.filter(p => p !== value)
|
||||
}
|
||||
|
||||
function togglePermissionInForm(current: string[], value: string): string[] {
|
||||
return current.includes(value) ?
|
||||
removePermissionFromForm(current, value) :
|
||||
addPermissionToForm(current, value)
|
||||
}
|
||||
|
||||
export function PositionDialog(props: Props) {
|
||||
const t = useTranslations("MePage.items.admin.positions")
|
||||
const locale = useLocale()
|
||||
const isEdit = props.mode === "edit"
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
const { register, handleSubmit, reset, formState: { errors, isSubmitting }, watch, setValue } = useForm<FormData>({
|
||||
defaultValues: isEdit
|
||||
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "", permissions: props.position.permissions.map(p => p.code) ?? [] }
|
||||
: { code: "", name: "", description: "", permissions: [] },
|
||||
})
|
||||
|
||||
function handleOpenChange(o: boolean) {
|
||||
setOpen(o)
|
||||
if (!o) {
|
||||
reset(isEdit
|
||||
? { code: props.position.code, name: props.position.name, description: props.position.description ?? "", permissions: props.position.permissions.map(p => p.code) ?? [] }
|
||||
: { code: "", name: "", description: "", permissions: [] }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
const positionCode = isEdit
|
||||
? (props as EditProps).position.code
|
||||
: data.code
|
||||
|
||||
const oldPermissions = isEdit
|
||||
? (props as EditProps).position.permissions.map(p => p.code)
|
||||
: []
|
||||
|
||||
const result = isEdit
|
||||
? await editPosition(positionCode, data.name, data.description, locale)
|
||||
: await addPosition(data.code, data.name, data.description, locale)
|
||||
|
||||
if (!result.success) {
|
||||
toast(isEdit ? t("edit.error") : t("create.error"), {
|
||||
icon: <X size={16} />,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await syncPositionPermissions(
|
||||
positionCode,
|
||||
oldPermissions,
|
||||
data.permissions
|
||||
)
|
||||
|
||||
const nextPermissions = data.permissions.map((permissionCode) => {
|
||||
const permission = props.allPermissions?.find((p) => p.code === permissionCode)
|
||||
return permission ?? { id: permissionCode, code: permissionCode, name: permissionCode, description: permissionCode, created_at: new Date().toISOString() }
|
||||
})
|
||||
|
||||
const updated: Position = {
|
||||
...(isEdit ? (props as EditProps).position : { code: data.code }),
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
permissions: nextPermissions,
|
||||
}
|
||||
|
||||
toast(isEdit ? t("edit.success") : t("create.success"), {
|
||||
icon: <Check size={16} />,
|
||||
})
|
||||
|
||||
props.onSuccess(updated)
|
||||
reset()
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const selectedPermissions = watch("permissions");
|
||||
|
||||
const togglePermission = (value: string) => {
|
||||
const updated = togglePermissionInForm(selectedPermissions, value)
|
||||
setValue("permissions", updated, { shouldDirty: true, shouldValidate: true })
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>{props.trigger}</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? t("edit.title") : t("create.title")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.code}>
|
||||
<FieldLabel htmlFor="code">{isEdit ? t("edit.code") : t("create.code")}</FieldLabel>
|
||||
<Input
|
||||
id="code"
|
||||
disabled={isEdit || isSubmitting}
|
||||
aria-invalid={!!errors.code}
|
||||
{...register("code", { validate: (v) => isEdit || v.trim().length > 0 || t("create.codeRequired") })}
|
||||
/>
|
||||
{errors.code && <FieldError>{errors.code.message}</FieldError>}
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="name">{isEdit ? t("edit.name") : t("create.name")}</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.name}
|
||||
{...register("name", { validate: (v) => v.trim().length > 0 || t("create.nameRequired") })}
|
||||
/>
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="description">{isEdit ? t("edit.description") : t("create.description")}</FieldLabel>
|
||||
<Input
|
||||
id="description"
|
||||
disabled={isSubmitting}
|
||||
{...register("description")}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="permissions">{t("permissions.label")}</FieldLabel>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{props.allPermissions?.length == 0 && <p className="text-sm text-muted-foreground">{t("permissions.empty")}</p>}
|
||||
{props.allPermissions?.map((p) => {
|
||||
const active = selectedPermissions.includes(p.code)
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={p.id}
|
||||
variant={active ? "default" : "ghost"}
|
||||
onClick={(e) => {e.preventDefault(); togglePermission(p.code)}}
|
||||
>
|
||||
{p.description || p.name || p.code}
|
||||
</Button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter className="mt-6">
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">{isEdit ? t("edit.cancel") : t("create.cancel")}</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner className="mr-2 size-4" />}
|
||||
{isEdit ? t("edit.save") : t("create.save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { MoreHorizontalIcon } from "lucide-react";
|
||||
import { Check, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { PermissionDialog } from "./dialogs/permissionDialog";
|
||||
import { removePermission } from "@/actions/positions";
|
||||
import type { Permission } from "@/types";
|
||||
|
||||
interface Props {
|
||||
permissions: Permission[] | null;
|
||||
setPermissions: React.Dispatch<React.SetStateAction<Permission[] | null>>;
|
||||
}
|
||||
|
||||
export default function Permissions({ permissions, setPermissions }: Props) {
|
||||
const t = useTranslations("MePage.items.admin.permissions")
|
||||
|
||||
function handleCreated(permission: Permission) {
|
||||
setPermissions((prev) => [...(prev || []), permission])
|
||||
}
|
||||
|
||||
function handleUpdated(code: string, permission: Permission) {
|
||||
setPermissions((prev) => (prev || []).map((p) => (p.code === code ? permission : p)))
|
||||
}
|
||||
|
||||
async function handleDelete(code: string) {
|
||||
const result = await removePermission(code)
|
||||
if (result.success) {
|
||||
setPermissions((prev) => (prev || []).filter((p) => p.code !== code))
|
||||
toast(t("delete.success"), { icon: <Check size={16} /> })
|
||||
} else {
|
||||
toast(t("delete.error"), { icon: <X size={16} /> })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-lg">{t("title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader className="rounded-lg">
|
||||
<TableRow>
|
||||
<TableHead>{t("columns.code")}</TableHead>
|
||||
<TableHead>{t("columns.description")}</TableHead>
|
||||
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{permissions?.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{permissions?.map((permission) => (
|
||||
<TableRow key={permission.code}>
|
||||
<TableCell className="font-mono">{permission.code}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{permission.description || permission.name || permission.code}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">{t("columns.actions")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<PermissionDialog
|
||||
mode="edit"
|
||||
permission={permission}
|
||||
onSuccess={(updated) => handleUpdated(permission.code, updated)}
|
||||
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
|
||||
/>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(permission.code)}>{t("actions.delete")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<PermissionDialog
|
||||
mode="create"
|
||||
onSuccess={handleCreated}
|
||||
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { MoreHorizontalIcon } from "lucide-react";
|
||||
import { Check, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { PositionDialog } from "./dialogs/positionDialog";
|
||||
import { deletePosition } from "@/actions/positions";
|
||||
import type { Permission, Position } from "@/types";
|
||||
|
||||
interface Props {
|
||||
positions: Position[] | null;
|
||||
permissions: Permission[] | null;
|
||||
setPositions: React.Dispatch<React.SetStateAction<Position[] | null>>;
|
||||
}
|
||||
|
||||
export default function Positions({ positions, permissions, setPositions }: Props) {
|
||||
const t = useTranslations("MePage.items.admin.positions")
|
||||
|
||||
function handleCreated(position: Position) {
|
||||
setPositions((prev) => [...(prev || []), position])
|
||||
}
|
||||
|
||||
function handleUpdated(code: string, position: Position) {
|
||||
setPositions((prev) => (prev || []).map((p) => (p.code === code ? position : p)))
|
||||
}
|
||||
|
||||
async function handleDelete(code: string) {
|
||||
const result = await deletePosition(code)
|
||||
if (result.success) {
|
||||
setPositions((prev) => (prev || []).filter((p) => p.code !== code))
|
||||
toast(t("delete.success"), { icon: <Check size={16} /> })
|
||||
} else {
|
||||
toast(t("delete.error"), { icon: <X size={16} /> })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-lg">{t("title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader className="rounded-lg">
|
||||
<TableRow>
|
||||
<TableHead>{t("columns.code")}</TableHead>
|
||||
<TableHead>{t("columns.name")}</TableHead>
|
||||
<TableHead>{t("columns.description")}</TableHead>
|
||||
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{positions?.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{positions?.map((position) => (
|
||||
<TableRow key={position.code}>
|
||||
<TableCell className="font-mono">{position.code}</TableCell>
|
||||
<TableCell>{position.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{position.description || t("noDescription")}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">{t("columns.actions")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<PositionDialog
|
||||
mode="edit"
|
||||
position={position}
|
||||
onSuccess={(updated) => handleUpdated(position.code, updated)}
|
||||
trigger={<Button variant="ghost" size="sm" className="w-full px-2 justify-start">{t("actions.edit")}</Button>}
|
||||
allPermissions={permissions}
|
||||
/>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => handleDelete(position.code)}>{t("actions.delete")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<PositionDialog
|
||||
mode="create"
|
||||
onSuccess={handleCreated}
|
||||
trigger={<Button variant="outline" size="sm" className="w-full">{t("actions.create")}</Button>}
|
||||
allPermissions={permissions}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { assignPositionToUser, revokePositionFromUser } from "@/actions/positions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import type { AdminUser, Position } from "@/types";
|
||||
import { Check, MoreHorizontalIcon, X } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Props {
|
||||
users: AdminUser[] | null;
|
||||
setUsers: React.Dispatch<React.SetStateAction<AdminUser[] | null>>;
|
||||
positions: Position[] | null;
|
||||
canAssignPositions: boolean;
|
||||
canRevokePositions: boolean;
|
||||
}
|
||||
|
||||
export default function UserPositions({
|
||||
users,
|
||||
setUsers,
|
||||
positions,
|
||||
canAssignPositions,
|
||||
canRevokePositions,
|
||||
}: Props) {
|
||||
const t = useTranslations("MePage.items.admin.userPositions")
|
||||
|
||||
async function handleAssign(userId: string, positionCode: string) {
|
||||
const result = await assignPositionToUser(userId, positionCode)
|
||||
if (!result.success) {
|
||||
toast(t("assign.error"), { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
const added = positions?.find((p) => p.code === positionCode)
|
||||
if (added) {
|
||||
setUsers((prev) => (prev || []).map((u) => {
|
||||
if (u.id !== userId) return u
|
||||
if (u.positions.some((p) => p.code === positionCode)) return u
|
||||
return { ...u, positions: [...u.positions, added] }
|
||||
}))
|
||||
}
|
||||
|
||||
toast(t("assign.success"), { icon: <Check size={16} /> })
|
||||
}
|
||||
|
||||
async function handleRevoke(userId: string, positionCode: string) {
|
||||
const result = await revokePositionFromUser(userId, positionCode)
|
||||
if (!result.success) {
|
||||
toast(t("revoke.error"), { icon: <X size={16} /> })
|
||||
return
|
||||
}
|
||||
|
||||
setUsers((prev) => (prev || []).map((u) => (
|
||||
u.id === userId
|
||||
? { ...u, positions: u.positions.filter((p) => p.code !== positionCode) }
|
||||
: u
|
||||
)))
|
||||
|
||||
toast(t("revoke.success"), { icon: <Check size={16} /> })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-lg">{t("title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader className="rounded-lg">
|
||||
<TableRow>
|
||||
<TableHead>{t("columns.user")}</TableHead>
|
||||
<TableHead>{t("columns.positions")}</TableHead>
|
||||
<TableHead className="text-right">{t("columns.actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users === null && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("loadError")}</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{users?.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} className="text-center text-sm text-muted-foreground py-6">{t("empty")}</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{users?.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<div className="flex flex-col">
|
||||
<span>{user.first_name} {user.second_name}</span>
|
||||
<span className="text-xs text-muted-foreground">{user.email}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{user.positions.length === 0 && <span className="text-sm text-muted-foreground">{t("noPositions")}</span>}
|
||||
{user.positions.map((position) => (
|
||||
<Badge key={position.code} variant="secondary">{position.name || position.code}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontalIcon />
|
||||
<span className="sr-only">{t("columns.actions")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{canAssignPositions && (positions || []).map((position) => (
|
||||
<DropdownMenuItem
|
||||
key={`assign-${user.id}-${position.code}`}
|
||||
disabled={user.positions.some((p) => p.code === position.code)}
|
||||
onClick={() => handleAssign(user.id, position.code)}
|
||||
>
|
||||
{t("actions.assign")} {position.name}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{canAssignPositions && (user.positions.filter(p => p.code !== "kotosoft_id_staff")).length > 0 && canRevokePositions && <DropdownMenuSeparator />}
|
||||
{canRevokePositions && user.positions.filter(p => p.code !== "kotosoft_id_staff").map((position) => (
|
||||
<DropdownMenuItem
|
||||
key={`revoke-${user.id}-${position.code}`}
|
||||
variant="destructive"
|
||||
onClick={() => handleRevoke(user.id, position.code)}
|
||||
>
|
||||
{t("actions.revoke")} {position.name}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { OAuthClient } from "@/types";
|
||||
import { useState } from "react";
|
||||
import { DataTable } from "./table";
|
||||
import { useColumns } from "./columns";
|
||||
import { CreateClientDialog } from "./createClientDialog";
|
||||
import { UpdateClientDialog } from "./updateClientDialog";
|
||||
|
||||
interface Props {
|
||||
clientsData: OAuthClient[];
|
||||
}
|
||||
|
||||
export default function Applications({ clientsData }: Props) {
|
||||
const t = useTranslations("MePage.items.applications");
|
||||
const [editingClient, setEditingClient] = useState<OAuthClient | null>(null);
|
||||
const [clients, setClients] = useState<OAuthClient[] | []>(clientsData);
|
||||
const columns = useColumns({ setClients, setEditingClient });
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-2xl flex flex-col gap-8">
|
||||
<div className="lg:max-w-sm space-y-2">
|
||||
<h1 className="text-xl">{t("title")}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t("subtitle")}</p>
|
||||
</div>
|
||||
<CreateClientDialog setClients={setClients} />
|
||||
<UpdateClientDialog client={editingClient} onClose={() => setEditingClient(null)} setClients={setClients} />
|
||||
<div className="space-y-4">
|
||||
{clients.length > 0 ? <DataTable columns={columns} data={clients || []} /> : <h2 className="text-muted-foreground text-lg">{t("noApplications")}</h2>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
"use client"
|
||||
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { Dispatch, SetStateAction, useMemo } from "react";
|
||||
import { type DataTableFeatures } from "./features";
|
||||
import { OAuthClient } from "@/types";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { BanIcon, MoreHorizontal, PencilIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { deleteClient } from "@/actions/clients";
|
||||
|
||||
const columnHelper = createColumnHelper<DataTableFeatures, OAuthClient>();
|
||||
|
||||
async function handleDisable({ id, setClients }: { id: string; setClients: Dispatch<SetStateAction<OAuthClient[] | []>> }) {
|
||||
try {
|
||||
await deleteClient(id);
|
||||
setClients((prev) => prev ? prev.map((c) => c.id === id ? { ...c, is_active: false } : c) : prev);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function useColumns({ setClients, setEditingClient }: { setClients: Dispatch<SetStateAction<OAuthClient[] | []>>; setEditingClient: Dispatch<SetStateAction<OAuthClient | null>>; }) {
|
||||
const t = useTranslations("MePage.items.applications.table");
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
columnHelper.columns([
|
||||
columnHelper.accessor("name", {
|
||||
header: t("client"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<h4>{row.getValue("name")}</h4>
|
||||
<h5 className="text-xs text-muted-foreground">
|
||||
{row.original.client_id}
|
||||
</h5>
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("redirect_uris", {
|
||||
header: t("redirectURIs"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-row gap-1 flex-wrap">
|
||||
{(row.getValue("redirect_uris") as string[]).map((url) => (
|
||||
<Badge key={url} variant="secondary">
|
||||
{url}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("scopes", {
|
||||
header: t("scopes"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-row gap-1 flex-wrap">
|
||||
{(row.getValue("scopes") as string[]).map((scope) => (
|
||||
<Badge key={scope} variant="secondary">
|
||||
{scope}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("is_active", {
|
||||
header: t("status"),
|
||||
cell: ({ row }) => {
|
||||
return row.getValue("is_active") === true ? t("active") : t("disabled")
|
||||
},
|
||||
}),
|
||||
|
||||
columnHelper.display({
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
const client = row.original;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditingClient(client)}><PencilIcon />{t("edit")}</DropdownMenuItem>
|
||||
{client.is_active && <DropdownMenuItem onClick={() => handleDisable({ id: client.id, setClients })}><BanIcon />{t("disable")}</DropdownMenuItem>}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
},
|
||||
}),
|
||||
]),
|
||||
[t, setClients, setEditingClient]
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Field, FieldError, FieldGroup, FieldLabel, FieldDescription } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Dispatch, SetStateAction, useState } from "react";
|
||||
import { useFieldArray, useForm, Controller, SubmitHandler } from "react-hook-form";
|
||||
import { Plus, Trash2, Copy, Check } from "lucide-react";
|
||||
import { createClient } from "@/actions/clients";
|
||||
import type { CreatedOAuthClient, OAuthClient } from "@/types";
|
||||
|
||||
interface FormData {
|
||||
name: string;
|
||||
redirect_uris: { value: string }[];
|
||||
scopes: string[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
setClients: Dispatch<SetStateAction<OAuthClient[] | []>>;
|
||||
}
|
||||
|
||||
const GRANT_TYPES = ["authorization_code", "refresh_token"] as const;
|
||||
const SCOPES = ["profile:read", "profile:edit"] as const;
|
||||
|
||||
export function CreateClientDialog({ setClients }: Props) {
|
||||
const t = useTranslations("MePage.items.applications.dialog");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [createdClient, setCreatedClient] = useState<CreatedOAuthClient | null>(null);
|
||||
const [copied, setCopied] = useState<"id" | "secret" | null>(null);
|
||||
|
||||
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
redirect_uris: [{ value: "" }],
|
||||
scopes: [],
|
||||
},
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control,
|
||||
name: "redirect_uris",
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
setError(null);
|
||||
|
||||
const result = await createClient({
|
||||
name: data.name,
|
||||
redirect_uris: data.redirect_uris.map((r) => r.value).filter(Boolean),
|
||||
grant_types: [...GRANT_TYPES],
|
||||
scopes: data.scopes,
|
||||
});
|
||||
|
||||
if (!result.success || !result.client) {
|
||||
setError(result.message ?? null);
|
||||
return;
|
||||
}
|
||||
|
||||
setClients((prev) => (prev ? [...prev, result.client!] : [result.client!]));
|
||||
setCreatedClient(result.client);
|
||||
};
|
||||
|
||||
const handleCopy = async (value: string, key: "id" | "secret") => {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(key);
|
||||
setTimeout(() => setCopied(null), 2000);
|
||||
};
|
||||
|
||||
const handleClose = (open: boolean) => {
|
||||
setIsOpen(open);
|
||||
if (!open) {
|
||||
reset();
|
||||
setCreatedClient(null);
|
||||
setError(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="w-max">{t("trigger")}</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent onInteractOutside={(e) => createdClient && e.preventDefault()}>
|
||||
{!createdClient ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("title")}</DialogTitle>
|
||||
<DialogDescription>{t("subtitle")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="name">{t("name.title")}</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.name}
|
||||
{...register("name", {
|
||||
required: t("required"),
|
||||
minLength: { value: 2, message: t("name.minLength") },
|
||||
maxLength: { value: 128, message: t("name.maxLength") },
|
||||
})}
|
||||
/>
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>{t("redirectUris.title")}</FieldLabel>
|
||||
<div className="flex flex-col gap-2">
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="flex gap-2">
|
||||
<Input
|
||||
disabled={isSubmitting}
|
||||
placeholder={t("redirectUris.placeholder")}
|
||||
{...register(`redirect_uris.${index}.value` as const, {
|
||||
required: index === 0 ? t("required") : false,
|
||||
pattern: {
|
||||
value: /^https?:\/\/.+/,
|
||||
message: t("redirectUris.invalid"),
|
||||
},
|
||||
})}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
disabled={isSubmitting || fields.length === 1}
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{errors.redirect_uris?.[0]?.value && (
|
||||
<FieldError>{errors.redirect_uris[0]?.value?.message}</FieldError>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isSubmitting}
|
||||
onClick={() => append({ value: "" })}
|
||||
>
|
||||
<Plus />
|
||||
{t("redirectUris.add")}
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.scopes}>
|
||||
<FieldLabel>{t("scopes.title")}</FieldLabel>
|
||||
<Controller
|
||||
name="scopes"
|
||||
control={control}
|
||||
rules={{ required: t("required") }}
|
||||
render={({ field }) => (
|
||||
<div className="flex flex-col gap-2">
|
||||
{SCOPES.map((scope) => (
|
||||
<label key={scope} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
disabled={isSubmitting}
|
||||
checked={field.value.includes(scope)}
|
||||
onCheckedChange={(checked) => {
|
||||
field.onChange(
|
||||
checked
|
||||
? [...field.value, scope]
|
||||
: field.value.filter((s) => s !== scope)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{t(`scopes.${scope}`)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{errors.scopes && <FieldError>{errors.scopes.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
{error && <FieldError className="text-center">{error}</FieldError>}
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
{t("submit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("secretReveal.title")}</DialogTitle>
|
||||
<DialogDescription>{t("secretReveal.subtitle")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel>{t("secretReveal.clientId")}</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input readOnly value={createdClient.client_id} className="font-mono text-sm" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleCopy(createdClient.client_id, "id")}
|
||||
>
|
||||
{copied === "id" ? <Check /> : <Copy />}
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>{t("secretReveal.clientSecret")}</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input readOnly value={createdClient.client_secret} className="font-mono text-sm" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleCopy(createdClient.client_secret, "secret")}
|
||||
>
|
||||
{copied === "secret" ? <Check /> : <Copy />}
|
||||
</Button>
|
||||
</div>
|
||||
<FieldDescription className="text-destructive">
|
||||
{t("secretReveal.warning")}
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button onClick={() => handleClose(false)}>
|
||||
{t("secretReveal.confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
columnFilteringFeature,
|
||||
columnVisibilityFeature,
|
||||
createFilteredRowModel,
|
||||
createPaginatedRowModel,
|
||||
createSortedRowModel,
|
||||
filterFn_includesString,
|
||||
rowPaginationFeature,
|
||||
rowSelectionFeature,
|
||||
rowSortingFeature,
|
||||
sortFn_alphanumeric,
|
||||
sortFn_text,
|
||||
tableFeatures,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
export const features = tableFeatures({
|
||||
columnFilteringFeature,
|
||||
columnVisibilityFeature,
|
||||
rowPaginationFeature,
|
||||
rowSelectionFeature,
|
||||
rowSortingFeature,
|
||||
filteredRowModel: createFilteredRowModel(),
|
||||
paginatedRowModel: createPaginatedRowModel(),
|
||||
sortedRowModel: createSortedRowModel(),
|
||||
filterFns: { includesString: filterFn_includesString },
|
||||
sortFns: { alphanumeric: sortFn_alphanumeric, text: sortFn_text },
|
||||
});
|
||||
|
||||
export type DataTableFeatures = typeof features;
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client"
|
||||
|
||||
import { useTable, type ColumnDef, type RowData } from "@tanstack/react-table";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { features, type DataTableFeatures } from "./features";
|
||||
|
||||
interface DataTableProps<TData extends RowData> {
|
||||
columns: ColumnDef<DataTableFeatures, TData>[];
|
||||
data: TData[];
|
||||
}
|
||||
|
||||
export function DataTable<TData extends RowData>({ columns, data }: DataTableProps<TData>) {
|
||||
const table = useTable({ features, data, columns });
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<table.FlexRender header={header} />
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length > 0 && (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
<table.FlexRender cell={cell} />
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
"use client"
|
||||
|
||||
import { Dispatch, SetStateAction, useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Field, 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 { useFieldArray, useForm, Controller, SubmitHandler } from "react-hook-form";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { updateClient } from "@/actions/clients";
|
||||
import type { OAuthClient } from "@/types";
|
||||
|
||||
interface FormData {
|
||||
name: string;
|
||||
redirect_uris: { value: string }[];
|
||||
scopes: string[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
client: OAuthClient | null;
|
||||
onClose: () => void;
|
||||
setClients: Dispatch<SetStateAction<OAuthClient[] | []>>;
|
||||
}
|
||||
|
||||
const SCOPES = ["profile:read", "profile:edit"] as const;
|
||||
|
||||
export function UpdateClientDialog({ client, onClose, setClients }: Props) {
|
||||
const t = useTranslations("MePage.items.applications.dialog");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting }} = useForm<FormData>({
|
||||
defaultValues: { name: "", redirect_uris: [{ value: "" }], scopes: [] },
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control,
|
||||
name: "redirect_uris",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (client) {
|
||||
reset({
|
||||
name: client.name,
|
||||
redirect_uris: client.redirect_uris.map((value) => ({ value })),
|
||||
scopes: client.scopes,
|
||||
});
|
||||
}
|
||||
}, [client, reset]);
|
||||
|
||||
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||
if (!client) return;
|
||||
setError(null);
|
||||
|
||||
const result = await updateClient(client.id, {
|
||||
name: data.name,
|
||||
redirect_uris: data.redirect_uris.map((r) => r.value).filter(Boolean),
|
||||
scopes: data.scopes,
|
||||
});
|
||||
|
||||
if (!result.success || !result.client) {
|
||||
setError(result.message ?? null);
|
||||
return;
|
||||
}
|
||||
|
||||
setClients((prev) =>
|
||||
prev ? prev.map((c) => (c.id === result.client!.id ? result.client! : c)) : prev
|
||||
);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={!!client} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("editTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("editSubtitle")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="name">{t("name.title")}</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={!!errors.name}
|
||||
{...register("name", {
|
||||
required: t("required"),
|
||||
minLength: { value: 2, message: t("name.minLength") },
|
||||
maxLength: { value: 128, message: t("name.maxLength") },
|
||||
})}
|
||||
/>
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>{t("redirectUris.title")}</FieldLabel>
|
||||
<div className="flex flex-col gap-2">
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="flex gap-2">
|
||||
<Input
|
||||
disabled={isSubmitting}
|
||||
placeholder={t("redirectUris.placeholder")}
|
||||
{...register(`redirect_uris.${index}.value` as const, {
|
||||
required: index === 0 ? t("required") : false,
|
||||
pattern: { value: /^https?:\/\/.+/, message: t("redirectUris.invalid") },
|
||||
})}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
disabled={isSubmitting || fields.length === 1}
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{errors.redirect_uris?.[0]?.value && (
|
||||
<FieldError>{errors.redirect_uris[0]?.value?.message}</FieldError>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isSubmitting}
|
||||
onClick={() => append({ value: "" })}
|
||||
>
|
||||
<Plus />
|
||||
{t("redirectUris.add")}
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.scopes}>
|
||||
<FieldLabel>{t("scopes.title")}</FieldLabel>
|
||||
<Controller
|
||||
name="scopes"
|
||||
control={control}
|
||||
rules={{ required: t("required") }}
|
||||
render={({ field }) => (
|
||||
<div className="flex flex-col gap-2">
|
||||
{SCOPES.map((scope) => (
|
||||
<label key={scope} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
disabled={isSubmitting}
|
||||
checked={field.value.includes(scope)}
|
||||
onCheckedChange={(checked) => {
|
||||
field.onChange(
|
||||
checked ? [...field.value, scope] : field.value.filter((s) => s !== scope)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{t(`scopes.${scope}`)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{errors.scopes && <FieldError>{errors.scopes.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
{error && <FieldError className="text-center">{error}</FieldError>}
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Spinner />}
|
||||
{t("editSubmit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -18,8 +18,8 @@ interface Props {
|
||||
setConsents: (consents: Consent[]) => void;
|
||||
}
|
||||
|
||||
export default function Applications({ consents, setConsents }: Props) {
|
||||
const t = useTranslations("MePage.items.applications");
|
||||
export default function Consents({ consents, setConsents }: Props) {
|
||||
const t = useTranslations("MePage.items.consents");
|
||||
const [list, setList] = useState(consents);
|
||||
const [revokingId, setRevokingId] = useState<string | null>(null);
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useLocale, useTranslations } from "next-intl"
|
||||
import type { Position } from "@/types"
|
||||
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { fetchMyPositions } from "@/actions/positions"
|
||||
|
||||
const positionsCache: Record<string, Position[]> = {}
|
||||
|
||||
export default function Positions() {
|
||||
const t = useTranslations("MePage.items.positions")
|
||||
const locale = useLocale()
|
||||
const [positions, setPositions] = useState<Position[] | null>(
|
||||
() => positionsCache[locale] ?? null
|
||||
)
|
||||
const [loading, setLoading] = useState(!positionsCache[locale])
|
||||
|
||||
useEffect(() => {
|
||||
if (positionsCache[locale]) return
|
||||
|
||||
fetchMyPositions(locale)
|
||||
.then((data) => {
|
||||
positionsCache[locale] = data
|
||||
setPositions(data)
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [locale])
|
||||
|
||||
return (
|
||||
<div className="w-full lg:max-w-sm flex flex-col gap-4">
|
||||
<h1 className="text-xl">{t("title")}</h1>
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Spinner />
|
||||
<span>{t("loading")}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && (
|
||||
<div className="space-y-4">
|
||||
{positions && positions.length > 0 ? (
|
||||
positions.map((position) => (
|
||||
<Item key={position.code}>
|
||||
<ItemContent>
|
||||
<ItemTitle>{position.name}</ItemTitle>
|
||||
{position.description && (
|
||||
<ItemDescription>{position.description}</ItemDescription>
|
||||
)}
|
||||
{position.permissions.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-2">
|
||||
{position.permissions.map((perm) => (
|
||||
<Badge key={perm.code} variant="secondary" className="text-xs">
|
||||
{perm.description}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ItemContent>
|
||||
</Item>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">{t("empty")}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,45 +1,27 @@
|
||||
import { fetchUser } from "@/actions/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import MeComponent from "./component";
|
||||
|
||||
import { fetchConsents } from "@/actions/consents";
|
||||
import { fetchAllPositions, fetchAllPermissions, fetchAdminUsers, fetchMyPositions } from "@/actions/positions";
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { fetchOAuthClients } from "@/actions/clients";
|
||||
|
||||
export default async function Me() {
|
||||
const locale = await getLocale();
|
||||
const user = await fetchUser();
|
||||
|
||||
if (!user) {
|
||||
redirect("/api/auth/initiate");
|
||||
}
|
||||
|
||||
const [consents, myPositions] = await Promise.all([
|
||||
const [consents, clients] = await Promise.all([
|
||||
fetchConsents(),
|
||||
fetchMyPositions(locale),
|
||||
]);
|
||||
const granted = new Set(myPositions.flatMap((position) => position.permissions.map((p) => p.code)));
|
||||
const canManage = granted.has("positions.manage");
|
||||
const canAssign = granted.has("positions.assign");
|
||||
const canRevoke = granted.has("positions.revoke");
|
||||
const canAccessAdmin = canManage || canAssign || canRevoke;
|
||||
|
||||
const [permissions, positions, adminUsers] = await Promise.all([
|
||||
canAccessAdmin && canManage ? fetchAllPermissions(locale) : Promise.resolve<null>(null),
|
||||
canAccessAdmin && (canManage || canAssign || canRevoke) ? fetchAllPositions(locale) : Promise.resolve<null>(null),
|
||||
canAccessAdmin && (canAssign || canRevoke) ? fetchAdminUsers(locale).then((data) => data ?? []) : Promise.resolve<null>(null),
|
||||
fetchOAuthClients(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<MeComponent
|
||||
userData={user}
|
||||
consentsData={consents}
|
||||
permissionsData={permissions}
|
||||
positionsData={positions}
|
||||
adminUsersData={adminUsers}
|
||||
canManagePositions={canManage}
|
||||
canAssignPositions={canAssign}
|
||||
canRevokePositions={canRevoke}
|
||||
canAccessAdmin={canAccessAdmin}
|
||||
clientsData={clients}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,30 +5,32 @@
|
||||
"": {
|
||||
"name": "kotosoft-id-frontend",
|
||||
"dependencies": {
|
||||
"@tanstack/react-table": "^9.2.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"cn": "^0.3.0",
|
||||
"date-fns": "^4.4.0",
|
||||
"lucide-react": "^0.575.0",
|
||||
"next": "^16.2.3",
|
||||
"next-intl": "^4.9.1",
|
||||
"next": "^16.2.9",
|
||||
"next-intl": "^4.13.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"radix-ui": "^1.4.3",
|
||||
"radix-ui": "^1.5.0",
|
||||
"react": "19.2.3",
|
||||
"react-day-picker": "^9.14.0",
|
||||
"react-dom": "19.2.3",
|
||||
"react-hook-form": "^7.72.1",
|
||||
"react-hook-form": "^7.78.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.2.2",
|
||||
"@types/node": "^20.19.39",
|
||||
"@types/react": "^19.2.14",
|
||||
"@tailwindcss/postcss": "^4.3.0",
|
||||
"@types/node": "^20.19.42",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-next": "16.1.6",
|
||||
"shadcn": "^3.8.5",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5.9.3",
|
||||
},
|
||||
@@ -489,6 +491,14 @@
|
||||
|
||||
"@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.0", "@tailwindcss/oxide": "4.3.0", "postcss": "^8.5.10", "tailwindcss": "4.3.0" } }, "sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w=="],
|
||||
|
||||
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.11.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ=="],
|
||||
|
||||
"@tanstack/react-table": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/react-store": "^0.11.1", "@tanstack/table-core": "9.2.4" }, "peerDependencies": { "react": ">=18" } }, "sha512-Rzp1Q4e0/nIgEjmISYR5HeEgLTNtrG+C7NFZf/AbCxPO5hg+zC3yNGwcoECigUk8SFzzvhXbd2rFdtP2ZiGrfA=="],
|
||||
|
||||
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA=="],
|
||||
|
||||
"@tanstack/table-core": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.11.1" } }, "sha512-GwdDyGGr6UXAtubF14yAwcXvdaogqfsQgIk89Suebjxob/Rjq2xvfmXsjDF1rQmKmhHsJm9TOY7myxv3i6geJw=="],
|
||||
|
||||
"@ts-morph/common": ["@ts-morph/[email protected]", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="],
|
||||
|
||||
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
||||
@@ -661,6 +671,8 @@
|
||||
|
||||
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"cn": ["[email protected]", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-qRoU0ARrZD3Bbj1wKFftEKxPjSnzTEdFkf22NVhW+zU9D/wajhoP+qUZ5DChhhSOBCH1onV12hrmGqfu1+5Z2Q=="],
|
||||
|
||||
"code-block-writer": ["[email protected]", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="],
|
||||
|
||||
"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
|
||||
@@ -1481,6 +1493,8 @@
|
||||
|
||||
"use-sidecar": ["[email protected]", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
|
||||
|
||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"validate-npm-package-name": ["[email protected]", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="],
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "cn"
|
||||
import { Checkbox as CheckboxPrimitive } from "radix-ui"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
|
||||
>
|
||||
<CheckIcon
|
||||
/>
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
@@ -57,7 +56,7 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -74,130 +74,61 @@
|
||||
"updateError": "An error occurred during the update. Please try again later."
|
||||
}
|
||||
},
|
||||
"applications": {
|
||||
"title": "Applications",
|
||||
"consents": {
|
||||
"title": "Consents",
|
||||
"subtitle": "Here you can review and revoke concents for connected applications.",
|
||||
"authorized": "Autorized on",
|
||||
"revoke": "Revoke",
|
||||
"successfullyRevoked": "Access successfully revoked!",
|
||||
"revocationError": "Failed to revoke access"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Positions",
|
||||
"loading": "Loading positions...",
|
||||
"empty": "No positions assigned"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Administration",
|
||||
"permissions": {
|
||||
"title": "Permissions",
|
||||
"subtitle": "Permissions can be assigned to positions to control access.",
|
||||
"empty": "There're no permissions yet",
|
||||
"noDescription": "No description",
|
||||
"columns": {
|
||||
"code": "Code",
|
||||
"description": "Description",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"create": "Create permission"
|
||||
},
|
||||
"create": {
|
||||
"title": "Create permission",
|
||||
"code": "Code",
|
||||
"description": "Description",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save",
|
||||
"codeRequired": "Code is required",
|
||||
"success": "Permission successfully created!",
|
||||
"error": "Failed to create permission"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Edit permission",
|
||||
"code": "Code",
|
||||
"description": "Description",
|
||||
"cancel": "Cancel",
|
||||
"save": "Update",
|
||||
"success": "Permission successfully updated!",
|
||||
"error": "Failed to update permission"
|
||||
},
|
||||
"delete": {
|
||||
"success": "Permission successfully deleted!",
|
||||
"error": "Failed to delete permission"
|
||||
}
|
||||
"applications": {
|
||||
"title": "Applications",
|
||||
"subtitle": "Here you can connect your own applications to Kotosoft ID to provide your users an easy way to authorize.",
|
||||
"table": {
|
||||
"client": "Client",
|
||||
"redirectURIs": "Redirect URIs",
|
||||
"scopes": "Scopes",
|
||||
"status": "Status",
|
||||
"active": "Active",
|
||||
"disabled": "Disabled",
|
||||
"disable": "Disable this appplication",
|
||||
"edit": "Edit this application"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Positions",
|
||||
"subtitle": "Manage positions and assign permissions to control access.",
|
||||
"empty": "There're no positions yet",
|
||||
"noDescription": "No description",
|
||||
"columns": {
|
||||
"code": "Code",
|
||||
"name": "Name",
|
||||
"description": "Description",
|
||||
"actions": "Actions"
|
||||
"noApplications": "You don't have any connected applications yet",
|
||||
"dialog": {
|
||||
"trigger": "Connect application",
|
||||
"title": "Connect a new application",
|
||||
"subtitle": "Enter the details of your application to connect it.",
|
||||
"required": "This field is required",
|
||||
"name": {
|
||||
"title": "Application name",
|
||||
"minLength": "Name must be at least 2 characters",
|
||||
"maxLength": "Name must be at most 128 characters"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"create": "Create position"
|
||||
"editTitle": "Edit application",
|
||||
"editSubtitle": "Update your application's details.",
|
||||
"editSubmit": "Save changes",
|
||||
"redirectUris": {
|
||||
"title": "Redirect URIs",
|
||||
"placeholder": "https://example.com/callback",
|
||||
"add": "Add another URI",
|
||||
"invalid": "Must be a valid URL starting with http:// or https://"
|
||||
},
|
||||
"create": {
|
||||
"title": "Create position",
|
||||
"code": "Code",
|
||||
"name": "Name",
|
||||
"description": "Description",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save",
|
||||
"codeRequired": "Code is required",
|
||||
"nameRequired": "Name is required",
|
||||
"success": "Position successfully created!",
|
||||
"error": "Failed to create position"
|
||||
"scopes": {
|
||||
"title": "Scopes",
|
||||
"profile:read": "Read profile",
|
||||
"profile:edit": "Edit profile"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Edit position",
|
||||
"code": "Code",
|
||||
"name": "Name",
|
||||
"description": "Description",
|
||||
"cancel": "Cancel",
|
||||
"save": "Update",
|
||||
"success": "Position successfully updated!",
|
||||
"error": "Failed to update position"
|
||||
},
|
||||
"delete": {
|
||||
"success": "Position successfully deleted!",
|
||||
"error": "Failed to delete position"
|
||||
},
|
||||
"permissions": {
|
||||
"label": "Permissions",
|
||||
"empty": "There are no permissions yet"
|
||||
"submit": "Connect application",
|
||||
"secretReveal": {
|
||||
"title": "Save your client secret",
|
||||
"subtitle": "This is the only time your client secret will be shown. Copy it now and store it somewhere safe.",
|
||||
"clientId": "Client ID",
|
||||
"clientSecret": "Client secret",
|
||||
"warning": "You won't be able to see this secret again. If you lose it, you'll need to regenerate it.",
|
||||
"confirm": "I've saved it"
|
||||
}
|
||||
},
|
||||
"userPositions": {
|
||||
"title": "User positions",
|
||||
"subtitle": "Assign and revoke positions for users.",
|
||||
"empty": "There're no users yet",
|
||||
"noPositions": "No positions",
|
||||
"columns": {
|
||||
"user": "User",
|
||||
"positions": "Positions",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"actions": {
|
||||
"assign": "Assign",
|
||||
"revoke": "Revoke"
|
||||
},
|
||||
"assign": {
|
||||
"success": "Position assigned successfully!",
|
||||
"error": "Failed to assign position"
|
||||
},
|
||||
"revoke": {
|
||||
"success": "Position revoked successfully!",
|
||||
"error": "Failed to revoke position"
|
||||
},
|
||||
"loadError": "Failed to load users"
|
||||
}
|
||||
},
|
||||
"logout": "Logout"
|
||||
|
||||
@@ -74,130 +74,61 @@
|
||||
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
|
||||
}
|
||||
},
|
||||
"applications": {
|
||||
"title": "Applicazioni",
|
||||
"consents": {
|
||||
"title": "Consensi",
|
||||
"subtitle": "Qui puoi vedere e revocare i consensi per le applicazioni connesse.",
|
||||
"authorized": "Autorizzato il",
|
||||
"revoke": "Revoca",
|
||||
"successfullyRevoked": "Accesso all'applicazione revocato con successo!",
|
||||
"revocationError": "Impossibile revocare l'accesso all'applicazione"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Posizioni",
|
||||
"loading": "Caricamento posizioni...",
|
||||
"empty": "Nessuna posizione assegnata"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Amministrazione",
|
||||
"permissions": {
|
||||
"title": "Permessi",
|
||||
"subtitle": "I permessi possono essere assegnati alle posizioni per controllare l'accesso.",
|
||||
"empty": "Non ci sono permessi",
|
||||
"noDescription": "Senza descrizione",
|
||||
"columns": {
|
||||
"code": "Codice",
|
||||
"description": "Descrizione",
|
||||
"actions": "Azioni"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Modifica",
|
||||
"delete": "Elimina",
|
||||
"create": "Crea permesso"
|
||||
},
|
||||
"create": {
|
||||
"title": "Creazione del permesso",
|
||||
"code": "Codice",
|
||||
"description": "Descrizione",
|
||||
"cancel": "Annulla",
|
||||
"save": "Salva",
|
||||
"codeRequired": "Il codice è obbligatorio",
|
||||
"success": "Il permesso è stato creato con successo!",
|
||||
"error": "Impossibile creare il permesso"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Modifica permesso",
|
||||
"code": "Codice",
|
||||
"description": "Descrizione",
|
||||
"cancel": "Annulla",
|
||||
"save": "Aggiorna",
|
||||
"success": "Il permesso è stato aggiornato con successo!",
|
||||
"error": "Impossibile aggiornare il permesso"
|
||||
},
|
||||
"delete": {
|
||||
"success": "Il permesso è stato eliminato con successo!",
|
||||
"error": "Impossibile eliminare il permesso"
|
||||
}
|
||||
"applications": {
|
||||
"title": "Applicazioni",
|
||||
"subtitle": "Qui puoi collegare le tue applicazioni a Kotosoft ID per offrire ai tuoi utenti un modo semplice per autenticarsi.",
|
||||
"table": {
|
||||
"client": "Client",
|
||||
"redirectURIs": "Redirect URIs",
|
||||
"scopes": "Ambiti di accesso",
|
||||
"status": "Stato",
|
||||
"active": "Attivo",
|
||||
"disabled": "Disabilitato",
|
||||
"disable": "Disabilita applicazione",
|
||||
"edit": "Modifica applicazione"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Posizioni",
|
||||
"subtitle": "Gestire le posizioni e assegnare i permessi per controllare l'accesso.",
|
||||
"empty": "Non ci sono posizioni",
|
||||
"noDescription": "Senza descrizione",
|
||||
"columns": {
|
||||
"code": "Codice",
|
||||
"name": "Nome",
|
||||
"description": "Descrizione",
|
||||
"actions": "Azioni"
|
||||
"noApplications": "Non hai ancora applicazioni collegate",
|
||||
"dialog": {
|
||||
"trigger": "Collega applicazione",
|
||||
"title": "Collega una nuova applicazione",
|
||||
"subtitle": "Inserisci i dati della tua applicazione per collegarla.",
|
||||
"required": "Questo campo è obbligatorio",
|
||||
"name": {
|
||||
"title": "Nome dell'applicazione",
|
||||
"minLength": "Il nome deve contenere almeno 2 caratteri",
|
||||
"maxLength": "Il nome deve contenere al massimo 128 caratteri"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Modifica",
|
||||
"delete": "Elimina",
|
||||
"create": "Crea posizione"
|
||||
"editTitle": "Modifica applicazione",
|
||||
"editSubtitle": "Modifica i dati della tua applicazione.",
|
||||
"editSubmit": "Salva modifiche",
|
||||
"redirectUris": {
|
||||
"title": "URI di reindirizzamento",
|
||||
"placeholder": "https://example.com/callback",
|
||||
"add": "Aggiungi un altro URI",
|
||||
"invalid": "Deve essere un URL valido che inizi con http:// o https://"
|
||||
},
|
||||
"create": {
|
||||
"title": "Crea posizione",
|
||||
"code": "Codice",
|
||||
"name": "Nome",
|
||||
"description": "Descrizione",
|
||||
"cancel": "Annulla",
|
||||
"save": "Salva",
|
||||
"codeRequired": "Il codice è obbligatorio",
|
||||
"nameRequired": "Il nome è obbligatorio",
|
||||
"success": "La posizione è stata creata con successo!",
|
||||
"error": "Impossibile creare la posizione"
|
||||
"scopes": {
|
||||
"title": "Ambiti di accesso",
|
||||
"profile:read": "Lettura del profilo",
|
||||
"profile:edit": "Modifica del profilo"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Modifica posizione",
|
||||
"code": "Codice",
|
||||
"name": "Nome",
|
||||
"description": "Descrizione",
|
||||
"cancel": "Annulla",
|
||||
"save": "Aggiorna",
|
||||
"success": "La posizione è stata aggiornata con successo!",
|
||||
"error": "Impossibile aggiornare la posizione"
|
||||
},
|
||||
"delete": {
|
||||
"success": "La posizione è stata eliminata con successo!",
|
||||
"error": "Impossibile eliminare la posizione"
|
||||
},
|
||||
"permissions": {
|
||||
"label": "Permessi",
|
||||
"empty": "Non ci sono permessi"
|
||||
"submit": "Collega applicazione",
|
||||
"secretReveal": {
|
||||
"title": "Salva il segreto del client",
|
||||
"subtitle": "Questa è l'unica volta in cui il segreto del client verrà mostrato. Copialo ora e conservalo in un luogo sicuro.",
|
||||
"clientId": "ID client",
|
||||
"clientSecret": "Segreto del client",
|
||||
"warning": "Non potrai visualizzare nuovamente questo segreto. Se lo perdi, dovrai generarne uno nuovo.",
|
||||
"confirm": "Ho salvato il segreto"
|
||||
}
|
||||
},
|
||||
"userPositions": {
|
||||
"title": "Posizioni utenti",
|
||||
"subtitle": "Assegna e revoca posizioni agli utenti.",
|
||||
"empty": "Non ci sono utenti",
|
||||
"noPositions": "Nessuna posizione",
|
||||
"columns": {
|
||||
"user": "Utente",
|
||||
"positions": "Posizioni",
|
||||
"actions": "Azioni"
|
||||
},
|
||||
"actions": {
|
||||
"assign": "Assegna",
|
||||
"revoke": "Revoca"
|
||||
},
|
||||
"assign": {
|
||||
"success": "Posizione assegnata con successo!",
|
||||
"error": "Impossibile assegnare la posizione"
|
||||
},
|
||||
"revoke": {
|
||||
"success": "Posizione revocata con successo!",
|
||||
"error": "Impossibile revocare la posizione"
|
||||
},
|
||||
"loadError": "Impossibile caricare gli utenti"
|
||||
}
|
||||
},
|
||||
"logout": "Esci"
|
||||
|
||||
@@ -74,130 +74,61 @@
|
||||
"updateError": "Произошла ошибка при обновлении. Попробуйте ещё раз позже."
|
||||
}
|
||||
},
|
||||
"applications": {
|
||||
"title": "Приложения",
|
||||
"consents": {
|
||||
"title": "Разрешения",
|
||||
"subtitle": "Здесь вы можете просматривать и отзывать доступ приложений.",
|
||||
"authorized": "Разрешено",
|
||||
"revoke": "Отозвать",
|
||||
"successfullyRevoked": "Доступ приложения успешно отозван!",
|
||||
"revocationError": "Не удалось отозвать доступ приложения"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Должности",
|
||||
"loading": "Загрузка должностей...",
|
||||
"empty": "Нет назначенных должностей"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Администрирование",
|
||||
"permissions": {
|
||||
"title": "Разрешения",
|
||||
"subtitle": "Разрешения могут быть присвоены должностям для контроля прав доступа.",
|
||||
"empty": "Разрешений пока нет",
|
||||
"noDescription": "Без описания",
|
||||
"columns": {
|
||||
"code": "Код",
|
||||
"description": "Описание",
|
||||
"actions": "Действия"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Изменить",
|
||||
"delete": "Удалить",
|
||||
"create": "Создать разрешение"
|
||||
},
|
||||
"create": {
|
||||
"title": "Создать разрешение",
|
||||
"code": "Код",
|
||||
"description": "Описание",
|
||||
"cancel": "Отмена",
|
||||
"save": "Сохранить",
|
||||
"codeRequired": "Код разрешения обязателен",
|
||||
"success": "Разрешение успешно создано!",
|
||||
"error": "Не удалось создать разрешение"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Редактирование разрешения",
|
||||
"code": "Код",
|
||||
"description": "Описание",
|
||||
"cancel": "Отмена",
|
||||
"save": "Сохранить",
|
||||
"success": "Разрешение успешно обновлено!",
|
||||
"error": "Не удалось обновить разрешение"
|
||||
},
|
||||
"delete": {
|
||||
"success": "Разрешение успешно удалено!",
|
||||
"error": "Не удалось удалить разрешение"
|
||||
}
|
||||
"applications": {
|
||||
"title": "Приложения",
|
||||
"subtitle": "Здесь вы можете подключить свои приложения к Kotosoft ID, чтобы предоставить пользователям удобный способ авторизации.",
|
||||
"table": {
|
||||
"client": "Клиент",
|
||||
"redirectURIs": "Redirect URIs",
|
||||
"scopes": "Области доступа",
|
||||
"status": "Статус",
|
||||
"active": "Активно",
|
||||
"disabled": "Отключено",
|
||||
"disable": "Отключить",
|
||||
"edit": "Редактировать"
|
||||
},
|
||||
"positions": {
|
||||
"title": "Должности",
|
||||
"subtitle": "Управление должностями и назначение разрешений для контроля доступа.",
|
||||
"empty": "Должностей пока нет",
|
||||
"noDescription": "Без описания",
|
||||
"columns": {
|
||||
"code": "Код",
|
||||
"name": "Название",
|
||||
"description": "Описание",
|
||||
"actions": "Действия"
|
||||
"noApplications": "У вас пока нет подключённых приложений",
|
||||
"dialog": {
|
||||
"trigger": "Подключить приложение",
|
||||
"title": "Подключить новое приложение",
|
||||
"subtitle": "Введите данные приложения, чтобы подключить его.",
|
||||
"required": "Это поле обязательно",
|
||||
"name": {
|
||||
"title": "Название приложения",
|
||||
"minLength": "Название должно содержать не менее 2 символов",
|
||||
"maxLength": "Название должно содержать не более 128 символов"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Изменить",
|
||||
"delete": "Удалить",
|
||||
"create": "Создать должность"
|
||||
"editTitle": "Редактировать приложение",
|
||||
"editSubtitle": "Измените данные вашего приложения.",
|
||||
"editSubmit": "Сохранить изменения",
|
||||
"redirectUris": {
|
||||
"title": "URI перенаправления",
|
||||
"placeholder": "https://example.com/callback",
|
||||
"add": "Добавить ещё URI",
|
||||
"invalid": "Должен быть корректный URL, начинающийся с http:// или https://"
|
||||
},
|
||||
"create": {
|
||||
"title": "Создать должность",
|
||||
"code": "Код",
|
||||
"name": "Название",
|
||||
"description": "Описание",
|
||||
"cancel": "Отмена",
|
||||
"save": "Сохранить",
|
||||
"codeRequired": "Код должности обязателен",
|
||||
"nameRequired": "Название должности обязательно",
|
||||
"success": "Должность успешно создана!",
|
||||
"error": "Не удалось создать должность"
|
||||
"scopes": {
|
||||
"title": "Области доступа",
|
||||
"profile:read": "Чтение профиля",
|
||||
"profile:edit": "Редактирование профиля"
|
||||
},
|
||||
"edit": {
|
||||
"title": "Редактирование должности",
|
||||
"code": "Код",
|
||||
"name": "Название",
|
||||
"description": "Описание",
|
||||
"cancel": "Отмена",
|
||||
"save": "Сохранить",
|
||||
"success": "Должность успешно обновлена!",
|
||||
"error": "Не удалось обновить должность"
|
||||
},
|
||||
"delete": {
|
||||
"success": "Должность успешно удалена!",
|
||||
"error": "Не удалось удалить должность"
|
||||
},
|
||||
"permissions": {
|
||||
"label": "Разрешения",
|
||||
"empty": "Разрешений пока нет"
|
||||
"submit": "Подключить приложение",
|
||||
"secretReveal": {
|
||||
"title": "Сохраните секрет клиента",
|
||||
"subtitle": "Секрет клиента будет показан только один раз. Скопируйте его сейчас и сохраните в безопасном месте.",
|
||||
"clientId": "ID клиента",
|
||||
"clientSecret": "Секрет клиента",
|
||||
"warning": "Вы больше не сможете посмотреть этот секрет. Если вы его потеряете, вам потребуется создать новое приложение.",
|
||||
"confirm": "Я сохранил секрет"
|
||||
}
|
||||
},
|
||||
"userPositions": {
|
||||
"title": "Должности пользователей",
|
||||
"subtitle": "Назначайте и отзывайте должности у пользователей.",
|
||||
"empty": "Пользователей пока нет",
|
||||
"noPositions": "Нет должностей",
|
||||
"columns": {
|
||||
"user": "Пользователь",
|
||||
"positions": "Должности",
|
||||
"actions": "Действия"
|
||||
},
|
||||
"actions": {
|
||||
"assign": "Назначить",
|
||||
"revoke": "Отозвать"
|
||||
},
|
||||
"assign": {
|
||||
"success": "Должность успешно назначена!",
|
||||
"error": "Не удалось назначить должность"
|
||||
},
|
||||
"revoke": {
|
||||
"success": "Должность успешно отозвана!",
|
||||
"error": "Не удалось отозвать должность"
|
||||
},
|
||||
"loadError": "Не удалось загрузить пользователей"
|
||||
}
|
||||
},
|
||||
"logout": "Выйти"
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -9,8 +9,10 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-table": "^9.2.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.3.0",
|
||||
"date-fns": "^4.4.0",
|
||||
"lucide-react": "^0.575.0",
|
||||
"next": "^16.2.9",
|
||||
|
||||
@@ -33,77 +33,25 @@ export interface Consent {
|
||||
isRevokable: boolean;
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
description: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
code: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
permissions: Permission[];
|
||||
}
|
||||
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
second_name: string;
|
||||
is_admin: boolean;
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
export const localeMap = {
|
||||
ru,
|
||||
en: enUS,
|
||||
it,
|
||||
};
|
||||
|
||||
export interface Region {
|
||||
export interface OAuthClient {
|
||||
id: string;
|
||||
code: string;
|
||||
client_id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
type FieldType = "text" | "date" | "select" | "masked"
|
||||
|
||||
export interface FieldOption {
|
||||
value: string;
|
||||
label: { en: string; ru: string };
|
||||
}
|
||||
|
||||
export interface FieldTemplate {
|
||||
id: string;
|
||||
name: { en: string; ru: string };
|
||||
type: FieldType;
|
||||
required?: boolean;
|
||||
mask?: string;
|
||||
options?: FieldOption[];
|
||||
generated?: boolean;
|
||||
}
|
||||
|
||||
type CitizenshipApplicationStatus = "pending" | "rejected" | "approved"
|
||||
|
||||
export interface CitizenshipApplication {
|
||||
id: string;
|
||||
user_id: string;
|
||||
status: CitizenshipApplicationStatus;
|
||||
region_id: string;
|
||||
reviewed_by?: string;
|
||||
reviewed_at?: string;
|
||||
reject_reason?: string;
|
||||
redirect_uris: string[];
|
||||
grant_types: string[];
|
||||
scopes: string[];
|
||||
trusted: boolean;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Citizen {
|
||||
id: string;
|
||||
user_id: string;
|
||||
application_id: string;
|
||||
number: string;
|
||||
issued_at: string;
|
||||
region_id: string;
|
||||
export interface CreatedOAuthClient extends OAuthClient {
|
||||
client_secret: string;
|
||||
}
|
||||
Reference in New Issue
Block a user