Compare commits
3 Commits
6a63e2801d
...
2981b2be2b
| Author | SHA1 | Date | |
|---|---|---|---|
| 2981b2be2b | |||
| 2be5276210 | |||
| 4ac430c1fe |
233
app/dashboard/dashboard-client.tsx
Normal file
233
app/dashboard/dashboard-client.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import TunnelConfig, { type TunnelConfig as TunnelConfigType, type Server } from "@/components/tunnel-config"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
|
||||
const defaultConfig: TunnelConfigType = {
|
||||
type: "http",
|
||||
serverPort: 443,
|
||||
localPort: 8000,
|
||||
}
|
||||
|
||||
const formatStartedAgo = (timestamp?: ApiTimestamp): string | undefined => {
|
||||
if (!timestamp) return undefined
|
||||
const startedMs = timestamp.seconds * 1000 + Math.floor(timestamp.nanos / 1_000_000)
|
||||
const diffSeconds = Math.max(0, Math.floor((Date.now() - startedMs) / 1000))
|
||||
|
||||
if (diffSeconds < 60) return `${diffSeconds}s ago`
|
||||
const diffMinutes = Math.floor(diffSeconds / 60)
|
||||
if (diffMinutes < 60) return `${diffMinutes}m ago`
|
||||
const diffHours = Math.floor(diffMinutes / 60)
|
||||
if (diffHours < 24) return `${diffHours}h ago`
|
||||
const diffDays = Math.floor(diffHours / 24)
|
||||
return `${diffDays}d ago`
|
||||
}
|
||||
|
||||
const toActiveConnection = (session: ApiSession): ActiveConnection => {
|
||||
const startedAgo = formatStartedAgo(session.started_at)
|
||||
|
||||
return {
|
||||
id: session.slug || `${session.node}-${session.started_at?.seconds ?? Date.now()}`,
|
||||
name: session.slug || session.node || "Unknown tunnel",
|
||||
status: session.active ? "connected" : "error",
|
||||
protocol: (session.forwarding_type || "http").toLowerCase(),
|
||||
serverLabel: session.node || "Unknown node",
|
||||
remote: session.slug ? `${session.slug}.${session.node}` : session.node || "—",
|
||||
startedAgo,
|
||||
latencyMs: null,
|
||||
dataInOut: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
type ApiTimestamp = {
|
||||
seconds: number
|
||||
nanos: number
|
||||
}
|
||||
|
||||
type ApiSession = {
|
||||
node: string
|
||||
forwarding_type: "HTTP" | "HTTPS" | "TCP" | string
|
||||
slug: string
|
||||
user_id: string
|
||||
active: boolean
|
||||
started_at?: ApiTimestamp
|
||||
}
|
||||
|
||||
type ApiSessionList = ApiSession[]
|
||||
|
||||
type SessionResponse = Awaited<ReturnType<typeof authClient.getSession>>
|
||||
|
||||
interface DashboardClientProps {
|
||||
initialActiveConnections: ApiSessionList
|
||||
}
|
||||
|
||||
type ActiveConnectionStatus = "connected" | "pending" | "error"
|
||||
|
||||
type ActiveConnection = {
|
||||
id: string
|
||||
name: string
|
||||
status: ActiveConnectionStatus
|
||||
protocol: string
|
||||
serverLabel: string
|
||||
remote: string
|
||||
localPort?: number
|
||||
serverPort?: number
|
||||
startedAgo?: string
|
||||
latencyMs?: number | null
|
||||
dataInOut?: string
|
||||
}
|
||||
|
||||
export default function DashboardClient({ initialActiveConnections }: DashboardClientProps) {
|
||||
const router = useRouter()
|
||||
const [selectedServer, setSelectedServer] = useState<Server | null>(null)
|
||||
const [tunnelConfig, setTunnelConfig] = useState<TunnelConfigType>(defaultConfig)
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null)
|
||||
const [activeConnections, setActiveConnections] = useState<ActiveConnection[]>(
|
||||
initialActiveConnections.map(toActiveConnection),
|
||||
)
|
||||
const { data: cachedSession } = authClient.useSession()
|
||||
const [session, setSession] = useState<SessionResponse["data"] | null>(cachedSession ?? null)
|
||||
|
||||
useEffect(() => {
|
||||
setActiveConnections(initialActiveConnections.map(toActiveConnection))
|
||||
}, [initialActiveConnections])
|
||||
|
||||
useEffect(() => {
|
||||
if (!session && cachedSession) {
|
||||
setSession(cachedSession)
|
||||
}
|
||||
}, [cachedSession, session])
|
||||
|
||||
const stopConnection = (id: string) => {
|
||||
setActiveConnections((prev) => prev.filter((conn) => conn.id !== id))
|
||||
setStatusMessage("Connection stopped")
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex-1">
|
||||
<div className="max-w-7xl mx-auto px-4 py-8 space-y-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold">Active Forwarding</h1>
|
||||
<p className="text-sm text-gray-400">Live tunnels for this session.</p>
|
||||
</div>
|
||||
|
||||
{statusMessage && (
|
||||
<div className="rounded-lg border border-emerald-700 bg-emerald-900/40 px-4 py-3 text-sm text-emerald-200">
|
||||
{statusMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border border-gray-800 bg-gray-900 p-5">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Active Connections</h2>
|
||||
<p className="text-sm text-gray-400">Monitor and manage your running tunnels</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.refresh()}
|
||||
className="text-sm text-emerald-400 hover:text-emerald-300"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{activeConnections.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-gray-700 bg-gray-800/60 p-6 text-center text-gray-400">
|
||||
No active connections yet. Configure a tunnel to see it here.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{activeConnections.map((connection) => {
|
||||
const metaParts: string[] = []
|
||||
if (connection.localPort && connection.serverPort) {
|
||||
metaParts.push(`Local ${connection.localPort} → Server ${connection.serverPort}`)
|
||||
}
|
||||
if (connection.startedAgo) {
|
||||
metaParts.push(connection.startedAgo)
|
||||
}
|
||||
const metaText = metaParts.length > 0 ? metaParts.join(" · ") : "No session metadata yet"
|
||||
|
||||
return (
|
||||
<div
|
||||
key={connection.id}
|
||||
className="rounded-lg border border-gray-800 bg-gray-800/60 p-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-white font-medium">{connection.name}</span>
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
|
||||
connection.status === "connected"
|
||||
? "bg-emerald-900/60 text-emerald-300 border border-emerald-700"
|
||||
: connection.status === "pending"
|
||||
? "bg-yellow-900/60 text-yellow-300 border border-yellow-700"
|
||||
: "bg-red-900/60 text-red-300 border border-red-700"
|
||||
}`}
|
||||
>
|
||||
{connection.status === "connected"
|
||||
? "Connected"
|
||||
: connection.status === "pending"
|
||||
? "Reconnecting"
|
||||
: "Error"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-300">
|
||||
{(connection.protocol || "http").toUpperCase()} · {connection.serverLabel}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">{connection.remote || "—"}</p>
|
||||
<p className="text-xs text-gray-500">{metaText}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 md:justify-end">
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-gray-300">Latency</p>
|
||||
<p className="text-lg font-semibold text-white">
|
||||
{connection.latencyMs != null ? `${connection.latencyMs}ms` : "—"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-gray-300">Data</p>
|
||||
<p className="text-lg font-semibold text-white">{connection.dataInOut || "—"}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => stopConnection(connection.id)}
|
||||
className="rounded-lg border border-gray-700 px-3 py-2 text-sm text-gray-200 hover:border-red-500 hover:text-red-200 transition"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-800 bg-gray-900 p-5">
|
||||
<div className="flex flex-col gap-2 mb-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Custom Tunnel Configuration</h2>
|
||||
<p className="text-sm text-gray-400">Pick a location, test latency, and shape your tunnel exactly how you need.</p>
|
||||
</div>
|
||||
<Link href="/tunnel-not-found" className="text-sm text-emerald-400 hover:text-emerald-300">
|
||||
View docs
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<TunnelConfig
|
||||
config={tunnelConfig}
|
||||
onConfigChange={setTunnelConfig}
|
||||
selectedServer={selectedServer}
|
||||
onServerSelect={setSelectedServer}
|
||||
isAuthenticated={Boolean(session)}
|
||||
userId={session?.user?.sshIdentifier}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -1,208 +1,39 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import TunnelConfig, { type TunnelConfig as TunnelConfigType, type Server } from "@/components/tunnel-config"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import SiteHeader from "@/components/site-header"
|
||||
import SiteFooter from "@/components/site-footer"
|
||||
import { auth } from "@/lib/auth"
|
||||
import { headers } from "next/headers"
|
||||
import DashboardClient from "./dashboard-client"
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const defaultConfig: TunnelConfigType = {
|
||||
type: "http",
|
||||
serverPort: 443,
|
||||
localPort: 8000,
|
||||
}
|
||||
export default async function DashboardPage() {
|
||||
const requestHeaders = await headers()
|
||||
const session = await auth.api.getSession({
|
||||
headers: requestHeaders,
|
||||
}).catch(() => {
|
||||
redirect('/')
|
||||
})
|
||||
|
||||
type ActiveConnection = {
|
||||
id: string
|
||||
name: string
|
||||
serverLabel: string
|
||||
protocol: TunnelConfigType["type"]
|
||||
localPort: number
|
||||
serverPort: number
|
||||
remote: string
|
||||
status: "connected" | "pending" | "error"
|
||||
latencyMs: number | null
|
||||
dataInOut: string
|
||||
startedAgo: string
|
||||
}
|
||||
const { token } = await auth.api.getToken({
|
||||
headers: requestHeaders,
|
||||
}).catch(() => {
|
||||
redirect('/')
|
||||
})
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [selectedServer, setSelectedServer] = useState<Server | null>(null)
|
||||
const [tunnelConfig, setTunnelConfig] = useState<TunnelConfigType>(defaultConfig)
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null)
|
||||
const [activeConnections, setActiveConnections] = useState<ActiveConnection[]>([
|
||||
{
|
||||
id: "conn-1",
|
||||
name: "Frontend Preview",
|
||||
serverLabel: "Singapore",
|
||||
protocol: "http",
|
||||
localPort: 3000,
|
||||
serverPort: 443,
|
||||
remote: "https://sgp.tunnl.live",
|
||||
status: "connected",
|
||||
latencyMs: 34,
|
||||
dataInOut: "1.2 GB",
|
||||
startedAgo: "3h 12m",
|
||||
const data = await fetch(`${process.env.API_URL}/api/sessions`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${token}`,
|
||||
},
|
||||
{
|
||||
id: "conn-2",
|
||||
name: "Game TCP",
|
||||
serverLabel: "Frankfurt",
|
||||
protocol: "tcp",
|
||||
localPort: 25565,
|
||||
serverPort: 20555,
|
||||
remote: "tcp://eu.tunnl.live:20555",
|
||||
status: "connected",
|
||||
latencyMs: 120,
|
||||
dataInOut: "320 MB",
|
||||
startedAgo: "54m",
|
||||
},
|
||||
])
|
||||
|
||||
type SessionResponse = Awaited<ReturnType<typeof authClient.getSession>>
|
||||
const [session, setSession] = useState<SessionResponse["data"] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSession = async () => {
|
||||
try {
|
||||
const result = await authClient.getSession()
|
||||
if (result.data) {
|
||||
setSession(result.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching session", error)
|
||||
}
|
||||
}
|
||||
|
||||
fetchSession()
|
||||
}, [])
|
||||
|
||||
const stopConnection = (id: string) => {
|
||||
setActiveConnections((prev) => prev.filter((conn) => conn.id !== id))
|
||||
setStatusMessage("Connection stopped")
|
||||
}
|
||||
cache: "no-store",
|
||||
})
|
||||
const initialActiveConnections = await data.json()
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-gray-950 text-white">
|
||||
<SiteHeader />
|
||||
|
||||
<main className="flex-1">
|
||||
<div className="max-w-7xl mx-auto px-4 py-8 space-y-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold">Active Forwarding</h1>
|
||||
<p className="text-sm text-gray-400">Live tunnels for this session.</p>
|
||||
</div>
|
||||
|
||||
{statusMessage && (
|
||||
<div className="rounded-lg border border-emerald-700 bg-emerald-900/40 px-4 py-3 text-sm text-emerald-200">
|
||||
{statusMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border border-gray-800 bg-gray-900 p-5">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Active Connections</h2>
|
||||
<p className="text-sm text-gray-400">Monitor and manage your running tunnels</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/tunnel-not-found"
|
||||
className="text-sm text-emerald-400 hover:text-emerald-300"
|
||||
>
|
||||
View logs
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{activeConnections.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-gray-700 bg-gray-800/60 p-6 text-center text-gray-400">
|
||||
No active connections yet. Configure a tunnel to see it here.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{activeConnections.map((connection) => (
|
||||
<div
|
||||
key={connection.id}
|
||||
className="rounded-lg border border-gray-800 bg-gray-800/60 p-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-white font-medium">{connection.name}</span>
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
|
||||
connection.status === "connected"
|
||||
? "bg-emerald-900/60 text-emerald-300 border border-emerald-700"
|
||||
: connection.status === "pending"
|
||||
? "bg-yellow-900/60 text-yellow-300 border border-yellow-700"
|
||||
: "bg-red-900/60 text-red-300 border border-red-700"
|
||||
}`}
|
||||
>
|
||||
{connection.status === "connected"
|
||||
? "Connected"
|
||||
: connection.status === "pending"
|
||||
? "Reconnecting"
|
||||
: "Error"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-300">
|
||||
{connection.protocol.toUpperCase()} · {connection.serverLabel}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">{connection.remote}</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Local {connection.localPort} → Server {connection.serverPort} · {connection.startedAgo}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 md:justify-end">
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-gray-300">Latency</p>
|
||||
<p className="text-lg font-semibold text-white">
|
||||
{connection.latencyMs ? `${connection.latencyMs}ms` : "—"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-gray-300">Data</p>
|
||||
<p className="text-lg font-semibold text-white">{connection.dataInOut}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => stopConnection(connection.id)}
|
||||
className="rounded-lg border border-gray-700 px-3 py-2 text-sm text-gray-200 hover:border-red-500 hover:text-red-200 transition"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-800 bg-gray-900 p-5">
|
||||
<div className="flex flex-col gap-2 mb-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Custom Tunnel Configuration</h2>
|
||||
<p className="text-sm text-gray-400">Pick a location, test latency, and shape your tunnel exactly how you need.</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/tunnel-not-found"
|
||||
className="text-sm text-emerald-400 hover:text-emerald-300"
|
||||
>
|
||||
View docs
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<TunnelConfig
|
||||
config={tunnelConfig}
|
||||
onConfigChange={setTunnelConfig}
|
||||
selectedServer={selectedServer}
|
||||
onServerSelect={setSelectedServer}
|
||||
isAuthenticated={Boolean(session)}
|
||||
userId={session?.user?.id}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<SiteHeader session={session} />
|
||||
<DashboardClient
|
||||
initialActiveConnections={initialActiveConnections}
|
||||
/>
|
||||
<SiteFooter />
|
||||
</div>
|
||||
)
|
||||
|
||||
25
app/page.tsx
25
app/page.tsx
@@ -5,7 +5,6 @@ import TunnelConfig, { type TunnelConfig as TunnelConfigType, type Server } from
|
||||
import SiteHeader from "@/components/site-header"
|
||||
import SiteFooter from "@/components/site-footer"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import { useEffect } from "react"
|
||||
|
||||
const defaultConfig: TunnelConfigType = {
|
||||
type: "http",
|
||||
@@ -16,26 +15,10 @@ const defaultConfig: TunnelConfigType = {
|
||||
export default function Home() {
|
||||
const [selectedServer, setSelectedServer] = useState<Server | null>(null)
|
||||
const [tunnelConfig, setTunnelConfig] = useState<TunnelConfigType>(defaultConfig)
|
||||
type SessionData = Awaited<ReturnType<typeof authClient.getSession>>;
|
||||
const [logedin, setLogedin] = useState<SessionData | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const result = await authClient.getSession()
|
||||
if (result.data != null) {
|
||||
setLogedin(result.data.user);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
const { data: session } = authClient.useSession()
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-gray-950 text-white">
|
||||
<SiteHeader />
|
||||
<SiteHeader session={session}/>
|
||||
<main className="flex-1 flex flex-col items-center justify-center px-4 py-8">
|
||||
<div className="w-full max-w-4xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
@@ -52,8 +35,8 @@ export default function Home() {
|
||||
onConfigChange={setTunnelConfig}
|
||||
selectedServer={selectedServer}
|
||||
onServerSelect={setSelectedServer}
|
||||
isAuthenticated={logedin != null ? true : false}
|
||||
userId={logedin?.id}
|
||||
isAuthenticated={Boolean(session)}
|
||||
userId={session?.user?.sshIdentifier}
|
||||
/>
|
||||
|
||||
<div className="max-w-3xl mx-auto">
|
||||
|
||||
@@ -1,40 +1,36 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import SiteHeader from "@/components/site-header"
|
||||
import SiteFooter from "@/components/site-footer"
|
||||
|
||||
export default function SettingsPage() {
|
||||
type SessionResponse = Awaited<ReturnType<typeof authClient.getSession>>
|
||||
const [session, setSession] = useState<SessionResponse["data"] | null>(null)
|
||||
const [requireAuth, setRequireAuth] = useState(true)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const { data: session, isPending } = authClient.useSession();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const loadSession = async () => {
|
||||
try {
|
||||
const result = await authClient.getSession()
|
||||
if (result.data) {
|
||||
setSession(result.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load session", error)
|
||||
}
|
||||
if (!isPending && !session) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [session, isPending, router]);
|
||||
|
||||
loadSession()
|
||||
}, [])
|
||||
|
||||
if (isPending) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
const handleToggle = (value: boolean) => {
|
||||
setRequireAuth(value)
|
||||
setMessage(value ? "Authentication required for tunnel requests" : "Authentication not required for tunnel requests")
|
||||
setTimeout(() => setMessage(null), 2500)
|
||||
}
|
||||
|
||||
return (
|
||||
return session ? (
|
||||
<div className="flex min-h-screen flex-col bg-gray-950 text-white">
|
||||
<SiteHeader />
|
||||
<SiteHeader session={session} />
|
||||
|
||||
<main className="flex-1">
|
||||
<div className="max-w-5xl mx-auto px-4 py-8 space-y-6">
|
||||
@@ -80,5 +76,5 @@ export default function SettingsPage() {
|
||||
</main>
|
||||
<SiteFooter />
|
||||
</div>
|
||||
)
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -3,29 +3,16 @@
|
||||
import Link from "next/link"
|
||||
import TunnlLogo from "./tunnl-logo"
|
||||
import UserMenu from "./user-menu"
|
||||
import { useEffect, useState } from "react"
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { redirect, RedirectType } from 'next/navigation'
|
||||
|
||||
export default function SiteHeader() {
|
||||
type SessionData = Awaited<ReturnType<typeof authClient.getSession>>;
|
||||
const [logedin, setLogedin] = useState<SessionData | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const result = await authClient.getSession()
|
||||
if (result.data != null) {
|
||||
setLogedin(result.data.user);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
type UseSessionReturn = ReturnType<typeof authClient.useSession>;
|
||||
type SessionType = UseSessionReturn extends { data: infer D } ? D : never;
|
||||
type SiteHeaderProps = {
|
||||
session?: SessionType;
|
||||
};
|
||||
|
||||
export default function SiteHeader({ session }: SiteHeaderProps) {
|
||||
const logout = async () => {
|
||||
await authClient.signOut({
|
||||
fetchOptions: {
|
||||
@@ -47,12 +34,12 @@ export default function SiteHeader() {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{logedin ? (
|
||||
{session ? (
|
||||
<UserMenu
|
||||
user={{
|
||||
name: logedin.name ?? "User",
|
||||
email: logedin.email ?? "",
|
||||
image: logedin.image ?? undefined,
|
||||
name: session.user?.name ?? "User",
|
||||
email: session.user.email ?? "",
|
||||
image: session.user.image ?? undefined,
|
||||
}}
|
||||
onSignOut={logout}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: "./app/db/schema/*",
|
||||
schema: "./lib/schema/*",
|
||||
out: "./drizzle",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL!
|
||||
|
||||
@@ -1,2 +1,8 @@
|
||||
import { createAuthClient } from "better-auth/react"
|
||||
export const authClient = createAuthClient({})
|
||||
import { jwtClient } from "better-auth/client/plugins"
|
||||
import { inferAdditionalFields } from "better-auth/client/plugins";
|
||||
import { auth } from "@/lib/auth"
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
plugins: [jwtClient(), inferAdditionalFields<typeof auth>()],
|
||||
})
|
||||
11
lib/auth.ts
11
lib/auth.ts
@@ -2,14 +2,25 @@ import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { db } from "@/lib/db";
|
||||
import * as schema from "@/lib/schema/auth"
|
||||
import { jwt } from "better-auth/plugins";
|
||||
|
||||
export const auth = betterAuth({
|
||||
plugins: [jwt()],
|
||||
socialProviders: {
|
||||
google: {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID!,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
additionalFields: {
|
||||
sshIdentifier: {
|
||||
type: "string",
|
||||
nullable: false,
|
||||
input: false,
|
||||
}
|
||||
},
|
||||
},
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: schema
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";
|
||||
import { relations, sql } from "drizzle-orm";
|
||||
import { pgTable, text, timestamp, boolean, index } from "drizzle-orm/pg-core";
|
||||
|
||||
export const user = pgTable("user", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
sshIdentifier: text("ssh_identifier")
|
||||
.notNull()
|
||||
.unique()
|
||||
.default(
|
||||
sql`substr(encode(gen_random_bytes(16), 'hex'), 1, 32)`
|
||||
),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: boolean("email_verified").default(false).notNull(),
|
||||
image: text("image"),
|
||||
@@ -13,49 +20,88 @@ export const user = pgTable("user", {
|
||||
.notNull(),
|
||||
});
|
||||
|
||||
export const session = pgTable("session", {
|
||||
export const session = pgTable(
|
||||
"session",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
token: text("token").notNull().unique(),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
ipAddress: text("ip_address"),
|
||||
userAgent: text("user_agent"),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
},
|
||||
(table) => [index("session_userId_idx").on(table.userId)],
|
||||
);
|
||||
|
||||
export const account = pgTable(
|
||||
"account",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
accountId: text("account_id").notNull(),
|
||||
providerId: text("provider_id").notNull(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("access_token"),
|
||||
refreshToken: text("refresh_token"),
|
||||
idToken: text("id_token"),
|
||||
accessTokenExpiresAt: timestamp("access_token_expires_at"),
|
||||
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
|
||||
scope: text("scope"),
|
||||
password: text("password"),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
},
|
||||
(table) => [index("account_userId_idx").on(table.userId)],
|
||||
);
|
||||
|
||||
export const verification = pgTable(
|
||||
"verification",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.defaultNow()
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
},
|
||||
(table) => [index("verification_identifier_idx").on(table.identifier)],
|
||||
);
|
||||
|
||||
export const jwks = pgTable("jwks", {
|
||||
id: text("id").primaryKey(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
token: text("token").notNull().unique(),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
ipAddress: text("ip_address"),
|
||||
userAgent: text("user_agent"),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
publicKey: text("public_key").notNull(),
|
||||
privateKey: text("private_key").notNull(),
|
||||
createdAt: timestamp("created_at").notNull(),
|
||||
expiresAt: timestamp("expires_at"),
|
||||
});
|
||||
|
||||
export const account = pgTable("account", {
|
||||
id: text("id").primaryKey(),
|
||||
accountId: text("account_id").notNull(),
|
||||
providerId: text("provider_id").notNull(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("access_token"),
|
||||
refreshToken: text("refresh_token"),
|
||||
idToken: text("id_token"),
|
||||
accessTokenExpiresAt: timestamp("access_token_expires_at"),
|
||||
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
|
||||
scope: text("scope"),
|
||||
password: text("password"),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
});
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
}));
|
||||
|
||||
export const verification = pgTable("verification", {
|
||||
id: text("id").primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.defaultNow()
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
});
|
||||
export const sessionRelations = relations(session, ({ one }) => ({
|
||||
user: one(user, {
|
||||
fields: [session.userId],
|
||||
references: [user.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const accountRelations = relations(account, ({ one }) => ({
|
||||
user: one(user, {
|
||||
fields: [account.userId],
|
||||
references: [user.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user