55 lines
2.3 KiB
TypeScript
55 lines
2.3 KiB
TypeScript
"use client";
|
|
|
|
import { useRouter } from "next/navigation";
|
|
import { useState } from "react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
|
|
|
type Target = { id: number | string; username?: string | null; displayName?: string | null };
|
|
|
|
export function ImpersonationControl({ users }: { users: Target[] }) {
|
|
const router = useRouter();
|
|
const [userId, setUserId] = useState("");
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
async function start() {
|
|
if (!userId) return;
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
const response = await fetch("/api/impersonation/start", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ userId }),
|
|
});
|
|
const body = await response.json().catch(() => null);
|
|
if (!response.ok) throw new Error(body?.error ?? "Unable to start impersonation.");
|
|
router.push("/");
|
|
router.refresh();
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : "Unable to start impersonation.");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="max-w-xl rounded-xl border border-border bg-card p-6 shadow-sm">
|
|
<h1 className="text-xl font-semibold">Impersonate a user</h1>
|
|
<p className="mt-2 text-sm text-muted-foreground">All requests will use the selected user's identity and permissions until you return to your account.</p>
|
|
<div className="mt-6 flex flex-col gap-2">
|
|
<Label htmlFor="impersonation-user">User</Label>
|
|
<Select value={userId} onValueChange={setUserId}>
|
|
<SelectTrigger id="impersonation-user"><SelectValue placeholder="Select a user" /></SelectTrigger>
|
|
<SelectContent>
|
|
{users.map((user) => <SelectItem key={String(user.id)} value={String(user.id)}>{user.displayName || user.username || `User ${user.id}`} {user.username ? `(${user.username})` : ""}</SelectItem>)}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
{error && <p className="mt-3 text-sm text-destructive">{error}</p>}
|
|
<Button className="mt-6" onClick={start} disabled={!userId || busy}>{busy ? "Starting..." : "Start impersonation"}</Button>
|
|
</div>
|
|
);
|
|
}
|