Completed Admin Users form

This commit is contained in:
PxlLoewe
2025-06-04 17:27:58 -07:00
parent 7aceae7c17
commit 3c620b9b67
22 changed files with 592 additions and 235 deletions

View File

@@ -8,6 +8,8 @@ import { dispatchSocket } from "dispatch/socket";
import { Mission, NotificationPayload } from "@repo/db";
import { HPGnotificationToast } from "_components/customToasts/HPGnotification";
import { useMapStore } from "_store/mapStore";
import { AdminMessageToast } from "_components/customToasts/AdminMessage";
import { pilotSocket } from "pilot/socket";
export function QueryProvider({ children }: { children: ReactNode }) {
const mapStore = useMapStore((s) => s);
@@ -39,6 +41,9 @@ export function QueryProvider({ children }: { children: ReactNode }) {
queryClient.invalidateQueries({
queryKey: ["aircrafts"],
});
queryClient.invalidateQueries({
queryKey: ["dispatchers"],
});
};
const invalidateConenctedAircrafts = () => {
@@ -58,13 +63,18 @@ export function QueryProvider({ children }: { children: ReactNode }) {
toast.custom(
(t) => <HPGnotificationToast event={notification} mapStore={mapStore} t={t} />,
{
duration: 9999,
duration: 99999,
},
);
break;
case "admin-message":
toast.custom((t) => <AdminMessageToast event={notification} t={t} />, {
duration: 999999,
});
break;
default:
toast(notification.message);
toast("unbekanntes Notification-Event");
break;
}
};
@@ -76,6 +86,7 @@ export function QueryProvider({ children }: { children: ReactNode }) {
dispatchSocket.on("pilots-update", invalidateConnectedUsers);
dispatchSocket.on("update-connectedAircraft", invalidateConenctedAircrafts);
dispatchSocket.on("notification", handleNotification);
pilotSocket.on("notification", handleNotification);
return () => {
dispatchSocket.off("update-mission", invalidateMission);

View File

@@ -0,0 +1,34 @@
import { AdminMessage } from "@repo/db";
import { BaseNotification } from "_components/customToasts/BaseNotification";
import { cn } from "_helpers/cn";
import { TriangleAlert } from "lucide-react";
import toast, { Toast } from "react-hot-toast";
export const AdminMessageToast = ({ event, t }: { event: AdminMessage; t: Toast }) => {
const handleClick = () => {
toast.dismiss(t.id);
};
return (
<BaseNotification icon={<TriangleAlert />} className="flex flex-row">
<div className="flex-1">
<h1
className={cn(
"font-bold",
event.status == "ban" && "text-red-500 ",
event.status == "kick" && "text-yellow-500 ",
)}
>
Du wurdes durch den Admin {event.data?.admin.publicId}{" "}
{event.status == "ban" ? "gebannt" : "gekickt"}!
</h1>
<p>{event.message}</p>
</div>
<div className="ml-11">
<button className="btn" onClick={handleClick}>
OK
</button>
</div>
</BaseNotification>
);
};

View File

@@ -1,4 +1,4 @@
import { NotificationPayload } from "@repo/db";
import { NotificationPayload, ValidationFailed, ValidationSuccess } from "@repo/db";
import { BaseNotification } from "_components/customToasts/BaseNotification";
import { MapStore, useMapStore } from "_store/mapStore";
import { Check, Cross } from "lucide-react";
@@ -9,7 +9,7 @@ export const HPGnotificationToast = ({
t,
mapStore,
}: {
event: NotificationPayload;
event: ValidationFailed | ValidationSuccess;
t: Toast;
mapStore: MapStore;
}) => {

View File

@@ -1,21 +1,102 @@
"use client";
import { PublicUser } from "@repo/db";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getConnectedAircraftsAPI, kickAircraftAPI } from "_querys/aircrafts";
import { getConnectedDispatcherAPI, kickDispatcherAPI } from "_querys/connected-user";
import { getLivekitRooms, kickLivekitParticipant } from "_querys/livekit";
import { editUserAPI } from "_querys/user";
import { ParticipantInfo } from "livekit-server-sdk";
import {
ArrowLeftRight,
Eye,
LockKeyhole,
Plane,
RedoDot,
Shield,
ShieldAlert,
Speaker,
User,
UserCheck,
Workflow,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRef } from "react";
import toast from "react-hot-toast";
export default function AdminPanel() {
const path = usePathname();
const queryClient = useQueryClient();
const { data: pilots } = useQuery({
queryKey: ["pilots"],
queryFn: () => getConnectedAircraftsAPI(),
refetchInterval: 10000,
});
const { data: dispatcher } = useQuery({
queryKey: ["dispatcher"],
queryFn: () => getConnectedDispatcherAPI(),
refetchInterval: 10000,
});
const { data: livekitRooms } = useQuery({
queryKey: ["connected-audio-users"],
queryFn: () => getLivekitRooms(),
refetchInterval: 10000,
});
const kickLivekitParticipantMutation = useMutation({
mutationFn: kickLivekitParticipant,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["connected-audio-users"] });
},
});
const editUSerMutation = useMutation({
mutationFn: editUserAPI,
});
const kickPilotMutation = useMutation({
mutationFn: kickAircraftAPI,
onSuccess: () => {
toast.success("Pilot wurde erfolgreich gekickt");
queryClient.invalidateQueries({
queryKey: ["aircrafts"],
});
queryClient.invalidateQueries({
queryKey: ["connected-audio-users"],
});
},
});
const kickDispatchMutation = useMutation({
mutationFn: kickDispatcherAPI,
onSuccess: () => {
toast.success("Disponent wurde erfolgreich gekickt");
queryClient.invalidateQueries({
queryKey: ["dispatcher"],
});
queryClient.invalidateQueries({
queryKey: ["connected-audio-users"],
});
},
});
const participants: { participant: ParticipantInfo; room: string }[] = [];
if (livekitRooms) {
livekitRooms?.forEach((room) => {
room.participants.forEach((participant) => {
participants.push({
participant,
room: room.room.name,
});
});
});
}
const livekitUserNotConnected = participants.filter((p) => {
const pilot = pilots?.find(
(d) => (d.publicUser as unknown as PublicUser).publicId === p.participant.identity,
);
const fDispatcher = dispatcher?.find(
(d) => (d.publicUser as unknown as PublicUser).publicId === p.participant.identity,
);
return !pilot && !fDispatcher;
});
console.log("Livekit Rooms", livekitRooms);
const modalRef = useRef<HTMLDialogElement>(null);
return (
@@ -29,7 +110,7 @@ export default function AdminPanel() {
>
<Shield size={18} /> Admin Panel
</button>
<dialog ref={modalRef} className="modal">
<dialog ref={modalRef} className="modal min-w-[500px]">
<div className="modal-box w-11/12 max-w-7xl">
<form method="dialog">
<button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"></button>
@@ -50,203 +131,171 @@ export default function AdminPanel() {
<th>Name</th>
<th>Station</th>
<th>Voice</th>
<th>Dispatch</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
<tr>
<td>VAR0124</td>
<td>Max Mustermann</td>
<td>Christoph 31</td>
<td className="text-error">
<span>Nicht verbunden</span>
</td>
<td className="text-success">
<span>Verbunden</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</td>
</tr>
{pilots?.map((p) => {
const publicUser = p.publicUser as unknown as PublicUser;
const livekitParticipant = participants.find(
(p) => p.participant.identity === publicUser.publicId,
);
return (
<tr key={p.id}>
<td className="flex items-center gap-2">
<Plane /> {publicUser.publicId}
</td>
<td>{publicUser.fullName}</td>
<td>{p.Station.bosCallsign}</td>
<td>
{!livekitParticipant ? (
<span className="text-error">Nicht verbunden</span>
) : (
<span className="text-success">{livekitParticipant.room}</span>
)}
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
onClick={() => kickPilotMutation.mutate({ id: p.id })}
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
onClick={() => {
kickPilotMutation.mutate({ id: p.id, bann: true });
}}
>
<LockKeyhole size={15} />
</button>
<a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/admin/user/${p.userId}`}
target="_blank"
rel="noopener noreferrer"
>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</a>
</td>
</tr>
);
})}
{dispatcher?.map((d) => {
const publicUser = d.publicUser as unknown as PublicUser;
const livekitParticipant = participants.find(
(p) => p.participant.identity === publicUser.publicId,
);
return (
<tr key={d.id}>
<td className="flex items-center gap-2">
<Workflow /> {publicUser.publicId}
</td>
<td>{publicUser.fullName}</td>
<td>{d.zone}</td>
<td>
{!livekitParticipant ? (
<span className="text-error">Nicht verbunden</span>
) : (
<span className="text-success">{livekitParticipant.room}</span>
)}
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
onClick={() => kickDispatchMutation.mutate({ id: d.id })}
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
onClick={() => {
kickDispatchMutation.mutate({ id: d.id, bann: true });
}}
>
<LockKeyhole size={15} />
</button>
<a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/admin/user/${d.userId}`}
target="_blank"
rel="noopener noreferrer"
>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</a>
</td>
</tr>
);
})}
{livekitUserNotConnected.map((p) => {
const publicUser = JSON.parse(
p.participant.attributes.publicUser || "{}",
) as PublicUser;
return (
<tr key={p.participant.identity}>
<td className="flex items-center gap-2">
<Speaker /> {p.participant.identity}
</td>
<td>{publicUser?.fullName}</td>
<td>
<span className="text-error">Nicht verbunden</span>
</td>
<td>
<span className="text-success">{p.room}</span>
</td>
<td className="flex gap-2">
<button
className="btn btn-xs btn-square btn-warning btn-soft tooltip tooltip-bottom tooltip-warning"
data-tip="Kick"
onClick={() =>
kickLivekitParticipantMutation.mutate({
roomName: p.room,
identity: p.participant.identity,
})
}
>
<RedoDot size={15} />
</button>
<button
className="btn btn-xs btn-square btn-error btn-soft tooltip tooltip-bottom tooltip-error"
data-tip="Ban"
>
<LockKeyhole size={15} />
</button>
<a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/admin/user/${p.participant.attributes.userId}`}
target="_blank"
rel="noopener noreferrer"
>
<button
className="btn btn-xs btn-square btn-info btn-soft tooltip tooltip-bottom tooltip-info"
data-tip="Profil"
>
<User size={15} />
</button>
</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
<div className="card bg-base-300 shadow-md w-full mt-4 max-h-48 overflow-y-auto">
{/* <div className="card bg-base-300 shadow-md w-full mt-4 max-h-48 overflow-y-auto">
<div className="card-body">
<div className="card-title flex items-center gap-2">
<ShieldAlert size={20} /> Allgemeine Befehle
@@ -266,7 +315,7 @@ export default function AdminPanel() {
</button>
</div>
</div>
</div>
</div> */}
</div>
<form method="dialog" className="modal-backdrop">
<button>close</button>

View File

@@ -19,8 +19,7 @@ export const SettingsBtn = () => {
const testSoundRef = useRef<HTMLAudioElement | null>(null);
const editUserMutation = useMutation({
mutationFn: ({ user }: { user: Prisma.UserUpdateInput }) =>
editUserAPI(session.data!.user.id, user),
mutationFn: editUserAPI,
});
useEffect(() => {
@@ -201,7 +200,8 @@ export const SettingsBtn = () => {
onSubmit={() => false}
onClick={async () => {
testSoundRef.current?.pause();
const res = await editUserMutation.mutateAsync({
await editUserMutation.mutateAsync({
id: session.data!.user.id,
user: {
settingsMicDevice: selectedDevice,
settingsMicVolume: micVol,

View File

@@ -0,0 +1,9 @@
import { RoomServiceClient } from "livekit-server-sdk";
if (!process.env.NEXT_PUBLIC_LIVEKIT_URL) throw new Error("NEXT_PUBLIC_LIVEKIT_URL is not defined");
export const RoomManager = new RoomServiceClient(
process.env.NEXT_PUBLIC_LIVEKIT_URL!,
process.env.LIVEKIT_API_KEY,
process.env.LIVEKIT_API_SECRET,
);

View File

@@ -27,3 +27,14 @@ export const getConnectedAircraftPositionLogAPI = async ({ id }: { id: number })
}
return res.data;
};
export const kickAircraftAPI = async ({ id, bann }: { id: number; bann?: boolean }) => {
const res = await serverApi.delete(`/aircrafts/${id}`, {
data: { bann },
});
console.log(res.status);
if (res.status != 204) {
throw new Error("Failed to kick aircraft");
}
return res.data;
};

View File

@@ -35,3 +35,14 @@ export const getConnectedDispatcherAPI = async (filter?: Prisma.ConnectedDispatc
}
return res.data;
};
export const kickDispatcherAPI = async ({ id, bann }: { id: number; bann?: boolean }) => {
const res = await serverApi.delete(`/dispatcher/${id}`, {
data: { bann },
});
console.log(res.status);
if (res.status != 204) {
throw new Error("Failed to kick aircraft");
}
return res.data;
};

View File

@@ -0,0 +1,28 @@
import axios from "axios";
import { Room } from "livekit-client";
import { ParticipantInfo } from "livekit-server-sdk";
export const getLivekitRooms = async () => {
const res = await axios.get<
{
room: Room;
participants: ParticipantInfo[];
}[]
>("/api/livekit-participant");
if (res.status !== 200) {
throw new Error("Failed to fetch keywords");
}
return res.data;
};
export const kickLivekitParticipant = async (body: { identity: string; roomName: string }) => {
const res = await axios.delete("/api/livekit-participant", {
params: body,
});
if (res.status !== 200) {
throw new Error("Failed to kick participant");
}
return res.data;
};

View File

@@ -1,7 +1,7 @@
import { Prisma, User } from "@repo/db";
import axios from "axios";
export const editUserAPI = async (id: string, user: Prisma.UserUpdateInput) => {
export const editUserAPI = async ({ id, user }: { id: string; user: Prisma.UserUpdateInput }) => {
const response = await axios.post<User>(`/api/user?id=${id}`, user);
return response.data;
};

View File

@@ -0,0 +1,85 @@
import { prisma } from "@repo/db";
import { RoomManager } from "_helpers/LivekitRoomManager";
import { getServerSession } from "api/auth/[...nextauth]/auth";
import { NextRequest } from "next/server";
export const GET = async (request: NextRequest) => {
const session = await getServerSession();
if (!session) return Response.json({ message: "Unauthorized" }, { status: 401 });
const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
});
if (!user || !user.permissions.includes("AUDIO_ADMIN"))
return Response.json({ message: "Missing permissions" }, { status: 401 });
const rooms = await RoomManager.listRooms();
const roomsWithParticipants = rooms.map(async (room) => {
const participants = await RoomManager.listParticipants(room.name);
return {
room,
participants,
};
});
return Response.json(await Promise.all(roomsWithParticipants), { status: 200 });
};
export const DELETE = async (request: NextRequest) => {
try {
const identity = request.nextUrl.searchParams.get("identity");
const roomName = request.nextUrl.searchParams.get("roomName");
const ban = request.nextUrl.searchParams.get("ban");
if (!identity) return Response.json({ message: "Missing User identity" }, { status: 400 });
if (!roomName) return Response.json({ message: "Missing roomName" }, { status: 400 });
const session = await getServerSession();
if (!session) return Response.json({ message: "Unauthorized" }, { status: 401 });
const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
});
if (!user || !user.permissions.includes("AUDIO_ADMIN"))
return Response.json({ message: "Missing permissions" }, { status: 401 });
if (ban && !user.permissions.includes("ADMIN_USER")) {
return Response.json({ message: "Missing permissions to ban user" }, { status: 401 });
}
if (ban) {
const participant = await RoomManager.getParticipant(roomName, identity);
const pUser = await prisma.user.findUnique({
where: {
id: participant.attributes.userId,
},
});
if (!pUser) return;
// If the user is banned, we need to remove their permissions
await prisma.user.update({
where: { id: session.user.id },
data: {
permissions: {
set: pUser.permissions.filter((p) => p !== "AUDIO"),
},
},
});
}
await RoomManager.removeParticipant(roomName, identity);
return Response.json(
{ message: `User ${identity} kicked from room ${roomName}` },
{ status: 200 },
);
} catch (error) {
console.error("Error in DELETE /api/livekit-participant:", error);
return Response.json({ message: "Internal Server Error" }, { status: 500 });
}
};

View File

@@ -27,8 +27,7 @@ export const GET = async (request: NextRequest) => {
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {
identity: user.publicId,
// Token to expire after 10 minutes
ttl: "1d",
ttl: "1h",
});
at.addGrant({
@@ -41,6 +40,8 @@ export const GET = async (request: NextRequest) => {
at.attributes = {
publicId: user.publicId,
publicUser: JSON.stringify(getPublicUser(user)),
userId: user.id,
};
const token = await at.toJwt();

View File

@@ -1,5 +1,3 @@
"use client";
import { Connection } from "./_components/Connection";
/* import { ThemeSwap } from "./_components/ThemeSwap"; */
import { Audio } from "../../../_components/Audio/Audio";
@@ -9,24 +7,16 @@ import Link from "next/link";
import { Settings } from "_components/navbar/Settings";
import ModeSwitchDropdown from "_components/navbar/ModeSwitchDropdown";
import AdminPanel from "_components/navbar/AdminPanel";
import { getServerSession } from "api/auth/[...nextauth]/auth";
export default function Navbar() {
/* const [isDark, setIsDark] = useState(false);
const toggleTheme = () => {
const newTheme = !isDark;
setIsDark(newTheme);
document.documentElement.setAttribute(
"data-theme",
newTheme ? "nord" : "dark",
);
}; */
export default async function Navbar() {
const session = await getServerSession();
return (
<div className="navbar bg-base-100 shadow-sm flex gap-5 justify-between">
<div className="flex items-center gap-2">
<ModeSwitchDropdown />
<AdminPanel />
{session?.user.permissions.includes("ADMIN_KICK") && <AdminPanel />}
</div>
<div className="flex items-center gap-5">
<div className="flex items-center gap-2">