update: get active forwarder from api
This commit is contained in:
235
app/dashboard/dashboard-client.tsx
Normal file
235
app/dashboard/dashboard-client.tsx
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
"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"
|
||||||
|
|
||||||
|
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}.tunnl.live` : 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 [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 [session, setSession] = useState<SessionResponse["data"] | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setActiveConnections(initialActiveConnections.map(toActiveConnection))
|
||||||
|
}, [initialActiveConnections])
|
||||||
|
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
<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) => {
|
||||||
|
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,27 @@
|
|||||||
"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 SiteHeader from "@/components/site-header"
|
||||||
import SiteFooter from "@/components/site-footer"
|
import SiteFooter from "@/components/site-footer"
|
||||||
|
import { auth } from "@/lib/auth"
|
||||||
|
import { headers } from "next/headers"
|
||||||
|
import DashboardClient from "./dashboard-client"
|
||||||
|
|
||||||
const defaultConfig: TunnelConfigType = {
|
export default async function DashboardPage() {
|
||||||
type: "http",
|
const { token } = await auth.api.getToken({
|
||||||
serverPort: 443,
|
headers: await headers(),
|
||||||
localPort: 8000,
|
})
|
||||||
}
|
|
||||||
|
|
||||||
type ActiveConnection = {
|
const data = await fetch(`${process.env.API_URL}/api/sessions`, {
|
||||||
id: string
|
method: "GET",
|
||||||
name: string
|
headers: {
|
||||||
serverLabel: string
|
"Authorization": `Bearer ${token}`,
|
||||||
protocol: TunnelConfigType["type"]
|
|
||||||
localPort: number
|
|
||||||
serverPort: number
|
|
||||||
remote: string
|
|
||||||
status: "connected" | "pending" | "error"
|
|
||||||
latencyMs: number | null
|
|
||||||
dataInOut: string
|
|
||||||
startedAgo: string
|
|
||||||
}
|
|
||||||
|
|
||||||
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",
|
|
||||||
},
|
},
|
||||||
{
|
cache: "no-store",
|
||||||
id: "conn-2",
|
})
|
||||||
name: "Game TCP",
|
const initialActiveConnections = await data.json()
|
||||||
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")
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col bg-gray-950 text-white">
|
<div className="flex min-h-screen flex-col bg-gray-950 text-white">
|
||||||
<SiteHeader />
|
<SiteHeader />
|
||||||
|
<DashboardClient initialActiveConnections={initialActiveConnections} />
|
||||||
<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>
|
|
||||||
|
|
||||||
<SiteFooter />
|
<SiteFooter />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ export default function Home() {
|
|||||||
selectedServer={selectedServer}
|
selectedServer={selectedServer}
|
||||||
onServerSelect={setSelectedServer}
|
onServerSelect={setSelectedServer}
|
||||||
isAuthenticated={logedin != null ? true : false}
|
isAuthenticated={logedin != null ? true : false}
|
||||||
userId={logedin?.id}
|
userId={logedin?.sshIdentifier}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="max-w-3xl mx-auto">
|
<div className="max-w-3xl mx-auto">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineConfig } from "drizzle-kit";
|
import { defineConfig } from "drizzle-kit";
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
dialect: "postgresql",
|
dialect: "postgresql",
|
||||||
schema: "./app/db/schema/*",
|
schema: "./lib/schema/*",
|
||||||
out: "./drizzle",
|
out: "./drizzle",
|
||||||
dbCredentials: {
|
dbCredentials: {
|
||||||
url: process.env.DATABASE_URL!
|
url: process.env.DATABASE_URL!
|
||||||
|
|||||||
@@ -1,2 +1,8 @@
|
|||||||
import { createAuthClient } from "better-auth/react"
|
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 { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import * as schema from "@/lib/schema/auth"
|
import * as schema from "@/lib/schema/auth"
|
||||||
|
import { jwt } from "better-auth/plugins";
|
||||||
|
|
||||||
export const auth = betterAuth({
|
export const auth = betterAuth({
|
||||||
|
plugins: [jwt()],
|
||||||
socialProviders: {
|
socialProviders: {
|
||||||
google: {
|
google: {
|
||||||
clientId: process.env.GOOGLE_CLIENT_ID!,
|
clientId: process.env.GOOGLE_CLIENT_ID!,
|
||||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
user: {
|
||||||
|
additionalFields: {
|
||||||
|
sshIdentifier: {
|
||||||
|
type: "string",
|
||||||
|
nullable: false,
|
||||||
|
input: false,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
database: drizzleAdapter(db, {
|
database: drizzleAdapter(db, {
|
||||||
provider: "pg",
|
provider: "pg",
|
||||||
schema: schema
|
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", {
|
export const user = pgTable("user", {
|
||||||
id: text("id").primaryKey(),
|
id: text("id").primaryKey(),
|
||||||
name: text("name").notNull(),
|
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(),
|
email: text("email").notNull().unique(),
|
||||||
emailVerified: boolean("email_verified").default(false).notNull(),
|
emailVerified: boolean("email_verified").default(false).notNull(),
|
||||||
image: text("image"),
|
image: text("image"),
|
||||||
@@ -13,49 +20,88 @@ export const user = pgTable("user", {
|
|||||||
.notNull(),
|
.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(),
|
id: text("id").primaryKey(),
|
||||||
expiresAt: timestamp("expires_at").notNull(),
|
publicKey: text("public_key").notNull(),
|
||||||
token: text("token").notNull().unique(),
|
privateKey: text("private_key").notNull(),
|
||||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
createdAt: timestamp("created_at").notNull(),
|
||||||
updatedAt: timestamp("updated_at")
|
expiresAt: timestamp("expires_at"),
|
||||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
|
||||||
.notNull(),
|
|
||||||
ipAddress: text("ip_address"),
|
|
||||||
userAgent: text("user_agent"),
|
|
||||||
userId: text("user_id")
|
|
||||||
.notNull()
|
|
||||||
.references(() => user.id, { onDelete: "cascade" }),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const account = pgTable("account", {
|
export const userRelations = relations(user, ({ many }) => ({
|
||||||
id: text("id").primaryKey(),
|
sessions: many(session),
|
||||||
accountId: text("account_id").notNull(),
|
accounts: many(account),
|
||||||
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 verification = pgTable("verification", {
|
export const sessionRelations = relations(session, ({ one }) => ({
|
||||||
id: text("id").primaryKey(),
|
user: one(user, {
|
||||||
identifier: text("identifier").notNull(),
|
fields: [session.userId],
|
||||||
value: text("value").notNull(),
|
references: [user.id],
|
||||||
expiresAt: timestamp("expires_at").notNull(),
|
}),
|
||||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
}));
|
||||||
updatedAt: timestamp("updated_at")
|
|
||||||
.defaultNow()
|
export const accountRelations = relations(account, ({ one }) => ({
|
||||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
user: one(user, {
|
||||||
.notNull(),
|
fields: [account.userId],
|
||||||
});
|
references: [user.id],
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|||||||
Reference in New Issue
Block a user