pertama
This commit is contained in:
15
src/App.tsx
Normal file
15
src/App.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
import '@mantine/core/styles.css';
|
||||
import '@mantine/notifications/styles.css';
|
||||
import { Notifications } from '@mantine/notifications';
|
||||
|
||||
import { MantineProvider } from '@mantine/core';
|
||||
import AppRoutes from './AppRoutes';
|
||||
|
||||
export function App() {
|
||||
return <MantineProvider>
|
||||
<Notifications />
|
||||
<AppRoutes />
|
||||
</MantineProvider>;
|
||||
}
|
||||
|
||||
32
src/AppRoutes.tsx
Normal file
32
src/AppRoutes.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import Home from "./pages/Home";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import Login from "./pages/Login";
|
||||
import ProtectedRoute from "./components/ProtectedRoute";
|
||||
import Dashboard from "./pages/dashboard/dashboard_page";
|
||||
import DashboardLayout from "./pages/dashboard/dashboard_layout";
|
||||
import ApiKeyPage from "./pages/dashboard/apikey/apikey_page";
|
||||
|
||||
export default function AppRoutes() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/dashboard" element={<DashboardLayout />}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="landing" element={<Dashboard />} />
|
||||
<Route path="apikey" element={<ApiKeyPage />} />
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
11
src/clientRoutes.ts
Normal file
11
src/clientRoutes.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// AUTO-GENERATED FILE
|
||||
const clientRoutes = {
|
||||
"/": "/",
|
||||
"/login": "/login",
|
||||
"/dashboard": "/dashboard",
|
||||
"/dashboard/landing": "/dashboard/landing",
|
||||
"/dashboard/apikey": "/dashboard/apikey",
|
||||
"/*": "/*"
|
||||
} as const;
|
||||
|
||||
export default clientRoutes;
|
||||
25
src/components/ProtectedRoute.tsx
Normal file
25
src/components/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigate, Outlet } from 'react-router-dom'
|
||||
import clientRoutes from '@/clientRoutes'
|
||||
import apiFetch from '@/lib/apiFetch'
|
||||
|
||||
export default function ProtectedRoute() {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function checkSession() {
|
||||
try {
|
||||
// backend otomatis baca cookie JWT dari request
|
||||
const res = await apiFetch.api.user.find.get()
|
||||
setIsAuthenticated(res.status === 200)
|
||||
} catch {
|
||||
setIsAuthenticated(false)
|
||||
}
|
||||
}
|
||||
checkSession()
|
||||
}, [])
|
||||
|
||||
if (isAuthenticated === null) return null // or loading spinner
|
||||
if (!isAuthenticated) return <Navigate to={clientRoutes['/login']} replace />
|
||||
return <Outlet />
|
||||
}
|
||||
26
src/frontend.tsx
Normal file
26
src/frontend.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* This file is the entry point for the React app, it sets up the root
|
||||
* element and renders the App component to the DOM.
|
||||
*
|
||||
* It is included in `src/index.html`.
|
||||
*/
|
||||
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
|
||||
const elem = document.getElementById("root")!;
|
||||
const app = (
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
if (import.meta.hot) {
|
||||
// With hot module reloading, `import.meta.hot.data` is persisted.
|
||||
const root = (import.meta.hot.data.root ??= createRoot(elem));
|
||||
root.render(app);
|
||||
} else {
|
||||
// The hot module reloading API is not available in production.
|
||||
createRoot(elem).render(app);
|
||||
}
|
||||
187
src/index.css
Normal file
187
src/index.css
Normal file
@@ -0,0 +1,187 @@
|
||||
:root {
|
||||
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
position: relative;
|
||||
}
|
||||
body::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
opacity: 0.05;
|
||||
background: url("./logo.svg");
|
||||
background-size: 256px;
|
||||
transform: rotate(-12deg) scale(1.35);
|
||||
animation: slide 30s linear infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
@keyframes slide {
|
||||
from {
|
||||
background-position: 0 0;
|
||||
}
|
||||
to {
|
||||
background-position: 256px 224px;
|
||||
}
|
||||
}
|
||||
.app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.logo-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 0.3s;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.bun-logo {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
.bun-logo:hover {
|
||||
filter: drop-shadow(0 0 2em #fbf0dfaa);
|
||||
}
|
||||
.react-logo {
|
||||
animation: spin 20s linear infinite;
|
||||
}
|
||||
.react-logo:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
code {
|
||||
background-color: #1a1a1a;
|
||||
padding: 0.2em 0.4em;
|
||||
border-radius: 0.3em;
|
||||
font-family: monospace;
|
||||
}
|
||||
.api-tester {
|
||||
margin: 2rem auto 0;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
text-align: left;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
.endpoint-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
background: #1a1a1a;
|
||||
padding: 0.75rem;
|
||||
border-radius: 12px;
|
||||
font: monospace;
|
||||
border: 2px solid #fbf0df;
|
||||
transition: 0.3s;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.endpoint-row:focus-within {
|
||||
border-color: #f3d5a3;
|
||||
}
|
||||
.method {
|
||||
background: #fbf0df;
|
||||
color: #1a1a1a;
|
||||
padding: 0.3rem 0.7rem;
|
||||
border-radius: 8px;
|
||||
font-weight: 700;
|
||||
font-size: 0.9em;
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
width: min-content;
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
border: none;
|
||||
}
|
||||
.method option {
|
||||
text-align: left;
|
||||
}
|
||||
.url-input {
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
background: 0;
|
||||
border: 0;
|
||||
color: #fbf0df;
|
||||
font: 1em monospace;
|
||||
padding: 0.2rem;
|
||||
outline: 0;
|
||||
}
|
||||
.url-input:focus {
|
||||
color: #fff;
|
||||
}
|
||||
.url-input::placeholder {
|
||||
color: rgba(251, 240, 223, 0.4);
|
||||
}
|
||||
.send-button {
|
||||
background: #fbf0df;
|
||||
color: #1a1a1a;
|
||||
border: 0;
|
||||
padding: 0.4rem 1.2rem;
|
||||
border-radius: 8px;
|
||||
font-weight: 700;
|
||||
transition: 0.1s;
|
||||
cursor: var(--bun-cursor);
|
||||
}
|
||||
.send-button:hover {
|
||||
background: #f3d5a3;
|
||||
transform: translateY(-1px);
|
||||
cursor: pointer;
|
||||
}
|
||||
.response-area {
|
||||
width: 100%;
|
||||
min-height: 120px;
|
||||
background: #1a1a1a;
|
||||
border: 2px solid #fbf0df;
|
||||
border-radius: 12px;
|
||||
padding: 0.75rem;
|
||||
color: #fbf0df;
|
||||
font: monospace;
|
||||
resize: vertical;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.response-area:focus {
|
||||
border-color: #f3d5a3;
|
||||
}
|
||||
.response-area::placeholder {
|
||||
color: rgba(251, 240, 223, 0.4);
|
||||
}
|
||||
@media (prefers-reduced-motion) {
|
||||
*,
|
||||
::before,
|
||||
::after {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
13
src/index.html
Normal file
13
src/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" type="image/svg+xml" href="./logo.svg" />
|
||||
<title>Bun + React</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./frontend.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
45
src/index.tsx
Normal file
45
src/index.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
|
||||
import Elysia, { t } from "elysia";
|
||||
import Swagger from "@elysiajs/swagger";
|
||||
import html from "./index.html"
|
||||
import Dashboard from "./server/routes/darmasaba";
|
||||
import apiAuth from "./server/middlewares/apiAuth";
|
||||
import Auth from "./server/routes/auth_route";
|
||||
import ApiKeyRoute from "./server/routes/apikey_route";
|
||||
import type { User } from "generated/prisma";
|
||||
|
||||
const Docs = new Elysia()
|
||||
.use(Swagger({
|
||||
path: "/docs",
|
||||
}))
|
||||
|
||||
const ApiUser = new Elysia({
|
||||
prefix: "/user",
|
||||
})
|
||||
.get('/find', (ctx) => {
|
||||
const { user } = ctx as any
|
||||
return {
|
||||
user: user as User
|
||||
}
|
||||
})
|
||||
|
||||
const Api = new Elysia({
|
||||
prefix: "/api",
|
||||
})
|
||||
.use(apiAuth)
|
||||
.use(ApiKeyRoute)
|
||||
.use(Dashboard)
|
||||
.use(ApiUser)
|
||||
|
||||
const app = new Elysia()
|
||||
.use(Api)
|
||||
.use(Docs)
|
||||
.use(Auth)
|
||||
.get("*", html)
|
||||
.listen(3000, () => {
|
||||
console.log("Server running at http://localhost:3000");
|
||||
});
|
||||
|
||||
|
||||
export type ServerApp = typeof app;
|
||||
|
||||
11
src/lib/apiFetch.ts
Normal file
11
src/lib/apiFetch.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { treaty } from '@elysiajs/eden'
|
||||
import type { ServerApp } from '..'
|
||||
|
||||
const URL = process.env.BUN_PUBLIC_BASE_URL
|
||||
if (!URL) {
|
||||
throw new Error('BUN_PUBLIC_BASE_URL is not defined')
|
||||
}
|
||||
|
||||
const apiFetch = treaty<ServerApp>(URL)
|
||||
|
||||
export default apiFetch
|
||||
1
src/logo.svg
Normal file
1
src/logo.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg id="Bun" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 70"><title>Bun Logo</title><path id="Shadow" d="M71.09,20.74c-.16-.17-.33-.34-.5-.5s-.33-.34-.5-.5-.33-.34-.5-.5-.33-.34-.5-.5-.33-.34-.5-.5-.33-.34-.5-.5-.33-.34-.5-.5A26.46,26.46,0,0,1,75.5,35.7c0,16.57-16.82,30.05-37.5,30.05-11.58,0-21.94-4.23-28.83-10.86l.5.5.5.5.5.5.5.5.5.5.5.5.5.5C19.55,65.3,30.14,69.75,42,69.75c20.68,0,37.5-13.48,37.5-30C79.5,32.69,76.46,26,71.09,20.74Z"/><g id="Body"><path id="Background" d="M73,35.7c0,15.21-15.67,27.54-35,27.54S3,50.91,3,35.7C3,26.27,9,17.94,18.22,13S33.18,3,38,3s8.94,4.13,19.78,10C67,17.94,73,26.27,73,35.7Z" style="fill:#fbf0df"/><path id="Bottom_Shadow" data-name="Bottom Shadow" d="M73,35.7a21.67,21.67,0,0,0-.8-5.78c-2.73,33.3-43.35,34.9-59.32,24.94A40,40,0,0,0,38,63.24C57.3,63.24,73,50.89,73,35.7Z" style="fill:#f6dece"/><path id="Light_Shine" data-name="Light Shine" d="M24.53,11.17C29,8.49,34.94,3.46,40.78,3.45A9.29,9.29,0,0,0,38,3c-2.42,0-5,1.25-8.25,3.13-1.13.66-2.3,1.39-3.54,2.15-2.33,1.44-5,3.07-8,4.7C8.69,18.13,3,26.62,3,35.7c0,.4,0,.8,0,1.19C9.06,15.48,20.07,13.85,24.53,11.17Z" style="fill:#fffefc"/><path id="Top" d="M35.12,5.53A16.41,16.41,0,0,1,29.49,18c-.28.25-.06.73.3.59,3.37-1.31,7.92-5.23,6-13.14C35.71,5,35.12,5.12,35.12,5.53Zm2.27,0A16.24,16.24,0,0,1,39,19c-.12.35.31.65.55.36C41.74,16.56,43.65,11,37.93,5,37.64,4.74,37.19,5.14,37.39,5.49Zm2.76-.17A16.42,16.42,0,0,1,47,17.12a.33.33,0,0,0,.65.11c.92-3.49.4-9.44-7.17-12.53C40.08,4.54,39.82,5.08,40.15,5.32ZM21.69,15.76a16.94,16.94,0,0,0,10.47-9c.18-.36.75-.22.66.18-1.73,8-7.52,9.67-11.12,9.45C21.32,16.4,21.33,15.87,21.69,15.76Z" style="fill:#ccbea7;fill-rule:evenodd"/><path id="Outline" d="M38,65.75C17.32,65.75.5,52.27.5,35.7c0-10,6.18-19.33,16.53-24.92,3-1.6,5.57-3.21,7.86-4.62,1.26-.78,2.45-1.51,3.6-2.19C32,1.89,35,.5,38,.5s5.62,1.2,8.9,3.14c1,.57,2,1.19,3.07,1.87,2.49,1.54,5.3,3.28,9,5.27C69.32,16.37,75.5,25.69,75.5,35.7,75.5,52.27,58.68,65.75,38,65.75ZM38,3c-2.42,0-5,1.25-8.25,3.13-1.13.66-2.3,1.39-3.54,2.15-2.33,1.44-5,3.07-8,4.7C8.69,18.13,3,26.62,3,35.7,3,50.89,18.7,63.25,38,63.25S73,50.89,73,35.7C73,26.62,67.31,18.13,57.78,13,54,11,51.05,9.12,48.66,7.64c-1.09-.67-2.09-1.29-3-1.84C42.63,4,40.42,3,38,3Z"/></g><g id="Mouth"><g id="Background-2" data-name="Background"><path d="M45.05,43a8.93,8.93,0,0,1-2.92,4.71,6.81,6.81,0,0,1-4,1.88A6.84,6.84,0,0,1,34,47.71,8.93,8.93,0,0,1,31.12,43a.72.72,0,0,1,.8-.81H44.26A.72.72,0,0,1,45.05,43Z" style="fill:#b71422"/></g><g id="Tongue"><path id="Background-3" data-name="Background" d="M34,47.79a6.91,6.91,0,0,0,4.12,1.9,6.91,6.91,0,0,0,4.11-1.9,10.63,10.63,0,0,0,1-1.07,6.83,6.83,0,0,0-4.9-2.31,6.15,6.15,0,0,0-5,2.78C33.56,47.4,33.76,47.6,34,47.79Z" style="fill:#ff6164"/><path id="Outline-2" data-name="Outline" d="M34.16,47a5.36,5.36,0,0,1,4.19-2.08,6,6,0,0,1,4,1.69c.23-.25.45-.51.66-.77a7,7,0,0,0-4.71-1.93,6.36,6.36,0,0,0-4.89,2.36A9.53,9.53,0,0,0,34.16,47Z"/></g><path id="Outline-3" data-name="Outline" d="M38.09,50.19a7.42,7.42,0,0,1-4.45-2,9.52,9.52,0,0,1-3.11-5.05,1.2,1.2,0,0,1,.26-1,1.41,1.41,0,0,1,1.13-.51H44.26a1.44,1.44,0,0,1,1.13.51,1.19,1.19,0,0,1,.25,1h0a9.52,9.52,0,0,1-3.11,5.05A7.42,7.42,0,0,1,38.09,50.19Zm-6.17-7.4c-.16,0-.2.07-.21.09a8.29,8.29,0,0,0,2.73,4.37A6.23,6.23,0,0,0,38.09,49a6.28,6.28,0,0,0,3.65-1.73,8.3,8.3,0,0,0,2.72-4.37.21.21,0,0,0-.2-.09Z"/></g><g id="Face"><ellipse id="Right_Blush" data-name="Right Blush" cx="53.22" cy="40.18" rx="5.85" ry="3.44" style="fill:#febbd0"/><ellipse id="Left_Bluch" data-name="Left Bluch" cx="22.95" cy="40.18" rx="5.85" ry="3.44" style="fill:#febbd0"/><path id="Eyes" d="M25.7,38.8a5.51,5.51,0,1,0-5.5-5.51A5.51,5.51,0,0,0,25.7,38.8Zm24.77,0A5.51,5.51,0,1,0,45,33.29,5.5,5.5,0,0,0,50.47,38.8Z" style="fill-rule:evenodd"/><path id="Iris" d="M24,33.64a2.07,2.07,0,1,0-2.06-2.07A2.07,2.07,0,0,0,24,33.64Zm24.77,0a2.07,2.07,0,1,0-2.06-2.07A2.07,2.07,0,0,0,48.75,33.64Z" style="fill:#fff;fill-rule:evenodd"/></g></svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
9
src/pages/Home.tsx
Normal file
9
src/pages/Home.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Home</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
46
src/pages/Login.tsx
Normal file
46
src/pages/Login.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Button, Container, Group, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { useState } from "react";
|
||||
import apiFetch from "../lib/apiFetch";
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const response = await apiFetch.auth.login.post({
|
||||
email,
|
||||
password,
|
||||
})
|
||||
|
||||
if (response.data?.token) {
|
||||
localStorage.setItem('token', response.data.token)
|
||||
window.location.href = '/dashboard'
|
||||
return
|
||||
}
|
||||
|
||||
if (response.error) {
|
||||
alert(JSON.stringify(response.error))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Stack>
|
||||
<Text>Login</Text>
|
||||
<TextInput placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
<TextInput placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
|
||||
<Group justify="right">
|
||||
<Button onClick={handleSubmit} disabled={loading}>Login</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
9
src/pages/NotFound.tsx
Normal file
9
src/pages/NotFound.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div>
|
||||
<h1>404 Not Found</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
112
src/pages/dashboard/apikey/apikey_page.tsx
Normal file
112
src/pages/dashboard/apikey/apikey_page.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { Button, Card, Container, Group, Stack, Table, Text, TextInput } from "@mantine/core";
|
||||
import { useEffect, useState } from "react";
|
||||
import apiFetch from "@/lib/apiFetch";
|
||||
import { showNotification } from "@mantine/notifications";
|
||||
|
||||
export default function ApiKeyPage() {
|
||||
return (
|
||||
<Container size="md" w={"100%"}>
|
||||
<Stack>
|
||||
<Text>API Key</Text>
|
||||
<CreateApiKey />
|
||||
</Stack>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateApiKey() {
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [expiredAt, setExpiredAt] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
const res = await apiFetch.api.apikey.create.post({ name, description, expiredAt });
|
||||
if (res.status === 200) {
|
||||
setName('');
|
||||
setDescription('');
|
||||
setExpiredAt('');
|
||||
showNotification({
|
||||
title: 'Success',
|
||||
message: 'API key created successfully',
|
||||
color: 'green',
|
||||
})
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
return (
|
||||
<Card >
|
||||
<Stack>
|
||||
<Text>API Create</Text>
|
||||
<TextInput label="Name" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextInput label="Description" placeholder="Description" value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
<TextInput label="Expired At" placeholder="Expired At" type="date" value={expiredAt} onChange={(e) => setExpiredAt(e.target.value)} />
|
||||
<Group>
|
||||
<Button variant="outline" onClick={() => { setName(''); setDescription(''); setExpiredAt(''); }}>Cancel</Button>
|
||||
<Button onClick={handleSubmit} type="submit" loading={loading}>Save</Button>
|
||||
</Group>
|
||||
|
||||
<ListApiKey />
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ListApiKey() {
|
||||
const [apiKeys, setApiKeys] = useState<any[]>([]);
|
||||
useEffect(() => {
|
||||
const fetchApiKeys = async () => {
|
||||
const res = await apiFetch.api.apikey.list.get();
|
||||
if (res.status === 200) {
|
||||
setApiKeys(res.data?.apiKeys || []);
|
||||
}
|
||||
}
|
||||
fetchApiKeys();
|
||||
}, []);
|
||||
return (
|
||||
<Card>
|
||||
<Stack>
|
||||
<Text>API List</Text>
|
||||
<Table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Description</th>
|
||||
<th>Expired At</th>
|
||||
<th>Created At</th>
|
||||
<th>Updated At</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{apiKeys.map((apiKey: any, index: number) => (
|
||||
<tr key={index}>
|
||||
<td>{apiKey.name}</td>
|
||||
<td>{apiKey.description}</td>
|
||||
<td>{apiKey.expiredAt.toISOString().split('T')[0]}</td>
|
||||
<td>{apiKey.createdAt.toISOString().split('T')[0]}</td>
|
||||
<td>{apiKey.updatedAt.toISOString().split('T')[0]}</td>
|
||||
<td>
|
||||
<Button variant="outline" onClick={() => {
|
||||
apiFetch.api.apikey.delete.delete({ id: apiKey.id })
|
||||
setApiKeys(apiKeys.filter((api: any) => api.id !== apiKey.id))
|
||||
}}>Delete</Button>
|
||||
<Button variant="outline" onClick={() => {
|
||||
navigator.clipboard.writeText(apiKey.key)
|
||||
showNotification({
|
||||
title: 'Success',
|
||||
message: 'API key copied to clipboard',
|
||||
color: 'green',
|
||||
})
|
||||
}}>Copy</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
163
src/pages/dashboard/dashboard_layout.tsx
Normal file
163
src/pages/dashboard/dashboard_layout.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import {
|
||||
ActionIcon,
|
||||
AppShell,
|
||||
Avatar,
|
||||
Card,
|
||||
Flex,
|
||||
Group,
|
||||
NavLink,
|
||||
Paper,
|
||||
ScrollArea,
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
Tooltip
|
||||
} from '@mantine/core'
|
||||
import { useLocalStorage } from '@mantine/hooks'
|
||||
import {
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconDashboard
|
||||
} from '@tabler/icons-react'
|
||||
import type { User } from 'generated/prisma'
|
||||
import { data, Outlet, useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
import { default as clientRoute, default as clientRoutes } from '@/clientRoutes'
|
||||
import apiFetch from '@/lib/apiFetch'
|
||||
import { showNotification } from '@mantine/notifications'
|
||||
|
||||
export default function DashboardLayout() {
|
||||
const [opened, setOpened] = useLocalStorage({
|
||||
key: 'nav_open',
|
||||
defaultValue: true,
|
||||
})
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
padding="md"
|
||||
navbar={{
|
||||
width: 260,
|
||||
breakpoint: 'sm',
|
||||
collapsed: { mobile: !opened, desktop: !opened },
|
||||
}}
|
||||
>
|
||||
<AppShell.Navbar>
|
||||
<AppShell.Section>
|
||||
<Group justify="flex-end" p="xs">
|
||||
<Tooltip
|
||||
label={opened ? 'Collapse navigation' : 'Expand navigation'}
|
||||
withArrow
|
||||
>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="gray"
|
||||
onClick={() => setOpened(v => !v)}
|
||||
aria-label="Toggle navigation"
|
||||
radius="xl"
|
||||
>
|
||||
{opened ? <IconChevronLeft /> : <IconChevronRight />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</AppShell.Section>
|
||||
|
||||
<AppShell.Section grow component={ScrollArea} flex={1}>
|
||||
<NavigationDashboard />
|
||||
</AppShell.Section>
|
||||
|
||||
<AppShell.Section>
|
||||
<HostView />
|
||||
</AppShell.Section>
|
||||
</AppShell.Navbar>
|
||||
|
||||
<AppShell.Main>
|
||||
<Stack>
|
||||
<Paper withBorder shadow="md" radius="lg" p="md">
|
||||
<Flex align="center" gap="md">
|
||||
{!opened && (
|
||||
<Tooltip label="Open navigation menu" withArrow>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="gray"
|
||||
onClick={() => setOpened(true)}
|
||||
aria-label="Open navigation"
|
||||
radius="xl"
|
||||
>
|
||||
<IconChevronRight />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Title order={3} fw={600}>
|
||||
App Dashboard
|
||||
</Title>
|
||||
</Flex>
|
||||
</Paper>
|
||||
<Outlet />
|
||||
</Stack>
|
||||
</AppShell.Main>
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
/* ----------------------- Host Info ----------------------- */
|
||||
function HostView() {
|
||||
const [host, setHost] = useState<User | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchHost() {
|
||||
const {data} = await apiFetch.api.user.find.get()
|
||||
setHost(data?.user ?? null)
|
||||
}
|
||||
fetchHost()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Card radius="lg" withBorder shadow="sm" p="md">
|
||||
{host ? (
|
||||
<Flex gap="md" align="center">
|
||||
<Avatar size="md" radius="xl" color="blue">
|
||||
{host.name?.[0]}
|
||||
</Avatar>
|
||||
<Stack gap={2}>
|
||||
<Text fw={600}>{host.name}</Text>
|
||||
<Text size="sm" c="dimmed">{host.email}</Text>
|
||||
</Stack>
|
||||
</Flex>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center">
|
||||
No host information available
|
||||
</Text>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
/* ----------------------- Navigation ----------------------- */
|
||||
function NavigationDashboard() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
const isActive = (path: keyof typeof clientRoute) =>
|
||||
location.pathname.startsWith(clientRoute[path])
|
||||
|
||||
return (
|
||||
<Stack gap="xs" p="sm">
|
||||
<NavLink
|
||||
active={isActive('/dashboard/landing')}
|
||||
leftSection={<IconDashboard size={20} />}
|
||||
label="Dashboard Overview"
|
||||
description="Quick summary and activity highlights"
|
||||
onClick={() => navigate(clientRoutes['/dashboard/landing'])}
|
||||
/>
|
||||
<NavLink
|
||||
active={isActive('/dashboard/apikey')}
|
||||
leftSection={<IconDashboard size={20} />}
|
||||
label="Dashboard Overview"
|
||||
description="Quick summary and activity highlights"
|
||||
onClick={() => navigate(clientRoutes['/dashboard/apikey'])}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
8
src/pages/dashboard/dashboard_page.tsx
Normal file
8
src/pages/dashboard/dashboard_page.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
export default function Dashboard() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
src/react.svg
Normal file
8
src/react.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-11.5 -10.23174 23 20.46348">
|
||||
<circle cx="0" cy="0" r="2.05" fill="#61dafb"/>
|
||||
<g stroke="#61dafb" stroke-width="1" fill="none">
|
||||
<ellipse rx="11" ry="4.2"/>
|
||||
<ellipse rx="11" ry="4.2" transform="rotate(60)"/>
|
||||
<ellipse rx="11" ry="4.2" transform="rotate(120)"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 338 B |
11
src/server/lib/prisma.ts
Normal file
11
src/server/lib/prisma.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { PrismaClient } from 'generated/prisma'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma
|
||||
}
|
||||
54
src/server/middlewares/apiAuth.ts
Normal file
54
src/server/middlewares/apiAuth.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import jwt, { type JWTPayloadSpec } from '@elysiajs/jwt'
|
||||
import Elysia from 'elysia'
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
const secret = process.env.JWT_SECRET
|
||||
|
||||
export default function apiAuth(app: Elysia) {
|
||||
if (!secret) {
|
||||
throw new Error('JWT_SECRET is not defined')
|
||||
}
|
||||
return app
|
||||
.use(
|
||||
jwt({
|
||||
name: 'jwt',
|
||||
secret,
|
||||
})
|
||||
)
|
||||
.derive(async ({ cookie, headers, jwt }) => {
|
||||
let token: string | undefined
|
||||
|
||||
if (cookie?.token?.value) {
|
||||
token = cookie.token.value as any
|
||||
}
|
||||
if (headers['x-token']?.startsWith('Bearer ')) {
|
||||
token = (headers['x-token'] as string).slice(7)
|
||||
}
|
||||
if (headers['authorization']?.startsWith('Bearer ')) {
|
||||
token = (headers['authorization'] as string).slice(7)
|
||||
}
|
||||
|
||||
let user: null | Awaited<ReturnType<typeof prisma.user.findUnique>> = null
|
||||
if (token) {
|
||||
try {
|
||||
const decoded = (await jwt.verify(token)) as JWTPayloadSpec
|
||||
if (decoded.sub) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { id: decoded.sub as string },
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[SERVER][apiAuth] Invalid token', err)
|
||||
}
|
||||
}
|
||||
|
||||
return { user }
|
||||
})
|
||||
.onBeforeHandle(({ user, set }) => {
|
||||
if (!user) {
|
||||
set.status = 401
|
||||
return { error: 'Unauthorized' }
|
||||
}
|
||||
})
|
||||
}
|
||||
105
src/server/routes/apikey_route.ts
Normal file
105
src/server/routes/apikey_route.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { type JWTPayloadSpec } from '@elysiajs/jwt'
|
||||
import Elysia, { t } from 'elysia'
|
||||
import { type User } from 'generated/prisma'
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
const NINETY_YEARS = 60 * 60 * 24 * 365 * 90 // in seconds
|
||||
|
||||
type JWT = {
|
||||
sign(data: Record<string, string | number> & JWTPayloadSpec): Promise<string>
|
||||
verify(
|
||||
jwt?: string
|
||||
): Promise<false | (Record<string, string | number> & JWTPayloadSpec)>
|
||||
}
|
||||
|
||||
const ApiKeyRoute = new Elysia({
|
||||
prefix: '/apikey',
|
||||
detail: { tags: ['apikey'] },
|
||||
})
|
||||
.post(
|
||||
'/create',
|
||||
async ctx => {
|
||||
const { user }: { user: User } = ctx as any
|
||||
const { name, description, expiredAt } = ctx.body
|
||||
const { sign } = (ctx as any).jwt as JWT
|
||||
|
||||
// hitung expiredAt
|
||||
const exp = expiredAt
|
||||
? Math.floor(new Date(expiredAt).getTime() / 1000) // jika dikirim
|
||||
: Math.floor(Date.now() / 1000) + NINETY_YEARS // default 90 tahun
|
||||
|
||||
const token = await sign({
|
||||
sub: user.id,
|
||||
aud: 'host',
|
||||
exp,
|
||||
payload: JSON.stringify({
|
||||
name,
|
||||
description,
|
||||
expiredAt,
|
||||
}),
|
||||
})
|
||||
|
||||
const apiKey = await prisma.apiKey.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
key: token,
|
||||
userId: user.id,
|
||||
expiredAt: new Date(exp * 1000), // simpan juga di DB biar gampang query
|
||||
},
|
||||
})
|
||||
|
||||
return { message: 'success', token, apiKey }
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
summary: 'create api key',
|
||||
},
|
||||
body: t.Object({
|
||||
name: t.String(),
|
||||
description: t.String(),
|
||||
expiredAt: t.Optional(t.String({ format: 'date-time' })), // ISO date string
|
||||
}),
|
||||
}
|
||||
)
|
||||
.get(
|
||||
'/list',
|
||||
async ctx => {
|
||||
const { user }: { user: User } = ctx as any
|
||||
const apiKeys = await prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
return { message: 'success', apiKeys }
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
summary: 'get api key list',
|
||||
},
|
||||
}
|
||||
)
|
||||
.delete(
|
||||
'/delete',
|
||||
async ctx => {
|
||||
const { id } = ctx.body as { id: string }
|
||||
const apiKey = await prisma.apiKey.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
})
|
||||
return { message: 'success', apiKey }
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
summary: 'delete api key',
|
||||
},
|
||||
body: t.Object({
|
||||
id: t.String(),
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
export default ApiKeyRoute
|
||||
155
src/server/routes/auth_route.ts
Normal file
155
src/server/routes/auth_route.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { jwt as jwtPlugin, type JWTPayloadSpec } from '@elysiajs/jwt'
|
||||
import Elysia, { t, type Cookie, type HTTPHeaders, type StatusMap } from 'elysia'
|
||||
import { type ElysiaCookie } from 'elysia/cookies'
|
||||
|
||||
import { prisma } from '@/server/lib/prisma'
|
||||
import type { User } from 'generated/prisma'
|
||||
|
||||
const secret = process.env.JWT_SECRET
|
||||
if (!secret) {
|
||||
throw new Error('Missing JWT_SECRET in environment variables')
|
||||
}
|
||||
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
const NINETY_YEARS = 60 * 60 * 24 * 365 * 90
|
||||
|
||||
type JWT = {
|
||||
sign(data: Record<string, string | number> & JWTPayloadSpec): Promise<string>
|
||||
verify(
|
||||
jwt?: string
|
||||
): Promise<false | (Record<string, string | number> & JWTPayloadSpec)>
|
||||
}
|
||||
|
||||
type COOKIE = Record<string, Cookie<string | undefined>>
|
||||
|
||||
type SET = {
|
||||
headers: HTTPHeaders
|
||||
status?: number | keyof StatusMap
|
||||
redirect?: string
|
||||
cookie?: Record<string, ElysiaCookie>
|
||||
}
|
||||
|
||||
async function issueToken({
|
||||
jwt,
|
||||
cookie,
|
||||
userId,
|
||||
role,
|
||||
expiresAt,
|
||||
}: {
|
||||
jwt: JWT
|
||||
cookie: COOKIE
|
||||
userId: string
|
||||
role: 'host' | 'user'
|
||||
expiresAt: number
|
||||
}) {
|
||||
const token = await jwt.sign({
|
||||
sub: userId,
|
||||
aud: role,
|
||||
exp: expiresAt,
|
||||
})
|
||||
|
||||
cookie.token?.set({
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
secure: isProd, // aktifkan hanya di production (HTTPS)
|
||||
sameSite: 'strict',
|
||||
maxAge: NINETY_YEARS,
|
||||
path: '/',
|
||||
})
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
async function login({
|
||||
body,
|
||||
cookie,
|
||||
set,
|
||||
jwt,
|
||||
}: {
|
||||
body: { email: string; password: string }
|
||||
cookie: COOKIE
|
||||
set: SET
|
||||
jwt: JWT
|
||||
}) {
|
||||
try {
|
||||
const { email, password } = body
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
set.status = 401
|
||||
return { message: 'User not found' }
|
||||
}
|
||||
|
||||
if (user.password !== password) {
|
||||
set.status = 401
|
||||
return { message: 'Invalid password' }
|
||||
}
|
||||
|
||||
const token = await issueToken({
|
||||
jwt,
|
||||
cookie,
|
||||
userId: user.id,
|
||||
role: 'user',
|
||||
expiresAt: Math.floor(Date.now() / 1000) + NINETY_YEARS,
|
||||
})
|
||||
return { token }
|
||||
} catch (error) {
|
||||
console.error('Error logging in:', error)
|
||||
return {
|
||||
message: 'Login failed',
|
||||
error:
|
||||
error instanceof Error ? error.message : JSON.stringify(error ?? null),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Auth = new Elysia({
|
||||
prefix: '/auth',
|
||||
detail: { description: 'Auth API', summary: 'Auth API', tags: ['auth'] },
|
||||
})
|
||||
.use(
|
||||
jwtPlugin({
|
||||
name: 'jwt',
|
||||
secret,
|
||||
})
|
||||
)
|
||||
.post(
|
||||
'/login',
|
||||
async ({ jwt, body, cookie, set }) => {
|
||||
return await login({
|
||||
jwt: jwt as JWT,
|
||||
body,
|
||||
cookie: cookie as any,
|
||||
set: set as any,
|
||||
})
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
email: t.String(),
|
||||
password: t.String(),
|
||||
}),
|
||||
detail: {
|
||||
description: 'Login with phone; auto-register if not found',
|
||||
summary: 'login',
|
||||
},
|
||||
}
|
||||
)
|
||||
.delete(
|
||||
'/logout',
|
||||
({ cookie }) => {
|
||||
cookie.token?.remove()
|
||||
return { message: 'Logout successful' }
|
||||
},
|
||||
{
|
||||
detail: {
|
||||
description: 'Logout (clear token cookie)',
|
||||
summary: 'logout',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export default Auth
|
||||
8
src/server/routes/darmasaba.ts
Normal file
8
src/server/routes/darmasaba.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import Elysia from "elysia";
|
||||
|
||||
const Dashboard = new Elysia({
|
||||
prefix: "/dashboard"
|
||||
})
|
||||
.get("/apa", () => "Hello World")
|
||||
|
||||
export default Dashboard
|
||||
Reference in New Issue
Block a user