show secret, update connected devices, and add checkmark anim for copy
All checks were successful
Deploy to Server / deploy (push) Successful in 1m52s

This commit is contained in:
rocord01 2025-07-14 07:52:34 -04:00
parent 1a3edce184
commit e6a9bdcdc8
4 changed files with 214 additions and 140 deletions

View file

@ -5,7 +5,7 @@ import { useAuth } from '@/contexts/AuthContext';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Copy, KeyRound, Server, User } from 'lucide-react';
import { Copy, KeyRound, Server, User, Check } from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
@ -19,7 +19,7 @@ import {
} from "@/components/ui/alert-dialog"
import { Skeleton } from '@/components/ui/skeleton';
function CredentialRow({ icon, label, value, onCopy }) {
function CredentialRow({ icon, label, value, onCopy, isCopied }) {
return (
<div className="flex items-center justify-between bg-gray-900 p-3 rounded-lg border border-gray-800">
<div className="flex items-center gap-3">
@ -30,16 +30,17 @@ function CredentialRow({ icon, label, value, onCopy }) {
</div>
</div>
<Button variant="ghost" size="icon" onClick={onCopy}>
<Copy className="h-4 w-4" />
{isCopied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
);
}
export function SipCredentialsCard({ details, loading }) {
export function SipCredentialsCard({ details, loading, refetchDetails }) {
const { token } = useAuth();
const [newSecret, setNewSecret] = useState(null);
const [isResetting, setIsResetting] = useState(false);
const [copiedState, setCopiedState] = useState({});
const handleResetSecret = async () => {
if (!token) return;
@ -51,6 +52,9 @@ export function SipCredentialsCard({ details, loading }) {
});
const data = await res.json();
setNewSecret(data.newSecret);
if (refetchDetails) {
refetchDetails();
}
} catch (error) {
console.error("Failed to reset secret", error);
alert('Failed to reset secret.');
@ -59,9 +63,14 @@ export function SipCredentialsCard({ details, loading }) {
}
};
const copyToClipboard = (text) => {
navigator.clipboard.writeText(text);
alert('Copied to clipboard!');
const copyToClipboard = (text, id) => {
if (!text) return;
navigator.clipboard.writeText(text).then(() => {
setCopiedState(prev => ({ ...prev, [id]: true }));
setTimeout(() => {
setCopiedState(prev => ({ ...prev, [id]: false }));
}, 2000);
});
};
if (loading) {
@ -72,6 +81,7 @@ export function SipCredentialsCard({ details, loading }) {
<Skeleton className="h-4 w-64 mt-2" />
</CardHeader>
<CardContent className="space-y-4 pt-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-10 w-full" />
@ -87,10 +97,11 @@ export function SipCredentialsCard({ details, loading }) {
<CardDescription>Use these details to connect your SIP client.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<CredentialRow icon={<Server className="h-5 w-5 text-gray-400" />} label="SIP Server" value="pbx.litenet.tel" onCopy={() => copyToClipboard('pbx.litenet.tel')} />
<CredentialRow icon={<User className="h-5 w-5 text-gray-400" />} label="SIP Username" value={details?.extensionId} onCopy={() => copyToClipboard(details?.extensionId)} />
<CredentialRow icon={<Server className="h-5 w-5 text-gray-400" />} label="SIP Server" value="pbx.litenet.tel" onCopy={() => copyToClipboard('pbx.litenet.tel', 'server')} isCopied={copiedState['server']} />
<CredentialRow icon={<User className="h-5 w-5 text-gray-400" />} label="SIP Username" value={details?.extensionId} onCopy={() => copyToClipboard(details?.extensionId, 'username')} isCopied={copiedState['username']} />
<CredentialRow icon={<KeyRound className="h-5 w-5 text-gray-400" />} label="SIP Secret" value="••••••••••••" onCopy={() => copyToClipboard(details?.user?.extPassword, 'secret')} isCopied={copiedState['secret']} />
<Dialog open={!!newSecret} onOpenChange={(open) => !open && setNewSecret(null)}>
<Dialog open={!!newSecret} onOpenChange={(open) => { if (!open) { setNewSecret(null); setCopiedState(prev => ({ ...prev, newSecret: false })); } }}>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive" disabled={isResetting} className="w-full">
@ -125,8 +136,8 @@ export function SipCredentialsCard({ details, loading }) {
</DialogHeader>
<div className="flex items-center space-x-2 bg-black p-3 rounded-md border border-gray-700">
<code className="text-lg font-mono flex-grow text-green-400">{newSecret}</code>
<Button variant="ghost" size="icon" onClick={() => copyToClipboard(newSecret)}>
<Copy className="h-4 w-4" />
<Button variant="ghost" size="icon" onClick={() => copyToClipboard(newSecret, 'newSecret')}>
{copiedState['newSecret'] ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
</DialogContent>

View file

@ -6,7 +6,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import { Trash2, PlusCircle, Copy, KeyRound } from 'lucide-react';
import { Trash2, PlusCircle, Copy, KeyRound, AlertTriangle, Check } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@ -34,6 +34,7 @@ export default function ApiKeys() {
const [keyToDelete, setKeyToDelete] = useState(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [isCopied, setIsCopied] = useState(false);
const fetchKeys = useCallback(async () => {
if (!token) return;
@ -43,9 +44,10 @@ export default function ApiKeys() {
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
setKeys(data);
setKeys(Array.isArray(data) ? data : []);
} catch (error) {
console.error("Failed to fetch API keys", error);
setKeys([]);
} finally {
setLoading(false);
}
@ -67,11 +69,26 @@ export default function ApiKeys() {
},
body: JSON.stringify({ expiresInDays })
});
const data = await res.json();
setNewKey(data.key);
fetchKeys();
const newKeyData = await res.json();
if (!res.ok) {
throw new Error(newKeyData.error || 'Failed to create key.');
}
// Use newKeyData.apiKey from the response
setNewKey(newKeyData.apiKey);
// Add the new key to the local state, transforming the object to match the table's expected structure
const keyForState = {
...newKeyData,
key: newKeyData.apiKey, // Rename apiKey to key
};
delete keyForState.apiKey;
delete keyForState.message;
setKeys(prevKeys => [keyForState, ...prevKeys]);
setIsCreateDialogOpen(false); // Close the creation dialog
} catch (error) {
console.error("Failed to create key", error);
alert(`Failed to create key: ${error.message}`);
} finally {
setIsCreating(false);
}
@ -80,19 +97,26 @@ export default function ApiKeys() {
const handleDeleteKey = async (keyToDelete) => {
if (!token) return;
try {
await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'}/keys/${keyToDelete}`, {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'}/keys/${keyToDelete}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
fetchKeys();
if (!res.ok) {
const errorData = await res.json().catch(() => ({ error: 'Failed to delete key.' }));
throw new Error(errorData.error);
}
setKeys(prevKeys => prevKeys.filter(key => key.key !== keyToDelete));
} catch (error) {
console.error("Failed to delete key", error);
alert(`Failed to delete key: ${error.message}`);
}
};
const copyToClipboard = (text) => {
navigator.clipboard.writeText(text);
alert('Key copied to clipboard!');
navigator.clipboard.writeText(text).then(() => {
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
});
};
const filteredKeys = keys
@ -100,36 +124,23 @@ export default function ApiKeys() {
.filter(key => key.key.toLowerCase().includes(searchTerm.toLowerCase()));
return (
<Card className="mt-6 bg-gray-950/50 border-gray-800">
<CardHeader>
<div className="flex justify-between items-center">
<div>
<CardTitle>API Keys</CardTitle>
<CardDescription>Manage your API keys for programmatic access.</CardDescription>
</div>
<Dialog open={isCreateDialogOpen} onOpenChange={(open) => {
if (isCreating) return;
setIsCreateDialogOpen(open);
if (!open) setNewKey(null);
}}>
<DialogTrigger asChild>
<Button><PlusCircle className="h-4 w-4 mr-2" /> Create New Key</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{newKey ? 'API Key Created' : 'Create New API Key'}</DialogTitle>
<DialogDescription>
{newKey ? 'Your new API key is shown below. Please save it now. You will not be able to see it again.' : 'Set an expiration for your new key.'}
</DialogDescription>
</DialogHeader>
{newKey ? (
<div className="flex items-center space-x-2 bg-gray-900 p-3 rounded-md">
<code className="text-sm font-mono flex-grow break-all">{newKey}</code>
<Button variant="ghost" size="icon" onClick={() => copyToClipboard(newKey)}>
<Copy className="h-4 w-4" />
</Button>
</div>
) : (
<>
<Card className="mt-6 bg-gray-950/50 border-gray-800">
<CardHeader>
<div className="flex justify-between items-center">
<div>
<CardTitle>API Keys</CardTitle>
<CardDescription>Manage your API keys for programmatic access.</CardDescription>
</div>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button><PlusCircle className="h-4 w-4 mr-2" /> Create New Key</Button>
</DialogTrigger>
<DialogContent className="bg-gray-950 border-gray-800 text-white">
<DialogHeader>
<DialogTitle>Create New API Key</DialogTitle>
<DialogDescription>Set an expiration for your new key.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="expiresIn">Expires in (days)</Label>
@ -139,87 +150,87 @@ export default function ApiKeys() {
{isCreating ? 'Generating...' : 'Generate Key'}
</Button>
</div>
)}
</DialogContent>
</Dialog>
</div>
</CardHeader>
<CardContent>
<div className="flex flex-col sm:flex-row gap-4 justify-between mb-4">
<Input
placeholder="Search keys..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="max-w-xs bg-gray-900 border-gray-700"
/>
<div className="flex items-center gap-1 p-1 bg-gray-900 rounded-lg">
<Button size="sm" variant={filterType === 'all' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('all')}>All</Button>
<Button size="sm" variant={filterType === 'api' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('api')}>API</Button>
<Button size="sm" variant={filterType === 'session' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('session')}>Session</Button>
</DialogContent>
</Dialog>
</div>
</div>
{loading ? (
<div className="space-y-2">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</CardHeader>
<CardContent>
<div className="flex flex-col sm:flex-row gap-4 justify-between mb-4">
<Input
placeholder="Search keys..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="max-w-xs bg-gray-900 border-gray-700"
/>
<div className="flex items-center gap-1 p-1 bg-gray-900 rounded-lg">
<Button size="sm" variant={filterType === 'all' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('all')}>All</Button>
<Button size="sm" variant={filterType === 'api' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('api')}>API</Button>
<Button size="sm" variant={filterType === 'session' ? 'secondary' : 'ghost'} className="w-full sm:w-auto" onClick={() => setFilterType('session')}>Session</Button>
</div>
</div>
) : filteredKeys.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Key</TableHead>
<TableHead>Type</TableHead>
<TableHead>IP Address</TableHead>
<TableHead>Created</TableHead>
<TableHead>Expires</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredKeys.map(key => {
const isCurrentSession = key.type === 'session' && token?.startsWith(key.key);
return (
<TableRow key={key.key} className="hover:bg-gray-900">
<TableCell className="font-mono">
{key.type === 'api' ? `${key.key.substring(0, 12)}...` : key.key}
{isCurrentSession && <span className="text-xs text-gray-400 ml-2">(this session)</span>}
</TableCell>
<TableCell>
<Badge variant="outline" className={key.type === 'session' ? 'border-gray-600/50 bg-gray-900/20 text-gray-300' : 'border-blue-600/50 bg-blue-900/20 text-blue-300'}>
{key.type}
</Badge>
</TableCell>
<TableCell>{key.ipAddress || 'N/A'}</TableCell>
<TableCell>{format(new Date(key.createdAt), 'PP')}</TableCell>
<TableCell>{key.expiresAt ? format(new Date(key.expiresAt), 'PP') : 'Never'}</TableCell>
<TableCell className="text-right">
{!isCurrentSession && (
<Button variant="ghost" size="icon" onClick={() => setKeyToDelete(key)}>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
) : (
<div className="text-center py-10 text-gray-400">
<KeyRound className="mx-auto h-12 w-12 mb-4" />
<h3 className="text-lg font-semibold text-white">
{searchTerm || filterType !== 'all' ? 'No Matching Keys' : 'No API Keys'}
</h3>
<p>
{searchTerm || filterType !== 'all'
? 'Try adjusting your search or filter.'
: 'Create your first API key to get started with integrations.'}
</p>
</div>
)}
</CardContent>
<AlertDialog open={!!keyToDelete} onOpenChange={setKeyToDelete}>
{loading ? (
<div className="space-y-2">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
) : filteredKeys.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Key</TableHead>
<TableHead>Type</TableHead>
<TableHead>IP Address</TableHead>
<TableHead>Created</TableHead>
<TableHead>Expires</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredKeys.map(key => {
const isCurrentSession = key.type === 'session' && token?.startsWith(key.key);
return (
<TableRow key={key.key} className="hover:bg-gray-900">
<TableCell className="font-mono">
{key.type === 'api' ? `${key.key.substring(0, 12)}...` : key.key}
{isCurrentSession && <span className="text-xs text-gray-400 ml-2">(this session)</span>}
</TableCell>
<TableCell>
<Badge variant="outline" className={key.type === 'session' ? 'border-gray-600/50 bg-gray-900/20 text-gray-300' : 'border-blue-600/50 bg-blue-900/20 text-blue-300'}>
{key.type}
</Badge>
</TableCell>
<TableCell>{key.ipAddress || 'N/A'}</TableCell>
<TableCell>{format(new Date(key.createdAt), 'PP')}</TableCell>
<TableCell>{key.expiresAt ? format(new Date(key.expiresAt), 'PP') : 'Never'}</TableCell>
<TableCell className="text-right">
{!isCurrentSession && (
<Button variant="ghost" size="icon" onClick={() => setKeyToDelete(key)}>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
) : (
<div className="text-center py-10 text-gray-400">
<KeyRound className="mx-auto h-12 w-12 mb-4" />
<h3 className="text-lg font-semibold text-white">
{searchTerm || filterType !== 'all' ? 'No Matching Keys' : 'No API Keys'}
</h3>
<p>
{searchTerm || filterType !== 'all'
? 'Try adjusting your search or filter.'
: 'Create your first API key to get started with integrations.'}
</p>
</div>
)}
</CardContent>
</Card>
<AlertDialog open={!!keyToDelete} onOpenChange={(open) => !open && setKeyToDelete(null)}>
<AlertDialogContent className="bg-gray-950 border-gray-800 text-white">
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
@ -247,6 +258,28 @@ export default function ApiKeys() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
<Dialog open={!!newKey} onOpenChange={(open) => { if (!open) { setNewKey(null); setIsCopied(false); } }}>
<DialogContent className="bg-gray-950 border-gray-800 text-white">
<DialogHeader>
<DialogTitle>API Key Created Successfully</DialogTitle>
<DialogDescription className="text-gray-400">
Your new API key is shown below. Copy it now, as you will not be able to see it again.
</DialogDescription>
</DialogHeader>
<div className="flex items-center space-x-2 bg-black p-3 rounded-md border border-gray-700">
<code className="text-sm font-mono flex-grow break-all">{newKey}</code>
<Button variant="ghost" size="icon" onClick={() => copyToClipboard(newKey)}>
{isCopied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
<div className="flex items-start gap-3 bg-yellow-900/20 border border-yellow-700/50 text-yellow-300 p-3 rounded-md">
<AlertTriangle className="h-5 w-5 mt-0.5 flex-shrink-0" />
<p className="text-sm">
Treat this key like a password. Do not share it with anyone or expose it in client-side code.
</p>
</div>
</DialogContent>
</Dialog>
</>
);
}

View file

@ -57,6 +57,7 @@ export default function DashboardClient() {
});
if (res.ok) {
const data = await res.json();
console.log("Fetched details:", data);
setDetails(data);
} else {
setDetails(null);

View file

@ -5,7 +5,7 @@ import { useAuth } from '@/contexts/AuthContext';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { RefreshCw, Smartphone, Server, Wifi } from 'lucide-react';
import { RefreshCw, Smartphone, Globe, Network, Wifi } from 'lucide-react';
import { TbPlugConnectedX } from 'react-icons/tb';
function DeviceCard({ device }) {
@ -14,20 +14,49 @@ function DeviceCard({ device }) {
if (ping > 150) pingColor = 'text-yellow-400';
if (ping > 300) pingColor = 'text-red-400';
// Extract IP and port from URI
const getIpFromUri = (uri) => {
try {
// Supports IPv4 and IPv6 addresses in brackets
const match = uri.match(/@((?:\[[a-fA-F0-9:]+\])|(?:[\d.]+)):(\d+)/);
if (match) {
return { ip: match[1].replace(/[\[\]]/g, ''), port: match[2] };
}
} catch (e) {
// ignore
}
return { ip: 'N/A', port: 'N/A' };
};
const { ip: uriIp, port: uriPort } = getIpFromUri(device.uri);
return (
<div className="bg-gray-900/80 p-4 rounded-lg border border-gray-800 space-y-3">
<div className="flex items-center gap-3">
<Smartphone className="h-5 w-5 text-gray-400" />
<span className="font-mono text-sm text-white truncate" title={device.useragent}>{device.useragent}</span>
<span className="font-mono text-sm text-white truncate" title={device.useragent}>{device.useragent || 'Unknown User Agent'}</span>
</div>
<div className="flex justify-between items-center text-sm">
<div className="flex items-center gap-2 text-gray-400">
<Server className="h-4 w-4" />
<span>{device.ip}:{device.port}</span>
<div className="space-y-2 text-sm">
<div className="flex justify-between items-center">
<div className="flex items-center gap-2 text-gray-400">
<Network className="h-4 w-4" />
<span>Client IP</span>
</div>
<span className="font-mono text-white">{device.ip}:{device.port}</span>
</div>
<div className={`flex items-center gap-2 font-semibold ${pingColor}`}>
<Wifi className="h-4 w-4" />
<span>{ping.toFixed(2)}ms</span>
<div className="flex justify-between items-center">
<div className="flex items-center gap-2 text-gray-400">
<Globe className="h-4 w-4" />
<span>Contact IP</span>
</div>
<span className="font-mono text-white">{uriIp}:{uriPort}</span>
</div>
<div className="flex justify-between items-center">
<div className="flex items-center gap-2 text-gray-400">
<Wifi className="h-4 w-4" />
<span>Latency</span>
</div>
<span className={`font-semibold ${pingColor}`}>{ping.toFixed(2)}ms</span>
</div>
</div>
</div>