v2: fixed oauth errors, oauth clients native control added
This commit is contained in:
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user