mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-12-01 01:15:36 +00:00
Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b17b556fa2 | |||
| 97d6b111e0 | |||
| 698ba092ea | |||
| 06ed6c8405 | |||
| 17d87cefde | |||
| 6af6ba5d2a | |||
| 1ee5ce681a | |||
| 68588bf9e4 | |||
| 71487d40b6 | |||
| 32f4e95194 | |||
| 0cc78ad586 | |||
| db26e88196 | |||
| 76f39b6fc5 | |||
| eba0878c59 | |||
| e196fc6008 | |||
| 2630c1fa22 | |||
| 8ed0085670 | |||
| e25916728f | |||
| 7d15508cf2 | |||
| fa34b386ff | |||
| b8122a94ee | |||
| 4439ccadfb | |||
| b8064a73fb | |||
| 78232e85f1 | |||
| d743538892 |
251
README.md
251
README.md
@@ -1,6 +1,6 @@
|
||||
# MantisBase Admin Dashboard
|
||||
|
||||
A modern, web-based admin dashboard for managing your MantisBase backend. This dashboard provides an intuitive interface for managing entities, admins, settings, and more.
|
||||
A modern, web-based admin dashboard for managing your [MantisBase](https://github.com/allankoechke/mantisbase) backend. Manage entities, schemas, auth, OAuth, API keys, admins, settings, and logs from a single UI.
|
||||
|
||||

|
||||
|
||||
@@ -9,176 +9,225 @@ A modern, web-based admin dashboard for managing your MantisBase backend. This d
|
||||
- [About](#about)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Development](#development)
|
||||
- [Authentication](#authentication)
|
||||
- [Building for Production](#building-for-production)
|
||||
- [Integration with MantisBase](#integration-with-mantisbase)
|
||||
- [Features](#features)
|
||||
- [API Reference](#api-reference)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Links](#links)
|
||||
|
||||
## About
|
||||
|
||||
MantisBase Admin Dashboard is the official administrative interface for [MantisBase](https://github.com/allankoechke/mantisbase), a lightweight Backend-as-a-Service (BaaS) written in C++. This dashboard allows you to:
|
||||
|
||||
- Manage database entities and their schemas
|
||||
- Configure access rules and permissions
|
||||
- Manage admin users
|
||||
- View application logs
|
||||
- Configure application settings
|
||||
- And much more!
|
||||
MantisBase Admin is the official administrative interface for MantisBase, a lightweight Backend-as-a-Service (BaaS) written in C++. It talks to the MantisBase REST API at `/api/v1/` and is designed to be served alongside the backend (typically under `/mb/`).
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before you begin, ensure you have the following installed:
|
||||
|
||||
- **Node.js** (version 20 or higher)
|
||||
- **npm** (comes with Node.js)
|
||||
- A running **MantisBase** server instance
|
||||
- **Node.js** 20 or higher
|
||||
- **npm**
|
||||
- A running **MantisBase** server (default port `7070`)
|
||||
|
||||
### Installation
|
||||
|
||||
1. **Clone the repository**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/allankoechke/mantisbase-admin.git
|
||||
cd mantis-admin
|
||||
cd mantisbase-admin
|
||||
```
|
||||
|
||||
2. **Install dependencies**
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **Start the development server**
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
4. **Open your browser**
|
||||
Navigate to `http://localhost:3000` (or the port shown in your terminal)
|
||||
4. **Open the app**
|
||||
|
||||
### First Login
|
||||
Navigate to `http://localhost:3000` (or the port shown in the terminal).
|
||||
|
||||
1. If this is your first time setting up MantisBase, you'll need to create an admin account:
|
||||
- Navigate to `/mb/setup?token=YOUR_SETUP_TOKEN`
|
||||
- Enter your email and password
|
||||
- You'll be redirected to the login page
|
||||
In development, API requests to `/api/*` are proxied to the MantisBase backend (see [Development](#development)).
|
||||
|
||||
2. Log in with your admin credentials at `/mb/login`
|
||||
### First login
|
||||
|
||||
1. **Initial setup** (first run of MantisBase only):
|
||||
|
||||
- Go to `/mb/setup?token=YOUR_SETUP_TOKEN`
|
||||
- Create the first admin account
|
||||
- You will be redirected to login
|
||||
|
||||
2. **Sign in** at `/mb/login` with your admin credentials.
|
||||
|
||||
## Development
|
||||
|
||||
### Available Scripts
|
||||
### Scripts
|
||||
|
||||
- `npm run dev` - Start the development server with hot-reload
|
||||
- `npm run build` - Build the application for production
|
||||
- `npm run lint` - Run ESLint to check code quality
|
||||
- `npm start` - Start the production server (requires build first)
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `npm run dev` | Development server with hot reload |
|
||||
| `npm run build` | Production static export to `out/` |
|
||||
| `npm run lint` | Run ESLint |
|
||||
| `npm start` | Production server (requires build) |
|
||||
|
||||
### Development Mode
|
||||
### Dev API proxy
|
||||
|
||||
In development mode, the dashboard will:
|
||||
- Connect to `http://localhost:7070` by default (or the port specified in `MANTIS_PORT` environment variable)
|
||||
- Enable hot module replacement for faster development
|
||||
- Show detailed error messages
|
||||
During `npm run dev`, Next.js rewrites `/api/:path*` to the MantisBase backend so the admin UI and API share the same origin. That allows **HttpOnly session cookies** to work without CORS issues.
|
||||
|
||||
### Environment Variables
|
||||
Default target: `http://127.0.0.1:7070` (override with `MANTIS_PORT` or `MANTIS_PROXY_URL`).
|
||||
|
||||
You can customize the development setup using environment variables:
|
||||
When `NEXT_PUBLIC_MANTIS_BASE_URL` is set, the client calls that URL directly instead of using the dev proxy (useful for remote backends).
|
||||
|
||||
- `MANTIS_PORT` - Port for the MantisBase API (default: 7070)
|
||||
- `NEXT_PUBLIC_BASE_PATH` - Base path for the app (default: `/mb` in production, empty in dev). Set to empty string for no prefix; overrides at both build and runtime.
|
||||
- `NEXT_PUBLIC_MANTIS_BASE_URL` - Backend API base URL. When set (e.g. `https://api.example.com`), all API and login requests use this URL instead of same-origin or localhost. Omit trailing slash.
|
||||
- `NEXT_PUBLIC_MB_IS_DEMO_MODE` - Set to `true` or `1` to enable demo mode: prefills login with test credentials and shows a banner that data is cleared every 30 minutes
|
||||
### Environment variables
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `MANTIS_PORT` | MantisBase API port when using the dev proxy (default: `7070`) |
|
||||
| `MANTIS_PROXY_URL` | Full backend URL for the dev proxy (overrides `MANTIS_PORT`) |
|
||||
| `NEXT_PUBLIC_BASE_PATH` | App base path. Default: `/mb` in production, empty in dev. Set to `""` for no prefix. |
|
||||
| `NEXT_PUBLIC_MANTIS_BASE_URL` | Backend API base URL (e.g. `https://api.example.com`). No trailing slash. Bypasses same-origin/proxy. |
|
||||
| `NEXT_PUBLIC_MB_IS_DEMO_MODE` | Set to `true` or `1` for demo mode (prefilled login + demo banner) |
|
||||
|
||||
## Authentication
|
||||
|
||||
Admin authentication uses **HttpOnly cookies** set by the backend on login/refresh. The dashboard does **not** store JWTs in `localStorage` or `sessionStorage`.
|
||||
|
||||
- Login: `POST /api/v1/sys/admins/login`
|
||||
- Session check: `GET /api/v1/sys/admins`
|
||||
- Logout: `POST /api/v1/sys/admins/logout`
|
||||
|
||||
All authenticated API calls use `credentials: "include"`.
|
||||
|
||||
## Building for Production
|
||||
|
||||
To build the dashboard for production:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
The built static files will be in the `out/` directory. These files can be served by any static file server.
|
||||
Static files are written to `out/` and can be served by any static host or bundled with MantisBase (see below).
|
||||
|
||||
### Static Export
|
||||
Production builds use `output: 'export'` and default `basePath` of `/mb`.
|
||||
|
||||
The dashboard is configured for static export, making it easy to deploy to:
|
||||
- GitHub Pages
|
||||
- Netlify
|
||||
- Vercel
|
||||
- Any static hosting service
|
||||
## Integration with MantisBase
|
||||
|
||||
## 🔗 Integration with MantisBase
|
||||
### The `mb-admins` branch
|
||||
|
||||
### The `mb-admins` Branch
|
||||
This repo includes an `mb-admins` branch with **built static files**, integrated into the main [MantisBase](https://github.com/allankoechke/mantisbase) project via CMake.
|
||||
|
||||
This repository includes a special branch called `mb-admins` that is automatically integrated with the main [MantisBase project](https://github.com/allankoechke/mantisbase) via CMake.
|
||||
|
||||
**Important Notes:**
|
||||
|
||||
- The `mb-admins` branch contains the built static files of the admin dashboard
|
||||
- This branch is **automatically updated** on every release
|
||||
- The MantisBase CMake build system uses this branch to include the admin interface
|
||||
- When you build MantisBase, it automatically fetches the latest admin dashboard from this branch
|
||||
|
||||
### How It Works
|
||||
|
||||
1. When a new version is released (tagged with `v*`), a GitHub Action automatically:
|
||||
- Builds the admin dashboard
|
||||
- Updates the `mb-admins` branch with the latest static files
|
||||
- Creates a GitHub release with downloadable assets
|
||||
|
||||
2. The MantisBase CMake configuration:
|
||||
- Clones or updates the `mb-admins` branch during build
|
||||
- Includes the admin dashboard files in the MantisBase build
|
||||
- Serves the admin interface at `/mb/*` when MantisBase is running
|
||||
|
||||
This integration ensures that MantisBase always includes the latest stable version of the admin dashboard without requiring manual updates.
|
||||
- Updated automatically on release tags (`v*`)
|
||||
- MantisBase fetches this branch during its build
|
||||
- Admin UI is served at `/mb/*` when MantisBase is running
|
||||
|
||||
## Features
|
||||
|
||||
### Entity Management
|
||||
- Create, read, update, and delete database entities
|
||||
- Configure entity schemas with custom fields
|
||||
- Set up access rules (list, get, add, update, delete)
|
||||
- View and manage entity records
|
||||
### Database & entities
|
||||
|
||||
### Admin Management
|
||||
- Create and manage admin user accounts
|
||||
- Change admin passwords
|
||||
- View admin activity
|
||||
- List, create, and open entities
|
||||
- **Entity types:** `base`, `auth`, and `view` (read-only SQL views)
|
||||
- **Configure drawer** (three tabs):
|
||||
- **Fields** — schema editor with constraints, validators, foreign keys
|
||||
- **OAuth** — register providers and enable/disable per auth entity (see below)
|
||||
- **Access Rules** — per-operation modes: admin-only, public, authenticated, custom expression
|
||||
- Record CRUD with search/filter, column visibility, file field uploads
|
||||
- Legacy field types (`int32`, `xml`, `blob`, etc.) are normalized in the editor and auto-migrated on save
|
||||
- **Field types:** `string`, `double`, `date`, `int` (with precision `u8`–`u64`, `i8`–`i64`), `json`, `bool`, `file`, `files`
|
||||
- In-app **API documentation** drawers:
|
||||
- Schema-level docs on the database list page
|
||||
- Per-entity docs on the entity detail page (CRUD, files, realtime SSE/WebSocket, auth/OAuth when applicable)
|
||||
|
||||
### Auth entities
|
||||
|
||||
For entities with `type: "auth"`:
|
||||
|
||||
- **Records** tab — user records
|
||||
- **API Keys** tab — list/create/revoke entity user API keys (`/api/v1/auth/{entity}/api-keys`)
|
||||
- Per-user “Create API Key” from row actions
|
||||
- **OAuth** (in configure drawer) — global provider registry + per-entity enablement via `enabled_for_entity`
|
||||
|
||||
OAuth workflow:
|
||||
|
||||
1. Register providers (name, client ID, secret) in the entity **OAuth** tab
|
||||
2. Toggle **Enabled for entity** (calls `POST/DELETE /api/v1/sys/oauth/entity-config`)
|
||||
3. Status is read from `GET /api/v1/auth/{entity}/oauth/providers` (`enabled_for_entity` on each provider)
|
||||
4. User login requires the provider to be globally enabled **and** enabled for that entity
|
||||
|
||||
### Admins
|
||||
|
||||
- **Accounts** tab — create, list, delete admin users; change passwords
|
||||
- **API Keys** tab — admin API keys (`/api/v1/sys/api-keys`) with create, edit, revoke; secret shown once at creation
|
||||
|
||||
### Settings
|
||||
- Configure application settings
|
||||
- Manage file upload limits
|
||||
- Configure session timeouts
|
||||
- Enable/disable features
|
||||
|
||||
Connected to `GET/PATCH /api/v1/sys/settings/config`:
|
||||
|
||||
- **General** — organization name, site domain, CORS origins
|
||||
- **File & Sessions** — max upload size (MB in UI, bytes in API), session timeouts
|
||||
- **Features** — registration, email verification, schema mutations, JWT issuer/audience flags
|
||||
- **SMTP** — outbound mail configuration, plus **Test SMTP** (`POST /api/v1/sys/settings/smtp/test`) using the saved server config
|
||||
- Server version from settings (`mantisVersion`) shown in the Settings header
|
||||
|
||||
Site domain is used for OAuth callback URL hints in the configure drawer.
|
||||
|
||||
### Logs
|
||||
- View application logs
|
||||
- Filter and search logs
|
||||
- Monitor system activity
|
||||
|
||||
### Modern UI
|
||||
- Dark/light theme support
|
||||
- Responsive design
|
||||
- Intuitive navigation
|
||||
- Real-time updates
|
||||
- Browse and filter application logs from `/api/v1/sys/logs`
|
||||
|
||||
## 🔗 Links
|
||||
### UI
|
||||
|
||||
- **Main MantisBase Project**: [https://github.com/allankoechke/mantisbase](https://github.com/allankoechke/mantisbase)
|
||||
- **Documentation**: [https://docs.mantisbase.com](https://docs.mantisbase.com)
|
||||
- **This Repository**: [https://github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
|
||||
- Dark/light theme
|
||||
- Responsive layout with sidebar navigation
|
||||
- Toast notifications and confirmation dialogs
|
||||
|
||||
## Notes
|
||||
## API Reference
|
||||
|
||||
> **Note**: This project is still in active development. Some features may be incomplete or subject to change.
|
||||
| Resource | Location |
|
||||
|----------|----------|
|
||||
| OpenAPI spec | [`openapi.yaml`](openapi.yaml) in this repository |
|
||||
| In-app schema API docs | Database page → documentation icon |
|
||||
| In-app entity API docs | Entity detail page → documentation icon |
|
||||
| External docs | [docs.mantisbase.com](https://docs.mantisbase.com) |
|
||||
|
||||
The OpenAPI spec covers entity CRUD, auth (login, refresh, API keys, OAuth), files (`/api/v1/files/{entity}/{file}`), realtime (SSE + WebSocket), schema management, and system routes (admins, settings, logs, OAuth registry).
|
||||
|
||||
**Response envelope:** most JSON endpoints return `{ "status", "data", "error" }`.
|
||||
|
||||
**Entity user credentials:** JWT or API key (`mb_sk_...`) via `Authorization: Bearer <token>`.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
app/ Next.js app shell and routes
|
||||
components/
|
||||
admins/ Admin accounts and admin API keys
|
||||
api-keys/ Shared API key UI (admins + auth entities)
|
||||
database/ Entities, records, schema config, API doc drawers
|
||||
oauth/ OAuth provider dialogs and entity OAuth panel
|
||||
settings/ Application settings
|
||||
logs/ Log viewer
|
||||
lib/
|
||||
api.ts API client, types, endpoint constants
|
||||
field-types.ts Field type definitions and migration helpers
|
||||
schema-migration.ts Legacy schema normalization
|
||||
openapi.yaml MantisBase REST API OpenAPI 3.1 spec
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- **MantisBase:** [github.com/allankoechke/mantisbase](https://github.com/allankoechke/mantisbase)
|
||||
- **Documentation:** [docs.mantisbase.com](https://docs.mantisbase.com)
|
||||
- **This repository:** [github.com/allankoechke/mantisbase-admin](https://github.com/allankoechke/mantisbase-admin)
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
Contributions are welcome. Please open an issue or pull request on GitHub.
|
||||
|
||||
## License
|
||||
|
||||
This project is part of the MantisBase ecosystem. Please refer to the main MantisBase repository for license information.
|
||||
Part of the MantisBase ecosystem. See the main MantisBase repository for license details.
|
||||
|
||||
@@ -31,7 +31,8 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { ApiClient, SYS_ADMINS_API, type TableMetadata, type Admin, type AppSettings } from "@/lib/api"
|
||||
import { ApiClient, SYS_ADMINS_API, type TableMetadata, type Admin } from "@/lib/api"
|
||||
import { applySchemaListMigration } from "@/lib/schema-migration"
|
||||
import { DatabaseSection } from "./database/database-section"
|
||||
import { AdminsSection } from "./admins/admins-section"
|
||||
import { SettingsSection } from "./settings/settings-section"
|
||||
@@ -39,26 +40,22 @@ import { LogsSection } from "./logs/logs-section"
|
||||
import { SyncSection } from "./sync/sync-section"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { ThemeToggle } from "./theme-toggle"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useAppState, type AppMode } from "@/lib/app-state"
|
||||
import { useNavigate, useLocation } from "react-router-dom"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { getDashboardSection, ROUTES } from "@/lib/routes"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface AdminDashboardProps {
|
||||
token: string
|
||||
onLogout: () => void
|
||||
}
|
||||
|
||||
export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
export function AdminDashboard() {
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [tables, setTables] = React.useState<TableMetadata[]>([])
|
||||
const [admins, setAdmins] = React.useState<Admin[]>([])
|
||||
const [loading, setLoading] = React.useState(true)
|
||||
const [settings, setSettings] = React.useState<AppSettings | null>(null)
|
||||
const [authErrorDialog, setAuthErrorDialog] = React.useState(false)
|
||||
const [authErrorReason, setAuthErrorReason] = React.useState("") // Auth error reason
|
||||
const { toast } = useToast()
|
||||
const { route, navigate } = useRouter()
|
||||
const { mode } = useAppState()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { logout, refreshSession } = useAuth()
|
||||
|
||||
const showError = React.useCallback(
|
||||
(error: string, type: "error" | "warning" = "error") => {
|
||||
@@ -88,18 +85,22 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
[toast],
|
||||
)
|
||||
|
||||
const handleUnauthorized = React.useCallback((reason?: string | "") => {
|
||||
const handleUnauthorized = React.useCallback(async (reason?: string | "") => {
|
||||
try {
|
||||
setAuthErrorReason(reason || "") // Set the auth error string
|
||||
setAuthErrorDialog(true) // Set the auth dialog to open
|
||||
// Don't call handleLogout() here - let the dialog handle navigation
|
||||
const stillAuthenticated = await refreshSession()
|
||||
if (stillAuthenticated) {
|
||||
return
|
||||
}
|
||||
|
||||
setAuthErrorReason(reason || "")
|
||||
setAuthErrorDialog(true)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle unauthorized:", error)
|
||||
}
|
||||
}, [])
|
||||
}, [refreshSession])
|
||||
|
||||
const [apiClient, setApiClient] = React.useState(
|
||||
() => new ApiClient(token || "", handleUnauthorized, showError),
|
||||
() => new ApiClient(handleUnauthorized, showError),
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -109,9 +110,9 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
|
||||
// Update API client when mode or settings change
|
||||
React.useEffect(() => {
|
||||
const newApiClient = new ApiClient(token || "", handleUnauthorized, showError)
|
||||
const newApiClient = new ApiClient(handleUnauthorized, showError)
|
||||
setApiClient(newApiClient)
|
||||
}, [token, handleUnauthorized, showError])
|
||||
}, [handleUnauthorized, showError])
|
||||
|
||||
const loadAdmins = React.useCallback(async () => {
|
||||
if (!apiClient) return
|
||||
@@ -139,29 +140,12 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
|
||||
// Load admins when navigating to the admins page
|
||||
React.useEffect(() => {
|
||||
// Check if we're on the admins page
|
||||
const pathParts = route.path.split("/").filter(Boolean)
|
||||
const section = pathParts[0] || "entities"
|
||||
if (section === "admins") {
|
||||
if (getDashboardSection(location.pathname) === "admins") {
|
||||
loadAdmins()
|
||||
}
|
||||
}, [route.path, loadAdmins])
|
||||
}, [location.pathname, loadAdmins])
|
||||
|
||||
const loadData = async () => {
|
||||
// Set default settings if loading fails
|
||||
setSettings({
|
||||
appName: "ACME Mantis Project",
|
||||
baseUrl: "http://127.0.0.1:7070",
|
||||
mantisVersion: "0.0.0",
|
||||
maintenanceMode: false,
|
||||
maxFileSize: 10,
|
||||
allowRegistration: true,
|
||||
emailVerificationRequired: false,
|
||||
sessionTimeout: 84000,
|
||||
adminSessionTimeout: 3600,
|
||||
mode: mode,
|
||||
})
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
|
||||
@@ -176,7 +160,8 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
tablesArray = tablesData.data
|
||||
}
|
||||
|
||||
setTables(tablesArray)
|
||||
const migratedTables = await applySchemaListMigration(apiClient, tablesArray)
|
||||
setTables(migratedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to load data:", error)
|
||||
} finally {
|
||||
@@ -185,10 +170,10 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
}
|
||||
|
||||
|
||||
const handleLogout = () => {
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
localStorage.removeItem("admin_token")
|
||||
onLogout()
|
||||
await logout()
|
||||
navigate(ROUTES.login, { replace: true })
|
||||
} catch (error) {
|
||||
console.warn("Failed to logout:", error)
|
||||
}
|
||||
@@ -211,55 +196,35 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleModeChange = (newMode: AppMode, baseUrl?: string) => {
|
||||
// Update API client when mode changes (mode is handled via app state)
|
||||
const newApiClient = new ApiClient(token || "", handleUnauthorized, showError)
|
||||
setApiClient(newApiClient)
|
||||
|
||||
// Reload data with new mode
|
||||
loadData()
|
||||
}
|
||||
|
||||
const sidebarItems = [
|
||||
{
|
||||
title: "Entities",
|
||||
icon: Table,
|
||||
id: "entities",
|
||||
path: "/entities",
|
||||
path: ROUTES.entities,
|
||||
},
|
||||
{
|
||||
title: "Logs",
|
||||
icon: FileText,
|
||||
id: "logs",
|
||||
path: "/logs",
|
||||
path: ROUTES.logs,
|
||||
},
|
||||
{
|
||||
title: "Admins",
|
||||
icon: Shield,
|
||||
id: "admins",
|
||||
path: "/admins",
|
||||
path: ROUTES.admins,
|
||||
},
|
||||
{
|
||||
title: "Settings",
|
||||
icon: Settings,
|
||||
id: "settings",
|
||||
path: "/settings",
|
||||
path: ROUTES.settings,
|
||||
},
|
||||
]
|
||||
|
||||
// Extract the section from the route path safely
|
||||
const getCurrentSection = () => {
|
||||
try {
|
||||
// Handle route patterns like "/entities/:name" -> "entities"
|
||||
const pathParts = route.path.split("/").filter(Boolean)
|
||||
return pathParts[0] || "entities"
|
||||
} catch (error) {
|
||||
console.warn("Error parsing route:", error)
|
||||
return "entities"
|
||||
}
|
||||
}
|
||||
|
||||
const currentSection = getCurrentSection()
|
||||
const currentSection = getDashboardSection(location.pathname)
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
@@ -291,13 +256,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<SidebarMenuButton
|
||||
onClick={() => {
|
||||
try {
|
||||
navigate(item.path, undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate:", error)
|
||||
}
|
||||
}}
|
||||
onClick={() => navigate(item.path)}
|
||||
isActive={currentSection === item.id}
|
||||
style={{ height: "4rem", minHeight: "4rem" }}
|
||||
className={cn(
|
||||
@@ -392,14 +351,7 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
|
||||
)}
|
||||
{currentSection === "logs" && <LogsSection apiClient={apiClient} />}
|
||||
{currentSection === "sync" && <SyncSection />}
|
||||
{currentSection === "settings" && (
|
||||
<SettingsSection
|
||||
apiClient={apiClient}
|
||||
settings={settings}
|
||||
onSettingsUpdate={setSettings}
|
||||
onModeChange={handleModeChange}
|
||||
/>
|
||||
)}
|
||||
{currentSection === "settings" && <SettingsSection apiClient={apiClient} />}
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { MoreHorizontal, Key, Trash2, Plus, RefreshCw } from "lucide-react"
|
||||
import { Key, MoreHorizontal, Plus, RefreshCw, Trash2 } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Dialog } from "@/components/ui/dialog"
|
||||
import { SYS_ADMINS_API, type ApiClient, type Admin, type TableMetadata } from "@/lib/api"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { SYS_ADMINS_API, SYS_API_KEYS_API, extractListItems, getApiClientError, type ApiClient, type Admin } from "@/lib/api"
|
||||
import { ChangePasswordDialog } from "./change-password-dialog"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { AddItemDrawer } from "../database/add-item-drawer"
|
||||
import { ApiKeysPanel, openCreateApiKeyDialog } from "../api-keys/api-keys-panel"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface AdminsSectionProps {
|
||||
@@ -24,8 +25,18 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
const [selectedAdmin, setSelectedAdmin] = React.useState<Admin | null>(null)
|
||||
const [addingAdmin, setAddingAdmin] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [activeTab, setActiveTab] = React.useState("accounts")
|
||||
const [createApiKeyForAdminId, setCreateApiKeyForAdminId] = React.useState<string | undefined>()
|
||||
const [createApiKeyRequested, setCreateApiKeyRequested] = React.useState(false)
|
||||
const [apiKeysReloadRequested, setApiKeysReloadRequested] = React.useState(0)
|
||||
const [apiKeysLoading, setApiKeysLoading] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
const adminUsers = React.useMemo(
|
||||
() => admins.map((admin) => ({ id: admin.id, label: admin.email })),
|
||||
[admins],
|
||||
)
|
||||
|
||||
const table: any = {
|
||||
has_api: true,
|
||||
name: "mb_admins",
|
||||
@@ -50,8 +61,8 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
validator: "@password",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "mbf_13735287961322938256",
|
||||
@@ -65,8 +76,8 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
validator: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "mbf_9124719522053273721",
|
||||
@@ -80,8 +91,8 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
validator: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "mbf_16339674465020246541",
|
||||
@@ -95,8 +106,8 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@email"
|
||||
}
|
||||
validator: "@email",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "mbf_6072375419398818283",
|
||||
@@ -110,61 +121,25 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
}
|
||||
}
|
||||
validator: "@password",
|
||||
},
|
||||
},
|
||||
],
|
||||
rules: {
|
||||
add: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
delete: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
get: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
list: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
},
|
||||
update: {
|
||||
expr: "",
|
||||
mode: "auth"
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const handleDeleteAdmin = async (adminId: string) => {
|
||||
try {
|
||||
const res: any = await apiClient.call(`${SYS_ADMINS_API}/${adminId}`, { method: "DELETE" })
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (res?.error?.length > 0) throw res.error
|
||||
|
||||
const response: any = await apiClient.call(SYS_ADMINS_API)
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (response?.error?.length > 0) throw response.error
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let updatedAdmins: Admin[] = []
|
||||
if (Array.isArray(response)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
updatedAdmins = response
|
||||
} else if (response?.items && Array.isArray(response.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
updatedAdmins = response.items
|
||||
} else if (response?.data?.items && Array.isArray(response.data.items)) {
|
||||
// If data is nested
|
||||
updatedAdmins = response.data.items
|
||||
}
|
||||
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
await apiClient.call(`${SYS_ADMINS_API}/${adminId}`, { method: "DELETE" })
|
||||
const response = await apiClient.call<unknown>(SYS_ADMINS_API)
|
||||
onAdminsUpdate(extractListItems<Admin>(response))
|
||||
|
||||
toast({
|
||||
title: "Admin Deleted",
|
||||
@@ -190,94 +165,151 @@ export function AdminsSection({ admins, apiClient, onAdminsUpdate }: AdminsSecti
|
||||
const handleReload = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const response: any = await apiClient.call(SYS_ADMINS_API)
|
||||
|
||||
// Handle paginated response structure: { items: [...], items_count, page, page_size, total_count }
|
||||
let updatedAdmins: Admin[] = []
|
||||
if (Array.isArray(response)) {
|
||||
// Fallback: if response is directly an array (shouldn't happen with new API)
|
||||
updatedAdmins = response
|
||||
} else if (response?.items && Array.isArray(response.items)) {
|
||||
// Paginated response: extract items from data object
|
||||
updatedAdmins = response.items
|
||||
} else if (response?.data?.items && Array.isArray(response.data.items)) {
|
||||
// If data is nested
|
||||
updatedAdmins = response.data.items
|
||||
const response = await apiClient.call<unknown>(SYS_ADMINS_API)
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
onAdminsUpdate(updatedAdmins)
|
||||
onAdminsUpdate(extractListItems<Admin>(response))
|
||||
} catch (error) {
|
||||
console.error("Failed to reload admins:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to reload admin accounts.",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateApiKeyForAdmin = (adminId: string) => {
|
||||
openCreateApiKeyDialog(setCreateApiKeyForAdminId, setCreateApiKeyRequested, adminId)
|
||||
setActiveTab("api-keys")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Admins</h1>
|
||||
<p className="text-muted-foreground">Manage administrator accounts</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
|
||||
<Button size="sm" onClick={() => setAddingAdmin(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Admins</h1>
|
||||
<p className="text-muted-foreground">Manage administrator accounts and API keys</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Administrator Accounts</CardTitle>
|
||||
<CardDescription>{admins.length} administrator accounts</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{Array.isArray(admins) && admins.map((admin) => (
|
||||
<TableRow key={admin.id}>
|
||||
<TableCell className="font-medium">{admin.email}</TableCell>
|
||||
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
|
||||
<TableCell>{new Date(admin.updated).toLocaleDateString()}</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setSelectedAdmin(admin)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Change Password
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteAdmin(admin.id)}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Remove Admin
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="accounts">Accounts</TabsTrigger>
|
||||
<TabsTrigger value="api-keys">API Keys</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{activeTab === "accounts" ? (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => setAddingAdmin(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Record
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setApiKeysReloadRequested((count) => count + 1)}
|
||||
disabled={apiKeysLoading}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${apiKeysLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => openCreateApiKeyDialog(setCreateApiKeyForAdminId, setCreateApiKeyRequested)}
|
||||
disabled={admins.length === 0}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New API Key
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TabsContent value="accounts" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Administrator Accounts</CardTitle>
|
||||
<CardDescription>{admins.length} administrator accounts</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{Array.isArray(admins) &&
|
||||
admins.map((admin) => (
|
||||
<TableRow key={admin.id}>
|
||||
<TableCell className="font-medium">{admin.email}</TableCell>
|
||||
<TableCell>{new Date(admin.created).toLocaleDateString()}</TableCell>
|
||||
<TableCell>{new Date(admin.updated).toLocaleDateString()}</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setSelectedAdmin(admin)}>
|
||||
<Key className="mr-2 h-4 w-4" />
|
||||
Change Password
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleCreateApiKeyForAdmin(admin.id)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create API Key
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteAdmin(admin.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Remove Admin
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api-keys" className="space-y-6">
|
||||
<ApiKeysPanel
|
||||
users={adminUsers}
|
||||
apiClient={apiClient}
|
||||
apiKeysApi={SYS_API_KEYS_API}
|
||||
cacheKey="mantis-admin-api-keys"
|
||||
isActive={activeTab === "api-keys"}
|
||||
defaultUserId={createApiKeyForAdminId}
|
||||
createRequested={createApiKeyRequested}
|
||||
reloadRequested={apiKeysReloadRequested}
|
||||
onCreateRequestHandled={() => setCreateApiKeyRequested(false)}
|
||||
onLoadingChange={setApiKeysLoading}
|
||||
panelTitle="Admin API Keys"
|
||||
userColumnLabel="Admin"
|
||||
createDialogTitle="Create API Key"
|
||||
createDialogDescription="Create a new API key linked to an admin account."
|
||||
userFieldLabel="Admin Account"
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<Dialog open={!!selectedAdmin} onOpenChange={() => setSelectedAdmin(null)}>
|
||||
{selectedAdmin && (
|
||||
|
||||
72
components/api-keys/api-key-secret-dialog.tsx
Normal file
72
components/api-keys/api-key-secret-dialog.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Check, Copy } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
|
||||
interface ApiKeySecretDialogProps {
|
||||
open: boolean
|
||||
label: string
|
||||
secret: string
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function ApiKeySecretDialog({ open, label, secret, onClose }: ApiKeySecretDialogProps) {
|
||||
const [copied, setCopied] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
setCopied(false)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(secret)
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 2000)
|
||||
} catch (error) {
|
||||
console.error("Failed to copy API key:", error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>API Key Created</DialogTitle>
|
||||
<DialogDescription>
|
||||
Copy the key for <span className="font-medium text-foreground">{label}</span> now. It will not be shown again.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
Store this key securely. You will not be able to view it again after closing this dialog.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input readOnly value={secret} className="font-mono text-sm" />
|
||||
<Button type="button" variant="outline" size="icon" onClick={handleCopy} aria-label="Copy API key">
|
||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button onClick={onClose}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
401
components/api-keys/api-keys-panel.tsx
Normal file
401
components/api-keys/api-keys-panel.tsx
Normal file
@@ -0,0 +1,401 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { MoreHorizontal, Pencil, Trash2 } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import {
|
||||
extractListItems,
|
||||
getApiClientError,
|
||||
type AdminApiKey,
|
||||
type AdminApiKeyCreated,
|
||||
type ApiClient,
|
||||
type ApiKeyUser,
|
||||
} from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { ApiKeySecretDialog } from "./api-key-secret-dialog"
|
||||
import { CreateApiKeyDialog } from "./create-api-key-dialog"
|
||||
import { EditApiKeyDialog } from "./edit-api-key-dialog"
|
||||
|
||||
interface ApiKeysPanelProps {
|
||||
users: ApiKeyUser[]
|
||||
apiClient: ApiClient
|
||||
apiKeysApi: string
|
||||
cacheKey: string
|
||||
isActive: boolean
|
||||
defaultUserId?: string
|
||||
createRequested?: boolean
|
||||
reloadRequested?: number
|
||||
supportsEdit?: boolean
|
||||
panelTitle?: string
|
||||
userColumnLabel?: string
|
||||
createDialogTitle?: string
|
||||
createDialogDescription?: string
|
||||
userFieldLabel?: string
|
||||
onCreateRequestHandled?: () => void
|
||||
onLoadingChange?: (loading: boolean) => void
|
||||
}
|
||||
|
||||
function formatDate(value: string | null): string {
|
||||
if (!value) {
|
||||
return "Never"
|
||||
}
|
||||
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return value
|
||||
}
|
||||
|
||||
return date.toLocaleString()
|
||||
}
|
||||
|
||||
function getUserLabel(users: ApiKeyUser[], userId: string): string {
|
||||
return users.find((user) => user.id === userId)?.label ?? userId
|
||||
}
|
||||
|
||||
function toCachedApiKey(key: AdminApiKey | AdminApiKeyCreated): AdminApiKey {
|
||||
const { key: _secret, ...metadata } = key as AdminApiKeyCreated
|
||||
return metadata
|
||||
}
|
||||
|
||||
function readCachedApiKeys(cacheKey: string): AdminApiKey[] {
|
||||
if (typeof window === "undefined") {
|
||||
return []
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = sessionStorage.getItem(cacheKey)
|
||||
if (!raw) {
|
||||
return []
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw)
|
||||
return extractListItems<AdminApiKey>(parsed)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeCachedApiKeys(cacheKey: string, keys: AdminApiKey[]): void {
|
||||
if (typeof window === "undefined") {
|
||||
return
|
||||
}
|
||||
|
||||
sessionStorage.setItem(cacheKey, JSON.stringify(keys))
|
||||
}
|
||||
|
||||
function mergeApiKeys(fetched: AdminApiKey[], cached: AdminApiKey[]): AdminApiKey[] {
|
||||
if (fetched.length > 0) {
|
||||
return fetched
|
||||
}
|
||||
|
||||
return cached
|
||||
}
|
||||
|
||||
export function ApiKeysPanel({
|
||||
users,
|
||||
apiClient,
|
||||
apiKeysApi,
|
||||
cacheKey,
|
||||
isActive,
|
||||
defaultUserId,
|
||||
createRequested,
|
||||
reloadRequested = 0,
|
||||
supportsEdit = true,
|
||||
panelTitle = "API Keys",
|
||||
userColumnLabel = "User",
|
||||
createDialogTitle,
|
||||
createDialogDescription,
|
||||
userFieldLabel,
|
||||
onCreateRequestHandled,
|
||||
onLoadingChange,
|
||||
}: ApiKeysPanelProps) {
|
||||
const { toast } = useToast()
|
||||
const [apiKeys, setApiKeys] = React.useState<AdminApiKey[]>(() => readCachedApiKeys(cacheKey))
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [creating, setCreating] = React.useState(false)
|
||||
const [selectedUserId, setSelectedUserId] = React.useState<string | undefined>()
|
||||
const [editingKey, setEditingKey] = React.useState<AdminApiKey | null>(null)
|
||||
const [deletingKey, setDeletingKey] = React.useState<AdminApiKey | null>(null)
|
||||
const [createdSecret, setCreatedSecret] = React.useState<{ label: string; secret: string } | null>(null)
|
||||
const hasLoadedRef = React.useRef(false)
|
||||
|
||||
const persistApiKeys = React.useCallback(
|
||||
(keys: AdminApiKey[]) => {
|
||||
setApiKeys(keys)
|
||||
writeCachedApiKeys(cacheKey, keys)
|
||||
},
|
||||
[cacheKey],
|
||||
)
|
||||
|
||||
const loadApiKeys = React.useCallback(async () => {
|
||||
const cached = readCachedApiKeys(cacheKey)
|
||||
|
||||
try {
|
||||
setIsLoading(true)
|
||||
onLoadingChange?.(true)
|
||||
|
||||
const response = await apiClient.call<unknown>(apiKeysApi)
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
const fetched = extractListItems<AdminApiKey>(response)
|
||||
const merged = mergeApiKeys(fetched, cached)
|
||||
persistApiKeys(merged)
|
||||
hasLoadedRef.current = true
|
||||
} catch (error) {
|
||||
console.error("Failed to load API keys:", error)
|
||||
|
||||
if (cached.length > 0) {
|
||||
setApiKeys(cached)
|
||||
}
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: hasLoadedRef.current
|
||||
? "Failed to refresh API keys."
|
||||
: cached.length > 0
|
||||
? "Could not refresh API keys from the server. Showing cached keys from this browser session."
|
||||
: "Failed to load API keys.",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
onLoadingChange?.(false)
|
||||
}
|
||||
}, [apiClient, apiKeysApi, cacheKey, onLoadingChange, persistApiKeys, toast])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isActive) {
|
||||
loadApiKeys()
|
||||
}
|
||||
}, [isActive, loadApiKeys])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isActive && reloadRequested > 0) {
|
||||
loadApiKeys()
|
||||
}
|
||||
}, [isActive, reloadRequested, loadApiKeys])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (createRequested) {
|
||||
setSelectedUserId(defaultUserId)
|
||||
setCreating(true)
|
||||
onCreateRequestHandled?.()
|
||||
}
|
||||
}, [createRequested, defaultUserId, onCreateRequestHandled])
|
||||
|
||||
const handleCreated = (created: AdminApiKeyCreated) => {
|
||||
const metadata = toCachedApiKey(created)
|
||||
setApiKeys((current) => {
|
||||
const next = [metadata, ...current.filter((key) => key.id !== metadata.id)]
|
||||
writeCachedApiKeys(cacheKey, next)
|
||||
return next
|
||||
})
|
||||
setCreatedSecret({ label: created.label, secret: created.key })
|
||||
toast({
|
||||
title: "API Key Created",
|
||||
description: "Copy the key now. It will not be shown again.",
|
||||
})
|
||||
}
|
||||
|
||||
const handleUpdated = (updated: AdminApiKey) => {
|
||||
setApiKeys((current) => {
|
||||
const next = current.map((key) => (key.id === updated.id ? updated : key))
|
||||
writeCachedApiKeys(cacheKey, next)
|
||||
return next
|
||||
})
|
||||
toast({
|
||||
title: "API Key Updated",
|
||||
description: "API key settings were saved.",
|
||||
})
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deletingKey) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.call(`${apiKeysApi}/${deletingKey.id}`, { method: "DELETE" })
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
setApiKeys((current) => {
|
||||
const next = current.filter((key) => key.id !== deletingKey.id)
|
||||
writeCachedApiKeys(cacheKey, next)
|
||||
return next
|
||||
})
|
||||
toast({
|
||||
title: "API Key Revoked",
|
||||
description: `"${deletingKey.label}" has been deleted.`,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to delete API key:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to delete API key.",
|
||||
})
|
||||
} finally {
|
||||
setDeletingKey(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{panelTitle}</CardTitle>
|
||||
<CardDescription>
|
||||
{isLoading && apiKeys.length === 0
|
||||
? "Loading API keys..."
|
||||
: `${apiKeys.length} API key${apiKeys.length === 1 ? "" : "s"}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Label</TableHead>
|
||||
<TableHead>{userColumnLabel}</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead>Last Used</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading && apiKeys.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center text-muted-foreground">
|
||||
Loading API keys...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : apiKeys.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center text-muted-foreground">
|
||||
No API keys yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
apiKeys.map((apiKey) => (
|
||||
<TableRow key={apiKey.id}>
|
||||
<TableCell className="font-medium">{apiKey.label}</TableCell>
|
||||
<TableCell>{getUserLabel(users, apiKey.user_id)}</TableCell>
|
||||
<TableCell>{formatDate(apiKey.created)}</TableCell>
|
||||
<TableCell>{formatDate(apiKey.last_used)}</TableCell>
|
||||
<TableCell>{apiKey.expires_at ? formatDate(apiKey.expires_at) : "Never"}</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{supportsEdit && (
|
||||
<DropdownMenuItem onClick={() => setEditingKey(apiKey)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => setDeletingKey(apiKey)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<CreateApiKeyDialog
|
||||
open={creating}
|
||||
users={users}
|
||||
apiClient={apiClient}
|
||||
apiKeysApi={apiKeysApi}
|
||||
defaultUserId={selectedUserId}
|
||||
userFieldLabel={userFieldLabel ?? userColumnLabel}
|
||||
title={createDialogTitle}
|
||||
description={createDialogDescription}
|
||||
onClose={() => setCreating(false)}
|
||||
onCreated={handleCreated}
|
||||
/>
|
||||
|
||||
{supportsEdit && (
|
||||
<EditApiKeyDialog
|
||||
open={!!editingKey}
|
||||
apiKey={editingKey}
|
||||
apiClient={apiClient}
|
||||
apiKeysApi={apiKeysApi}
|
||||
onClose={() => setEditingKey(null)}
|
||||
onUpdated={handleUpdated}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ApiKeySecretDialog
|
||||
open={!!createdSecret}
|
||||
label={createdSecret?.label ?? ""}
|
||||
secret={createdSecret?.secret ?? ""}
|
||||
onClose={() => setCreatedSecret(null)}
|
||||
/>
|
||||
|
||||
<AlertDialog open={!!deletingKey} onOpenChange={(open) => !open && setDeletingKey(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete API Key</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Revoke <span className="font-medium text-foreground">{deletingKey?.label}</span>? This action cannot be
|
||||
undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function openCreateApiKeyDialog(
|
||||
setDefaultUserId: (userId: string | undefined) => void,
|
||||
setCreateRequested: (requested: boolean) => void,
|
||||
userId?: string,
|
||||
) {
|
||||
setDefaultUserId(userId)
|
||||
setCreateRequested(true)
|
||||
}
|
||||
179
components/api-keys/create-api-key-dialog.tsx
Normal file
179
components/api-keys/create-api-key-dialog.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import {
|
||||
getApiClientError,
|
||||
type AdminApiKeyCreated,
|
||||
type ApiClient,
|
||||
type ApiKeyUser,
|
||||
} from "@/lib/api"
|
||||
|
||||
interface CreateApiKeyDialogProps {
|
||||
open: boolean
|
||||
users: ApiKeyUser[]
|
||||
apiClient: ApiClient
|
||||
apiKeysApi: string
|
||||
defaultUserId?: string
|
||||
userFieldLabel?: string
|
||||
title?: string
|
||||
description?: string
|
||||
onClose: () => void
|
||||
onCreated: (created: AdminApiKeyCreated) => void
|
||||
}
|
||||
|
||||
export function CreateApiKeyDialog({
|
||||
open,
|
||||
users,
|
||||
apiClient,
|
||||
apiKeysApi,
|
||||
defaultUserId,
|
||||
userFieldLabel = "User",
|
||||
title = "Create API Key",
|
||||
description = "Create a new API key linked to a user account.",
|
||||
onClose,
|
||||
onCreated,
|
||||
}: CreateApiKeyDialogProps) {
|
||||
const [userId, setUserId] = React.useState(defaultUserId ?? "")
|
||||
const [label, setLabel] = React.useState(`api-key-${Date.now()}`)
|
||||
const [expiresAt, setExpiresAt] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setUserId(defaultUserId ?? users[0]?.id ?? "")
|
||||
setLabel(`api-key-${Date.now()}`)
|
||||
setExpiresAt("")
|
||||
setError("")
|
||||
}
|
||||
}, [open, defaultUserId, users])
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
|
||||
if (!userId) {
|
||||
setError(`Select a ${userFieldLabel.toLowerCase()} for this API key`)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
user_id: userId,
|
||||
label: label.trim() || "API Key",
|
||||
}
|
||||
|
||||
if (expiresAt) {
|
||||
body.expires_at = new Date(expiresAt).toISOString()
|
||||
}
|
||||
|
||||
const created = await apiClient.call<AdminApiKeyCreated>(apiKeysApi, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
const apiError = getApiClientError(created)
|
||||
if (apiError) {
|
||||
throw new Error(apiError)
|
||||
}
|
||||
|
||||
if (!created?.key) {
|
||||
throw new Error("API key was created but the secret was not returned")
|
||||
}
|
||||
|
||||
onCreated({ ...created, user_id: created.user_id ?? userId })
|
||||
onClose()
|
||||
} catch (submitError) {
|
||||
console.error("Failed to create API key:", submitError)
|
||||
setError(submitError instanceof Error ? submitError.message : "Failed to create API key")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="api-key-user">{userFieldLabel}</Label>
|
||||
<Select value={userId} onValueChange={setUserId}>
|
||||
<SelectTrigger id="api-key-user">
|
||||
<SelectValue placeholder={`Select ${userFieldLabel.toLowerCase()}`} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{users.map((user) => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="api-key-label">Label</Label>
|
||||
<Input
|
||||
id="api-key-label"
|
||||
value={label}
|
||||
onChange={(event) => setLabel(event.target.value)}
|
||||
placeholder="Production automation"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="api-key-expires">Expires At (optional)</Label>
|
||||
<Input
|
||||
id="api-key-expires"
|
||||
type="datetime-local"
|
||||
value={expiresAt}
|
||||
onChange={(event) => setExpiresAt(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading || users.length === 0}>
|
||||
{isLoading ? "Creating..." : "Create API Key"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
139
components/api-keys/edit-api-key-dialog.tsx
Normal file
139
components/api-keys/edit-api-key-dialog.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { type AdminApiKey, type ApiClient } from "@/lib/api"
|
||||
|
||||
interface EditApiKeyDialogProps {
|
||||
open: boolean
|
||||
apiKey: AdminApiKey | null
|
||||
apiClient: ApiClient
|
||||
apiKeysApi: string
|
||||
onClose: () => void
|
||||
onUpdated: (updated: AdminApiKey) => void
|
||||
}
|
||||
|
||||
function toDateTimeLocalValue(value: string | null): string {
|
||||
if (!value) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const offset = date.getTimezoneOffset()
|
||||
const local = new Date(date.getTime() - offset * 60_000)
|
||||
return local.toISOString().slice(0, 16)
|
||||
}
|
||||
|
||||
export function EditApiKeyDialog({
|
||||
open,
|
||||
apiKey,
|
||||
apiClient,
|
||||
apiKeysApi,
|
||||
onClose,
|
||||
onUpdated,
|
||||
}: EditApiKeyDialogProps) {
|
||||
const [label, setLabel] = React.useState("")
|
||||
const [expiresAt, setExpiresAt] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && apiKey) {
|
||||
setLabel(apiKey.label)
|
||||
setExpiresAt(toDateTimeLocalValue(apiKey.expires_at))
|
||||
setError("")
|
||||
}
|
||||
}, [open, apiKey])
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (!apiKey) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const updated = await apiClient.call<AdminApiKey>(`${apiKeysApi}/${apiKey.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({
|
||||
label: label.trim() || "API Key",
|
||||
expires_at: expiresAt ? new Date(expiresAt).toISOString() : "",
|
||||
}),
|
||||
})
|
||||
|
||||
onUpdated(updated)
|
||||
onClose()
|
||||
} catch (submitError) {
|
||||
console.error("Failed to update API key:", submitError)
|
||||
setError(submitError instanceof Error ? submitError.message : "Failed to update API key")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit API Key</DialogTitle>
|
||||
<DialogDescription>Update the label or expiration for this API key.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-api-key-label">Label</Label>
|
||||
<Input
|
||||
id="edit-api-key-label"
|
||||
value={label}
|
||||
onChange={(event) => setLabel(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-api-key-expires">Expires At</Label>
|
||||
<Input
|
||||
id="edit-api-key-expires"
|
||||
type="datetime-local"
|
||||
value={expiresAt}
|
||||
onChange={(event) => setExpiresAt(event.target.value)}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">Leave blank for no expiration.</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
157
components/app-routes.tsx
Normal file
157
components/app-routes.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertTriangle } from "lucide-react"
|
||||
import {
|
||||
BrowserRouter,
|
||||
Navigate,
|
||||
Outlet,
|
||||
Route,
|
||||
Routes,
|
||||
useNavigate,
|
||||
useSearchParams,
|
||||
} from "react-router-dom"
|
||||
import { LoginForm } from "@/components/login-form"
|
||||
import { SetupForm } from "@/components/setup-form"
|
||||
import { AdminDashboard } from "@/components/admin-dashboard"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
|
||||
import { Logo } from "@/components/logo"
|
||||
import { AuthProvider, useAuth } from "@/lib/auth"
|
||||
import { getBasePath, ROUTES } from "@/lib/routes"
|
||||
|
||||
function LoadingScreen({ message = "Loading..." }: { message?: string }) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
|
||||
<p className="text-muted-foreground">{message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RequireAuth() {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingScreen />
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to={ROUTES.login} replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
function GuestOnly() {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingScreen />
|
||||
}
|
||||
|
||||
if (isAuthenticated) {
|
||||
return <Navigate to={ROUTES.entities} replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
function LoginRoute() {
|
||||
const { login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<LoginForm
|
||||
onLogin={async (email, password) => {
|
||||
await login(email, password)
|
||||
navigate(ROUTES.entities, { replace: true })
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SetupRoute() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const navigate = useNavigate()
|
||||
const setupToken = searchParams.get("token")
|
||||
|
||||
if (!setupToken) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mb-4 flex justify-center">
|
||||
<Logo className="h-12 w-12 text-primary" size={48} />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Setup Access Required</CardTitle>
|
||||
<CardDescription>An access token is required to access the setup page</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Missing Access Token</AlertTitle>
|
||||
<AlertDescription>
|
||||
This page requires an access token in the query string (e.g. /setup?token=your-token-here).
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SetupForm
|
||||
token={setupToken}
|
||||
onSetupComplete={() => navigate(ROUTES.login, { replace: true })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AppRoutesInner() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path={ROUTES.setup} element={<SetupRoute />} />
|
||||
|
||||
<Route element={<GuestOnly />}>
|
||||
<Route path={ROUTES.login} element={<LoginRoute />} />
|
||||
</Route>
|
||||
|
||||
<Route element={<RequireAuth />}>
|
||||
<Route path={ROUTES.home} element={<Navigate to={ROUTES.entities} replace />} />
|
||||
<Route path={ROUTES.entities} element={<AdminDashboard />} />
|
||||
<Route path={ROUTES.entityDetail} element={<AdminDashboard />} />
|
||||
<Route path={ROUTES.logs} element={<AdminDashboard />} />
|
||||
<Route path={ROUTES.admins} element={<AdminDashboard />} />
|
||||
<Route path={ROUTES.settings} element={<AdminDashboard />} />
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to={ROUTES.entities} replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
export function AppRouterProvider({ children }: { children: React.ReactNode }) {
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
|
||||
if (!mounted) {
|
||||
return <LoadingScreen />
|
||||
}
|
||||
|
||||
return (
|
||||
<BrowserRouter basename={getBasePath()}>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
export function AppRoutes() {
|
||||
return <AppRoutesInner />
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import type { ApiClient, TableMetadata, TableField } from "@/lib/api"
|
||||
import { isNumericFieldType } from "@/lib/field-types"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
@@ -161,8 +162,10 @@ export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, on
|
||||
switch (type) {
|
||||
case "string":
|
||||
case "xml":
|
||||
case "blob":
|
||||
return String(value);
|
||||
|
||||
case "int":
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
@@ -227,23 +230,7 @@ export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, on
|
||||
}
|
||||
}
|
||||
|
||||
const isIntegralType = (type: string) => {
|
||||
switch (type) {
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
case "int64":
|
||||
case "uint8":
|
||||
case "uint16":
|
||||
case "uint32":
|
||||
case "uint64":
|
||||
case "double":
|
||||
return true
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
const isIntegralType = (type: string) => isNumericFieldType(type)
|
||||
|
||||
function formatDateForInput(value: string | Date | number | undefined): string {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
|
||||
@@ -23,7 +23,12 @@ import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import type { ApiClient, TableMetadata, TableField, ForeignKeyConfig } from "@/lib/api"
|
||||
import { dataTypes } from "@/lib/constants"
|
||||
import { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/constants"
|
||||
import {
|
||||
appendPrecisionToFieldPayload,
|
||||
applyFieldTypeChange,
|
||||
normalizeFieldTypeForEditor,
|
||||
} from "@/lib/field-types"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatConstraintDefaultForInput, normalizeConstraintsForFieldType } from "@/lib/schema-constraints"
|
||||
@@ -44,6 +49,7 @@ interface Field {
|
||||
id?: string // Optional - missing/empty means new field
|
||||
name: string
|
||||
type: string
|
||||
precision?: string | null
|
||||
primary_key: boolean
|
||||
nullable: boolean
|
||||
unique?: boolean
|
||||
@@ -59,10 +65,12 @@ interface Field {
|
||||
}
|
||||
|
||||
function tableFieldToField(tf: TableField): Field {
|
||||
const normalized = normalizeFieldTypeForEditor(tf)
|
||||
return {
|
||||
id: tf.id,
|
||||
name: tf.name,
|
||||
type: tf.type,
|
||||
type: normalized.type,
|
||||
precision: normalized.precision,
|
||||
primary_key: tf.primary_key,
|
||||
nullable: !tf.required,
|
||||
unique: tf.unique ?? false,
|
||||
@@ -242,9 +250,10 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
const addField = () => {
|
||||
setFields([
|
||||
...fields,
|
||||
{
|
||||
{
|
||||
name: "",
|
||||
type: "string",
|
||||
precision: null,
|
||||
primary_key: false,
|
||||
nullable: true,
|
||||
system: false,
|
||||
@@ -280,18 +289,26 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
setFields((prevFields) =>
|
||||
prevFields.map((field, index) => {
|
||||
const currentKey = field.id || `temp-${index}`
|
||||
if (currentKey === fieldKey) {
|
||||
// Handle constraints updates
|
||||
if (updates.constraints) {
|
||||
return {
|
||||
...field,
|
||||
...updates,
|
||||
constraints: { ...field.constraints, ...updates.constraints }
|
||||
}
|
||||
}
|
||||
return { ...field, ...updates }
|
||||
if (currentKey !== fieldKey) {
|
||||
return field
|
||||
}
|
||||
return field
|
||||
|
||||
let nextField = { ...field, ...updates }
|
||||
if (updates.type !== undefined) {
|
||||
const typeUpdate = applyFieldTypeChange(field.type, updates.type, field.precision)
|
||||
nextField = {
|
||||
...nextField,
|
||||
type: typeUpdate.type,
|
||||
precision: typeUpdate.precision,
|
||||
}
|
||||
}
|
||||
if (updates.constraints) {
|
||||
nextField = {
|
||||
...nextField,
|
||||
constraints: { ...field.constraints, ...updates.constraints },
|
||||
}
|
||||
}
|
||||
return nextField
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -377,6 +394,15 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if (field.type === "int" && !field.precision) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: `Field "${field.name || 'unnamed'}" must have an integer precision selected.`,
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,7 +416,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
return field.name.trim() && field.type && field.type.trim()
|
||||
})
|
||||
for (const field of candidateFields) {
|
||||
const normalized = normalizeConstraintsForFieldType(field.type, field.constraints)
|
||||
const normalized = normalizeConstraintsForFieldType(field.type, field.constraints, field.precision)
|
||||
if (!normalized.ok) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
@@ -409,6 +435,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
system: field.system || false,
|
||||
constraints: normalized.constraints,
|
||||
}
|
||||
appendPrecisionToFieldPayload(fieldData, field)
|
||||
if (field.id && field.id.startsWith("mbf_")) {
|
||||
fieldData.id = field.id
|
||||
}
|
||||
@@ -600,7 +627,7 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
className={field.system ? "bg-muted" : ""}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className={field.type === "int" ? "grid grid-cols-2 gap-2" : ""}>
|
||||
<Select
|
||||
value={field.type}
|
||||
onValueChange={(value) => updateField(fieldKey, { type: value })}
|
||||
@@ -617,6 +644,24 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{field.type === "int" && (
|
||||
<Select
|
||||
value={field.precision ?? DEFAULT_INT_PRECISION}
|
||||
onValueChange={(value) => updateField(fieldKey, { precision: value })}
|
||||
disabled={field.system}
|
||||
>
|
||||
<SelectTrigger className={field.system ? "bg-muted" : ""}>
|
||||
<SelectValue placeholder="Precision" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{intPrecisions.map((precision) => (
|
||||
<SelectItem key={precision} value={precision}>
|
||||
{precision}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!field.system && (
|
||||
|
||||
145
components/database/api-doc-shared.tsx
Normal file
145
components/database/api-doc-shared.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { ChevronDown, ChevronRight, Copy } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
|
||||
export function getMethodColor(method: string): string {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
|
||||
case "POST":
|
||||
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
|
||||
case "PATCH":
|
||||
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
|
||||
case "DELETE":
|
||||
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
|
||||
}
|
||||
}
|
||||
|
||||
export function copyToClipboard(text: string): void {
|
||||
navigator.clipboard.writeText(text)
|
||||
}
|
||||
|
||||
export function DocCodeBlock({
|
||||
code,
|
||||
height = "h-48",
|
||||
}: {
|
||||
code: string
|
||||
height?: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(code)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className={height}>
|
||||
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocCollapsibleSection({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
defaultOpen = false,
|
||||
children,
|
||||
}: {
|
||||
title: React.ReactNode
|
||||
description?: string
|
||||
icon?: React.ReactNode
|
||||
defaultOpen?: boolean
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(defaultOpen)
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
{icon}
|
||||
<span className="font-medium">{title}</span>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
{description && <p className="text-sm text-muted-foreground mt-2">{description}</p>}
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">{children}</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocEndpointHeader({
|
||||
method,
|
||||
endpoint,
|
||||
description,
|
||||
isOpen,
|
||||
}: {
|
||||
method: string
|
||||
endpoint: string
|
||||
description: string
|
||||
isOpen: boolean
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge className={getMethodColor(method)} variant="secondary">
|
||||
{method}
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">{description}</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocErrorList({ errors }: { errors: Array<{ code: string; message: string }> }) {
|
||||
return (
|
||||
<div>
|
||||
<h5 className="font-medium mb-3">Possible Errors</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
|
||||
{errors.map((error) => (
|
||||
<div key={error.code} className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{error.code}
|
||||
</Badge>
|
||||
<span>{error.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocSectionHeading({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="pt-2">
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">{children}</h3>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocInfoBanner({ children }: { children: React.ReactNode }) {
|
||||
return <div className="rounded-lg border bg-muted/30 p-4">{children}</div>
|
||||
}
|
||||
@@ -33,10 +33,12 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import type { ApiClient, TableMetadata } from "@/lib/api"
|
||||
import { applySchemaListMigration } from "@/lib/schema-migration"
|
||||
import { AddTableDialog } from "./add-table-dialog"
|
||||
import { TableDetailView } from "./table-detail-view"
|
||||
import { TableDocsDrawer } from "./table-docs-drawer"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom"
|
||||
import { entityDetailPath, ROUTES } from "@/lib/routes"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
@@ -47,11 +49,12 @@ interface DatabaseSectionProps {
|
||||
}
|
||||
|
||||
export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseSectionProps) {
|
||||
const { route, navigate } = useRouter()
|
||||
const { name: entityNameParam } = useParams<{ name?: string }>()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const navigate = useNavigate()
|
||||
const { toast } = useToast()
|
||||
|
||||
// Initialize search term from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const initialFilter = searchParams.get("filter") || ""
|
||||
const [searchTerm, setSearchTerm] = React.useState(initialFilter)
|
||||
const [editingTable, setEditingTable] = React.useState<TableMetadata | null>(null)
|
||||
const [searchExpanded, setSearchExpanded] = React.useState(false)
|
||||
@@ -73,30 +76,32 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
|
||||
// Sync search term with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
const filterFromQuery = searchParams.get("filter") || ""
|
||||
if (filterFromQuery !== searchTerm) {
|
||||
setSearchTerm(filterFromQuery)
|
||||
}
|
||||
}, [route.queryParams.filter])
|
||||
}, [searchParams])
|
||||
|
||||
// Update URL when search term changes (debounced)
|
||||
React.useEffect(() => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (route.path === "/entities" || route.path === "/entities/:name") {
|
||||
const queryParams: Record<string, string> = searchTerm ? { filter: searchTerm } : {}
|
||||
if (route.pathParams.name) {
|
||||
navigate("/entities/:name", { name: route.pathParams.name }, queryParams)
|
||||
} else {
|
||||
navigate("/entities", undefined, queryParams)
|
||||
}
|
||||
const nextParams = new URLSearchParams(searchParams)
|
||||
if (searchTerm) {
|
||||
nextParams.set("filter", searchTerm)
|
||||
} else {
|
||||
nextParams.delete("filter")
|
||||
}
|
||||
}, 300) // Debounce for 300ms
|
||||
|
||||
if (nextParams.toString() !== searchParams.toString()) {
|
||||
setSearchParams(nextParams, { replace: true })
|
||||
}
|
||||
}, 300)
|
||||
|
||||
return () => clearTimeout(timeoutId)
|
||||
}, [searchTerm, route.path, route.pathParams.name])
|
||||
}, [searchTerm, searchParams, setSearchParams])
|
||||
|
||||
// Get selected entity name from path params
|
||||
const selectedEntityName = route.pathParams.name || null
|
||||
// Get selected entity name from route params
|
||||
const selectedEntityName = entityNameParam || null
|
||||
|
||||
const filteredTables = Array.isArray(tables) ? tables?.filter((table) => table?.schema?.name?.toLowerCase().includes(searchTerm.toLowerCase())) : []
|
||||
|
||||
@@ -115,7 +120,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
onTablesUpdate(updatedTables)
|
||||
onTablesUpdate(await applySchemaListMigration(apiClient, updatedTables))
|
||||
setDeleteTable(null)
|
||||
toast({
|
||||
title: "Entity deleted",
|
||||
@@ -159,7 +164,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
} else if (response?.data && Array.isArray(response.data)) {
|
||||
updatedTables = response.data
|
||||
}
|
||||
onTablesUpdate(updatedTables)
|
||||
onTablesUpdate(await applySchemaListMigration(apiClient, updatedTables))
|
||||
setRenameTable(null)
|
||||
setRenameNewName("")
|
||||
toast({
|
||||
@@ -179,11 +184,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
}
|
||||
|
||||
const handleEntityClick = (entityName: string) => {
|
||||
try {
|
||||
navigate("/entities/:name", { name: entityName })
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate to entity:", error)
|
||||
}
|
||||
navigate(entityDetailPath(entityName))
|
||||
}
|
||||
|
||||
const handleRefresh = async () => {
|
||||
@@ -202,7 +203,8 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
updatedTables = response.data
|
||||
}
|
||||
|
||||
onTablesUpdate(updatedTables)
|
||||
const migratedTables = await applySchemaListMigration(apiClient, updatedTables)
|
||||
onTablesUpdate(migratedTables)
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh tables:", error)
|
||||
} finally {
|
||||
@@ -342,13 +344,7 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
|
||||
{selectedEntity ? (
|
||||
<TableDetailView
|
||||
table={selectedEntity}
|
||||
onBack={() => {
|
||||
try {
|
||||
navigate("/entities", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate back:", error)
|
||||
}
|
||||
}}
|
||||
onBack={() => navigate(ROUTES.entities)}
|
||||
apiClient={apiClient}
|
||||
onTableUpdate={(updatedTable) => {
|
||||
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))
|
||||
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
} from "@/components/ui/drawer"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { ApiClient, TableMetadata, getApiBaseUrl, TableField } from "@/lib/api"
|
||||
import { ApiClient, TableMetadata, TableField, buildEntityFileUrl } from "@/lib/api"
|
||||
import { formatFieldTypeDisplay, isNumericFieldType } from "@/lib/field-types"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
@@ -57,7 +58,7 @@ const FilePreviewField = ({
|
||||
|
||||
const getFileUrl = (file: File | string): string => {
|
||||
if (typeof file === "string") {
|
||||
return `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(file)}`;
|
||||
return buildEntityFileUrl(table.schema.name, file);
|
||||
}
|
||||
return URL.createObjectURL(file); // for newly selected files
|
||||
};
|
||||
@@ -273,6 +274,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
|
||||
try {
|
||||
switch (type) {
|
||||
case "int":
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
@@ -449,7 +451,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
/>
|
||||
) : field.type.match(/^int|^uint|double|number$/) ? (
|
||||
) : isNumericFieldType(field.type) ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="number"
|
||||
@@ -457,7 +459,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.type}' value`}
|
||||
placeholder={`Enter '${formatFieldTypeDisplay(field)}' value`}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
|
||||
@@ -32,9 +32,18 @@ import { Textarea } from "@/components/ui/textarea"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import type { ApiClient, TableMetadata, ForeignKeyConfig } from "@/lib/api"
|
||||
import { dataTypes } from "@/lib/constants"
|
||||
import { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/constants"
|
||||
import {
|
||||
appendPrecisionToFieldPayload,
|
||||
applyFieldTypeChange,
|
||||
normalizeFieldTypeForEditor,
|
||||
schemaFieldsNeedMigration,
|
||||
} from "@/lib/field-types"
|
||||
import { migrateSchemaFieldsIfNeeded } from "@/lib/schema-migration"
|
||||
import { OAuthEntityPanel } from "@/components/oauth/oauth-entity-panel"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { ROUTES } from "@/lib/routes"
|
||||
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
@@ -89,7 +98,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
const { toast } = useToast()
|
||||
const { navigate } = useRouter()
|
||||
const navigate = useNavigate()
|
||||
const isAuthEntity = table.schema.type === "auth"
|
||||
|
||||
// Get unique key for field (use id if exists, otherwise generate one)
|
||||
const getFieldKey = (field: any, index: number) => field.id || `temp-${index}`
|
||||
@@ -97,18 +107,23 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
// Transform API format (with constraints) to UI format (flat camelCase)
|
||||
const transformedColumns = table.schema?.fields.map(col => ({
|
||||
...col,
|
||||
old_name: col.name,
|
||||
// Flatten constraints for UI
|
||||
primaryKey: col.primary_key || false,
|
||||
minValue: col.constraints?.min_value || null,
|
||||
maxValue: col.constraints?.max_value || null,
|
||||
defaultValue: col.constraints?.default_value || null,
|
||||
validator: col.constraints?.validator || null,
|
||||
// Include foreign_key if present
|
||||
foreign_key: col.foreign_key,
|
||||
})) || []
|
||||
const transformedColumns = table.schema?.fields.map(col => {
|
||||
const normalized = normalizeFieldTypeForEditor(col)
|
||||
return {
|
||||
...col,
|
||||
type: normalized.type,
|
||||
precision: normalized.precision,
|
||||
old_name: col.name,
|
||||
// Flatten constraints for UI
|
||||
primaryKey: col.primary_key || false,
|
||||
minValue: col.constraints?.min_value || null,
|
||||
maxValue: col.constraints?.max_value || null,
|
||||
defaultValue: col.constraints?.default_value || null,
|
||||
validator: col.constraints?.validator || null,
|
||||
// Include foreign_key if present
|
||||
foreign_key: col.foreign_key,
|
||||
}
|
||||
}) || []
|
||||
setColumns(transformedColumns)
|
||||
// Initialize rules with mode and expr from API
|
||||
// Convert empty string to "admin" for UI (Select doesn't allow empty string values)
|
||||
@@ -140,14 +155,37 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
setHasUnsavedChanges(false)
|
||||
setExpandedFields(new Set())
|
||||
setDeletedColumns([])
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const fresh = await apiClient.call<TableMetadata>(`/api/v1/schemas/${table.schema.name}`)
|
||||
if ((fresh as { error?: unknown[] })?.error?.length) {
|
||||
return
|
||||
}
|
||||
if (!schemaFieldsNeedMigration(fresh.schema?.fields ?? [])) {
|
||||
return
|
||||
}
|
||||
|
||||
const migrated = await migrateSchemaFieldsIfNeeded(apiClient, fresh)
|
||||
if (migrated) {
|
||||
onTableUpdate(migrated)
|
||||
} else {
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to migrate legacy field types:", error)
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
})()
|
||||
}
|
||||
}, [open, table])
|
||||
}, [open, table, apiClient, onTableUpdate])
|
||||
|
||||
const addColumn = () => {
|
||||
setColumns([...columns, {
|
||||
id: `field-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
name: "",
|
||||
type: "string",
|
||||
type: "string",
|
||||
precision: null,
|
||||
primary_key: false,
|
||||
primaryKey: false, // UI format
|
||||
required: true,
|
||||
@@ -201,13 +239,20 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
// Update existing column data
|
||||
const updateColumn = (index: number, field: string, value: any) => {
|
||||
const updatedColumns = columns.map((col, i) => {
|
||||
if (i === index) {
|
||||
var updated = { ...col }
|
||||
updated[field] = value
|
||||
return updated;
|
||||
if (i !== index) {
|
||||
return col
|
||||
}
|
||||
|
||||
return col
|
||||
if (field === "type") {
|
||||
const typeUpdate = applyFieldTypeChange(col.type, value, col.precision)
|
||||
return {
|
||||
...col,
|
||||
type: typeUpdate.type,
|
||||
precision: typeUpdate.precision,
|
||||
}
|
||||
}
|
||||
|
||||
return { ...col, [field]: value }
|
||||
})
|
||||
|
||||
setColumns(updatedColumns)
|
||||
@@ -233,7 +278,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
validator:
|
||||
col.validator !== undefined ? col.validator : (col.constraints?.validator ?? null),
|
||||
}
|
||||
const normalized = normalizeConstraintsForFieldType(col.type, rawConstraints)
|
||||
const normalized = normalizeConstraintsForFieldType(col.type, rawConstraints, col.precision)
|
||||
if (!normalized.ok) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
@@ -244,6 +289,16 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
if (col.type === "int" && !col.precision) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid field",
|
||||
description: `${col.name || "Field"}: integer fields require a precision.`,
|
||||
duration: 5000,
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
const fieldData: any = {
|
||||
id: col.id,
|
||||
name: col.name,
|
||||
@@ -255,6 +310,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
constraints: normalized.constraints,
|
||||
...(col.old_name && { old_name: col.old_name }),
|
||||
}
|
||||
appendPrecisionToFieldPayload(fieldData, col)
|
||||
if (col.foreign_key && col.foreign_key.entity && col.foreign_key.field) {
|
||||
fieldData.foreign_key = col.foreign_key
|
||||
}
|
||||
@@ -282,6 +338,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
if ((updatedTable as any)?.error?.length > 0) throw (updatedTable as any).error
|
||||
|
||||
onTableUpdate(updatedTable)
|
||||
setHasUnsavedChanges(false)
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
description: "Table fields updated successfully.",
|
||||
@@ -407,7 +464,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
})
|
||||
|
||||
// Navigate to entities list or another entity
|
||||
navigate("/entities", undefined, undefined)
|
||||
navigate(ROUTES.entities)
|
||||
onClose()
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
@@ -447,15 +504,16 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Manage table schema and access control rules</DrawerDescription>
|
||||
<DrawerDescription>Manage entity fields, OAuth providers, and access control rules</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2 mb-6">
|
||||
<TabsTrigger value="schema">Schema</TabsTrigger>
|
||||
<TabsList className="grid w-full grid-cols-3 mb-6">
|
||||
<TabsTrigger value="schema">Fields</TabsTrigger>
|
||||
<TabsTrigger value="oauth">OAuth</TabsTrigger>
|
||||
<TabsTrigger value="rules">Access Rules</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -503,7 +561,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
className={isSystem ? "bg-muted" : ""}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className={column.type === "int" ? "grid grid-cols-2 gap-2" : ""}>
|
||||
<Select
|
||||
value={column.type}
|
||||
onValueChange={(value) => updateColumn(index, "type", value)}
|
||||
@@ -520,6 +578,24 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{column.type === "int" && (
|
||||
<Select
|
||||
value={column.precision ?? DEFAULT_INT_PRECISION}
|
||||
onValueChange={(value) => updateColumn(index, "precision", value)}
|
||||
disabled={isSystem}
|
||||
>
|
||||
<SelectTrigger className={isSystem ? "bg-muted" : ""}>
|
||||
<SelectValue placeholder="Precision" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{intPrecisions.map((precision) => (
|
||||
<SelectItem key={precision} value={precision}>
|
||||
{precision}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!isSystem && (
|
||||
@@ -806,6 +882,23 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="oauth" className="space-y-6">
|
||||
{isAuthEntity ? (
|
||||
<OAuthEntityPanel
|
||||
entityName={table.schema.name}
|
||||
apiClient={apiClient}
|
||||
isActive={open && activeTab === "oauth"}
|
||||
/>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground">
|
||||
<p>
|
||||
OAuth is only available for <strong className="text-foreground">auth</strong>-type entities.
|
||||
Change this entity's type to auth to enable OAuth login and account linking.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="rules" className="space-y-6">
|
||||
<div>
|
||||
<h4 className="text-lg font-medium mb-2">Access Control Rules</h4>
|
||||
@@ -1059,13 +1152,15 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
Delete Entity
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={activeTab === "schema" ? handleSaveSchema : handleSaveRules}
|
||||
disabled={isLoading}
|
||||
className="w-full sm:flex-1"
|
||||
>
|
||||
{isLoading ? "Saving..." : `Save ${activeTab === "schema" ? "Schema" : "Rules"}`}
|
||||
</Button>
|
||||
{activeTab !== "oauth" && (
|
||||
<Button
|
||||
onClick={activeTab === "schema" ? handleSaveSchema : handleSaveRules}
|
||||
disabled={isLoading}
|
||||
className="w-full sm:flex-1"
|
||||
>
|
||||
{isLoading ? "Saving..." : `Save ${activeTab === "schema" ? "Fields" : "Rules"}`}
|
||||
</Button>
|
||||
)}
|
||||
</DrawerFooter>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus } from "lucide-react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, Key, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ApiClient, TableMetadata, getApiBaseUrl } from "@/lib/api"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { ApiClient, TableMetadata, buildEntityFileUrl, entityApiKeysApi } from "@/lib/api"
|
||||
import { toApiKeyUsers } from "@/lib/entity-users"
|
||||
import { ApiKeysPanel, openCreateApiKeyDialog } from "@/components/api-keys/api-keys-panel"
|
||||
import { TableConfigDrawer } from "./table-config-drawer"
|
||||
import { TableRecordDocsDrawer } from "./table-records-docs-drawer"
|
||||
import { EditItemDrawer } from "./edit-item-drawer"
|
||||
import { AddItemDrawer } from "./add-item-drawer"
|
||||
import { ColumnVisibilityDropdown } from "./column-visibility-dropdown"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { useSearchParams } from "react-router-dom"
|
||||
|
||||
interface TableDetailViewProps {
|
||||
table: TableMetadata
|
||||
@@ -41,22 +44,30 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
table.schema.fields?.map((field) => field.name) || [],
|
||||
)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
const { route, navigate } = useRouter()
|
||||
const { toast } = useToast()
|
||||
const [activeTab, setActiveTab] = React.useState("records")
|
||||
const [createApiKeyForUserId, setCreateApiKeyForUserId] = React.useState<string | undefined>()
|
||||
const [createApiKeyRequested, setCreateApiKeyRequested] = React.useState(false)
|
||||
const [apiKeysReloadRequested, setApiKeysReloadRequested] = React.useState(0)
|
||||
const [apiKeysLoading, setApiKeysLoading] = React.useState(false)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
|
||||
const isAuthEntity = table.schema.type === "auth"
|
||||
const entityUsers = React.useMemo(() => toApiKeyUsers(tableData), [tableData])
|
||||
const entityApiKeysPath = entityApiKeysApi(table.schema.name)
|
||||
const entityApiKeysCacheKey = `mantis-entity-api-keys-${table.schema.name}`
|
||||
|
||||
// Initialize filter from query params
|
||||
const initialFilter = route.queryParams.filter || ""
|
||||
const initialFilter = searchParams.get("filter") || ""
|
||||
const [filterTerm, setFilterTerm] = React.useState(initialFilter)
|
||||
const [appliedFilter, setAppliedFilter] = React.useState(initialFilter)
|
||||
|
||||
// Sync filter with query params
|
||||
React.useEffect(() => {
|
||||
const filterFromQuery = route.queryParams.filter || ""
|
||||
const filterFromQuery = searchParams.get("filter") || ""
|
||||
if (filterFromQuery !== appliedFilter) {
|
||||
setAppliedFilter(filterFromQuery)
|
||||
setFilterTerm(filterFromQuery)
|
||||
}
|
||||
}, [route.queryParams.filter])
|
||||
}, [searchParams, appliedFilter])
|
||||
|
||||
// Clear data and reset state when switching entities
|
||||
React.useEffect(() => {
|
||||
@@ -67,6 +78,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
setSelectedItems([])
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
setActiveTab("records")
|
||||
setIsLoading(true)
|
||||
|
||||
// Update visible columns based on new table schema
|
||||
@@ -74,8 +86,8 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
setIsViewType(table.schema.type === "view")
|
||||
|
||||
// Clear filter from URL when switching entities (if filter exists in query params)
|
||||
if (route.queryParams.filter) {
|
||||
navigate("/entities/:name", { name: table.schema.name }, {})
|
||||
if (searchParams.get("filter")) {
|
||||
setSearchParams({}, { replace: true })
|
||||
}
|
||||
|
||||
// Load new data after clearing - this will use the reset values (page 1, empty filter)
|
||||
@@ -144,11 +156,13 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
|
||||
const handleFilter = () => {
|
||||
setAppliedFilter(filterTerm)
|
||||
setCurrentPage(1) // Reset to first page when filtering
|
||||
|
||||
// Update URL with filter query param
|
||||
const queryParams: Record<string, string> = filterTerm ? { filter: filterTerm } : {}
|
||||
navigate("/entities/:name", { name: table.schema.name }, queryParams)
|
||||
setCurrentPage(1)
|
||||
|
||||
const nextParams = new URLSearchParams()
|
||||
if (filterTerm) {
|
||||
nextParams.set("filter", filterTerm)
|
||||
}
|
||||
setSearchParams(nextParams, { replace: true })
|
||||
}
|
||||
|
||||
const handleFilterKeyPress = (e: React.KeyboardEvent) => {
|
||||
@@ -209,6 +223,11 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateApiKeyForUser = (userId: string) => {
|
||||
openCreateApiKeyDialog(setCreateApiKeyForUserId, setCreateApiKeyRequested, userId)
|
||||
setActiveTab("api-keys")
|
||||
}
|
||||
|
||||
const filteredFields = table.schema.fields?.filter((field) => visibleColumns.includes(field.name)) || []
|
||||
|
||||
function renderCellContent(field: { name: string; type: string }, value: any) {
|
||||
@@ -242,7 +261,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
return (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{filenames.map((filename: string, i: number) => {
|
||||
const url = `${getApiBaseUrl()}/api/files/${table.schema.name}/${encodeURIComponent(filename)}`;
|
||||
const url = buildEntityFileUrl(table.schema.name, filename);
|
||||
const ext = filename.split(".").pop()?.toLowerCase() || "";
|
||||
|
||||
const isImage = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg"].includes(ext);
|
||||
@@ -278,199 +297,338 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
|
||||
</h2>
|
||||
const recordsCard = (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Table Data</CardTitle>
|
||||
<CardDescription>Current records in the {table.schema.name} table</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedItems.length > 0 && (
|
||||
<Button variant="destructive" size="sm" onClick={handleDeleteSelected} disabled={isDeleting}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{isDeleting
|
||||
? "Deleting..."
|
||||
: `Delete ${selectedItems.length} item${selectedItems.length > 1 ? "s" : ""}`}
|
||||
</Button>
|
||||
)}
|
||||
<ColumnVisibilityDropdown
|
||||
table={table}
|
||||
visibleColumns={visibleColumns}
|
||||
onVisibilityChange={setVisibleColumns}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="icon" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
{!isViewType && (
|
||||
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">
|
||||
<Checkbox
|
||||
checked={selectedItems.length === tableData.length && tableData.length > 0}
|
||||
onCheckedChange={handleSelectAll}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
</TableHead>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name}>
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
{isAuthEntity && <TableHead>Actions</TableHead>}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1 + (isAuthEntity ? 1 : 0)} className="text-center text-muted-foreground h-64">
|
||||
Loading...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : tableData.length > 0 ? (
|
||||
tableData.map((row, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={(e) => handleRowClick(row, e)}
|
||||
>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={selectedItems.includes(row.id)}
|
||||
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
|
||||
aria-label={`Select row ${index + 1}`}
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name} className="max-w-0">
|
||||
<div className="min-w-0 max-w-full line-clamp-2 break-words overflow-hidden text-ellipsis" title={typeof row[field.name] === "string" ? row[field.name] : undefined}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</div>
|
||||
</TableCell>
|
||||
))}
|
||||
{isAuthEntity && (
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleCreateApiKeyForUser(row.id)}>
|
||||
<Key className="mr-2 h-4 w-4" />
|
||||
Create API Key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1 + (isAuthEntity ? 1 : 0)} className="text-center h-64 align-middle">
|
||||
<div className="flex flex-col items-center justify-center py-16">
|
||||
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
|
||||
<p className="text-muted-foreground text-center mb-6 max-w-md">
|
||||
This table doesn't have any records yet. Add some data to get started.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
{!isViewType && (
|
||||
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
View API Documentation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search/Filter Bar */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
|
||||
<Input
|
||||
placeholder="Search records..."
|
||||
value={filterTerm}
|
||||
onChange={(e) => setFilterTerm(e.target.value)}
|
||||
onKeyPress={handleFilterKeyPress}
|
||||
className="pl-10 pr-20"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleFilter}
|
||||
disabled={isLoading}
|
||||
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
|
||||
size="sm"
|
||||
>
|
||||
Filter
|
||||
</Button>
|
||||
{appliedFilter && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
navigate("/entities/:name", { name: table.schema.name }, {})
|
||||
}}
|
||||
className="h-6 text-xs"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Page {currentPage} of {totalPages}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{isAuthEntity ? (
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<CardTitle>Table Data</CardTitle>
|
||||
<CardDescription>Current records in the {table.schema.name} table</CardDescription>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedItems.length > 0 && (
|
||||
<Button variant="destructive" size="sm" onClick={handleDeleteSelected} disabled={isDeleting}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{isDeleting
|
||||
? "Deleting..."
|
||||
: `Delete ${selectedItems.length} item${selectedItems.length > 1 ? "s" : ""}`}
|
||||
<TabsList>
|
||||
<TabsTrigger value="records">Records</TabsTrigger>
|
||||
<TabsTrigger value="api-keys">API Keys</TabsTrigger>
|
||||
</TabsList>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
activeTab === "api-keys"
|
||||
? setApiKeysReloadRequested((count) => count + 1)
|
||||
: handleReload()
|
||||
}
|
||||
disabled={activeTab === "api-keys" ? apiKeysLoading : isLoading}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`h-4 w-4 ${(activeTab === "api-keys" ? apiKeysLoading : isLoading) ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
{!isViewType && activeTab === "records" && (
|
||||
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
{activeTab === "api-keys" && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => openCreateApiKeyDialog(setCreateApiKeyForUserId, setCreateApiKeyRequested)}
|
||||
disabled={entityUsers.length === 0}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New API Key
|
||||
</Button>
|
||||
)}
|
||||
<ColumnVisibilityDropdown
|
||||
table={table}
|
||||
visibleColumns={visibleColumns}
|
||||
onVisibilityChange={setVisibleColumns}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">
|
||||
<Checkbox
|
||||
checked={selectedItems.length === tableData.length && tableData.length > 0}
|
||||
onCheckedChange={handleSelectAll}
|
||||
aria-label="Select all"
|
||||
/>
|
||||
</TableHead>
|
||||
{filteredFields.map((field) => (
|
||||
<TableHead key={field.name}>
|
||||
{field.name}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center text-muted-foreground h-64">
|
||||
Loading...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : tableData.length > 0 ? (
|
||||
tableData.map((row, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={(e) => handleRowClick(row, e)}
|
||||
>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={selectedItems.includes(row.id)}
|
||||
onCheckedChange={(checked) => handleSelectItem(row.id, checked as boolean)}
|
||||
aria-label={`Select row ${index + 1}`}
|
||||
/>
|
||||
</TableCell>
|
||||
{filteredFields.map((field) => (
|
||||
<TableCell key={field.name} className="max-w-0">
|
||||
<div className="min-w-0 max-w-full line-clamp-2 break-words overflow-hidden text-ellipsis" title={typeof row[field.name] === "string" ? row[field.name] : undefined}>
|
||||
{renderCellContent(field, row[field.name])}
|
||||
</div>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={filteredFields.length + 1} className="text-center h-64 align-middle">
|
||||
<div className="flex flex-col items-center justify-center py-16">
|
||||
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Records Found</h3>
|
||||
<p className="text-muted-foreground text-center mb-6 max-w-md">
|
||||
This table doesn't have any records yet. Add some data to get started.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
{!isViewType && (
|
||||
<Button onClick={handleAddItem} disabled={isDeleting || isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => setDocsOpen(true)} disabled={isDeleting}>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
View API Documentation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Page {currentPage} of {totalPages}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
{activeTab === "records" && (
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
|
||||
<Input
|
||||
placeholder="Search records..."
|
||||
value={filterTerm}
|
||||
onChange={(e) => setFilterTerm(e.target.value)}
|
||||
onKeyPress={handleFilterKeyPress}
|
||||
className="pl-10 pr-20"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleFilter}
|
||||
disabled={isLoading}
|
||||
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
|
||||
size="sm"
|
||||
>
|
||||
Filter
|
||||
</Button>
|
||||
{appliedFilter && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
setSearchParams({}, { replace: true })
|
||||
}}
|
||||
className="h-6 text-xs"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TabsContent value="records" className="mt-0 space-y-6">
|
||||
{recordsCard}
|
||||
</TabsContent>
|
||||
<TabsContent value="api-keys" className="mt-0 space-y-6">
|
||||
<ApiKeysPanel
|
||||
users={entityUsers}
|
||||
apiClient={apiClient}
|
||||
apiKeysApi={entityApiKeysPath}
|
||||
cacheKey={entityApiKeysCacheKey}
|
||||
isActive={activeTab === "api-keys"}
|
||||
defaultUserId={createApiKeyForUserId}
|
||||
createRequested={createApiKeyRequested}
|
||||
reloadRequested={apiKeysReloadRequested}
|
||||
onCreateRequestHandled={() => setCreateApiKeyRequested(false)}
|
||||
onLoadingChange={setApiKeysLoading}
|
||||
supportsEdit={false}
|
||||
panelTitle={`${table.schema.name} API Keys`}
|
||||
userColumnLabel="User"
|
||||
createDialogTitle="Create Entity API Key"
|
||||
createDialogDescription={`Create a new API key linked to a user in ${table.schema.name}.`}
|
||||
userFieldLabel="User"
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">
|
||||
Entity <span className="text-primary font-mono italic">'{table.schema.name}'</span> data
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="icon" onClick={handleReload} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setConfigOpen(true)}>
|
||||
<Cog className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" onClick={() => setDocsOpen(true)}>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
{!isViewType && (
|
||||
<Button size="sm" onClick={handleAddItem} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Record
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
|
||||
<Input
|
||||
placeholder="Search records..."
|
||||
value={filterTerm}
|
||||
onChange={(e) => setFilterTerm(e.target.value)}
|
||||
onKeyPress={handleFilterKeyPress}
|
||||
className="pl-10 pr-20"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleFilter}
|
||||
disabled={isLoading}
|
||||
className="absolute right-1 top-1/2 transform -translate-y-1/2 h-7"
|
||||
size="sm"
|
||||
>
|
||||
Filter
|
||||
</Button>
|
||||
{appliedFilter && (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<p className="text-sm text-muted-foreground">Filtering by: "{appliedFilter}"</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setFilterTerm("")
|
||||
setAppliedFilter("")
|
||||
setSearchParams({}, { replace: true })
|
||||
}}
|
||||
className="h-6 text-xs"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{recordsCard}
|
||||
</>
|
||||
)}
|
||||
|
||||
<TableConfigDrawer
|
||||
table={table}
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { FileText, ChevronDown, ChevronRight, X, Copy } from "lucide-react"
|
||||
import { BookOpen, FileText, X } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import {
|
||||
DocCodeBlock,
|
||||
DocCollapsibleSection,
|
||||
DocEndpointHeader,
|
||||
DocErrorList,
|
||||
DocInfoBanner,
|
||||
DocSectionHeading,
|
||||
} from "@/components/database/api-doc-shared"
|
||||
import { dataTypes, intPrecisions } from "@/lib/field-types"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
interface TableDocsDrawerProps {
|
||||
@@ -16,14 +23,9 @@ interface TableDocsDrawerProps {
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Generate docs for entity schema management API
|
||||
export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
const handleClose = () => {
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={handleClose}>
|
||||
<Drawer open={open} onOpenChange={onClose}>
|
||||
<DrawerContent side="right" className="w-[1000px] max-w-[95vw]">
|
||||
<DrawerHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -36,54 +38,67 @@ export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>
|
||||
API endpoints for managing entity schemas. All endpoints require admin authentication token.
|
||||
Admin-only endpoints for managing entity schemas, field types, and access rules.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="rounded-lg border bg-muted/30 p-4 mb-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong className="text-foreground">Note:</strong> All endpoints require an admin authentication token in the Authorization header:
|
||||
<code className="ml-2 px-2 py-1 bg-background rounded text-xs">Authorization: Bearer YOUR_ADMIN_TOKEN</code>
|
||||
<DocInfoBanner>
|
||||
<p className="text-sm text-muted-foreground space-y-2">
|
||||
<span className="block">
|
||||
<strong className="text-foreground">Admin authentication required:</strong> all schema endpoints
|
||||
require an admin JWT in{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">Authorization: Bearer YOUR_ADMIN_TOKEN</code>.
|
||||
</span>
|
||||
<span className="block">
|
||||
<strong className="text-foreground">Response envelope:</strong>{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">{`{ "status", "data", "error" }`}</code>.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</DocInfoBanner>
|
||||
|
||||
<DocSectionHeading>Schema CRUD</DocSectionHeading>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/schemas`}
|
||||
endpoint="/api/v1/schemas"
|
||||
description="List all entity schemas"
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
endpoint="/api/v1/schemas/{schema_name_or_id}"
|
||||
description="Get a specific entity schema by name or ID"
|
||||
operation="get"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/schemas`}
|
||||
endpoint="/api/v1/schemas"
|
||||
description="Create a new entity schema"
|
||||
operation="create"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
description="Update an existing entity schema"
|
||||
endpoint="/api/v1/schemas/{schema_name_or_id}"
|
||||
description="Update an existing entity schema (add/update/delete fields by id or name)"
|
||||
operation="update"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/schemas/{ENTITY_SCHEMA_NAME_OR_ID}`}
|
||||
endpoint="/api/v1/schemas/{schema_name_or_id}"
|
||||
description="Delete an entity schema"
|
||||
operation="delete"
|
||||
/>
|
||||
|
||||
<DocSectionHeading>Reference</DocSectionHeading>
|
||||
|
||||
<SchemaReferenceSection />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
@@ -92,6 +107,133 @@ export function TableDocsDrawer({ open, onClose }: TableDocsDrawerProps) {
|
||||
)
|
||||
}
|
||||
|
||||
function SchemaReferenceSection() {
|
||||
const fieldTypesList = dataTypes
|
||||
.map((type) => {
|
||||
if (type === "int") {
|
||||
return `int — integer with precision (${intPrecisions.join(", ")})`
|
||||
}
|
||||
return type
|
||||
})
|
||||
.join("\n")
|
||||
|
||||
const entityTypesExample = JSON.stringify(
|
||||
{
|
||||
base: "Standard CRUD entity with configurable access rules",
|
||||
auth: "User authentication entity — enables /auth/{name}/login, API keys, and OAuth",
|
||||
view: "Read-only SQL view — requires view_query, mutations rejected",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
|
||||
const accessRulesExample = JSON.stringify(
|
||||
{
|
||||
rules: {
|
||||
list: { mode: "public", expr: "" },
|
||||
get: { mode: "auth", expr: "" },
|
||||
add: { mode: "auth", expr: "" },
|
||||
update: { mode: "custom", expr: "@request.auth.id == @record.owner_id" },
|
||||
delete: { mode: "", expr: "" },
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
|
||||
const intFieldExample = JSON.stringify(
|
||||
{
|
||||
name: "quantity",
|
||||
type: "int",
|
||||
precision: "i32",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: 1000,
|
||||
min_value: 0,
|
||||
validator: null,
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DocCollapsibleSection
|
||||
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
|
||||
title="Field types"
|
||||
description="Supported field types when creating or patching schema fields."
|
||||
>
|
||||
<DocCodeBlock code={fieldTypesList} height="h-36" />
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">Integer precision example</h5>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Use type <code className="bg-muted px-1 rounded">int</code> with a{" "}
|
||||
<code className="bg-muted px-1 rounded">precision</code> property. Legacy types (int32, uint64, etc.) are
|
||||
normalized to <code className="bg-muted px-1 rounded">int</code> + precision on load.
|
||||
</p>
|
||||
<DocCodeBlock code={intFieldExample} height="h-48" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<code className="bg-muted px-1 rounded">file</code> and <code className="bg-muted px-1 rounded">files</code>{" "}
|
||||
fields store upload paths served at <code className="bg-muted px-1 rounded">GET /api/v1/files/{"{entity}"}/{"{file}"}</code>.
|
||||
Create/update records with <code className="bg-muted px-1 rounded">multipart/form-data</code>.
|
||||
</p>
|
||||
</DocCollapsibleSection>
|
||||
|
||||
<DocCollapsibleSection
|
||||
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
|
||||
title="Entity types"
|
||||
description="The type property determines entity behavior and available API routes."
|
||||
>
|
||||
<DocCodeBlock code={entityTypesExample} height="h-36" />
|
||||
</DocCollapsibleSection>
|
||||
|
||||
<DocCollapsibleSection
|
||||
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
|
||||
title="Access rules"
|
||||
description="Each CRUD operation has a mode and optional custom expression."
|
||||
>
|
||||
<DocCodeBlock code={accessRulesExample} height="h-44" />
|
||||
<div className="text-sm text-muted-foreground space-y-2">
|
||||
<p>
|
||||
<strong className="text-foreground">Modes:</strong>{" "}
|
||||
<code className="bg-muted px-1 rounded">public</code> — no auth required;{" "}
|
||||
<code className="bg-muted px-1 rounded">auth</code> — authenticated user required;{" "}
|
||||
<code className="bg-muted px-1 rounded">custom</code> — expression must evaluate true; empty mode — admin
|
||||
only (not exposed on public entity API).
|
||||
</p>
|
||||
<p>
|
||||
Realtime topic access mirrors list (entity name) and get (entity:row_id) rules.
|
||||
</p>
|
||||
</div>
|
||||
</DocCollapsibleSection>
|
||||
|
||||
<DocCollapsibleSection
|
||||
icon={<BookOpen className="h-4 w-4 text-muted-foreground" />}
|
||||
title="Field patch operations"
|
||||
description="When updating a schema via PATCH, fields support add, update, and delete."
|
||||
>
|
||||
<DocCodeBlock
|
||||
code={`// Add new field (omit id)
|
||||
{ "name": "new_field", "type": "string", ... }
|
||||
|
||||
// Update existing field (include id)
|
||||
{ "id": "mbf_existing_field_id", "name": "renamed_field", "type": "string", ... }
|
||||
|
||||
// Delete field
|
||||
{ "id": "mbf_field_to_delete", "op": "delete" }`}
|
||||
height="h-40"
|
||||
/>
|
||||
</DocCollapsibleSection>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ApiEndpointCard({
|
||||
method,
|
||||
endpoint,
|
||||
@@ -104,105 +246,99 @@ function ApiEndpointCard({
|
||||
operation: string
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
|
||||
const getMethodColor = (method: string) => {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
|
||||
case "POST":
|
||||
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
|
||||
case "PATCH":
|
||||
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
|
||||
case "DELETE":
|
||||
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
}
|
||||
const baseUrl = getApiBaseUrl()
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
if (method !== "GET") {
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
}
|
||||
|
||||
example += ` \\\n -H "Authorization: Bearer YOUR_ADMIN_TOKEN"`
|
||||
|
||||
if (operation === "create") {
|
||||
const sampleSchema = {
|
||||
name: "example_entity",
|
||||
type: "base",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
name: "title",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
}
|
||||
],
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
}
|
||||
}
|
||||
// For view types, also include: view_query: "CREATE VIEW ... AS SELECT ..."
|
||||
fields: [
|
||||
{
|
||||
name: "title",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "count",
|
||||
type: "int",
|
||||
precision: "i32",
|
||||
primary_key: false,
|
||||
required: false,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: 0,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" },
|
||||
},
|
||||
}
|
||||
example += ` \\\n -d '${JSON.stringify(sampleSchema, null, 2)}'`
|
||||
} else if (operation === "update") {
|
||||
const sampleUpdate = {
|
||||
name: "updated_entity_name",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
id: "mbf_existing_field_id",
|
||||
name: "updated_field_name",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
fields: [
|
||||
{
|
||||
id: "mbf_existing_field_id",
|
||||
name: "updated_field_name",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
{
|
||||
name: "new_field",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
required: false,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "new_field",
|
||||
type: "int",
|
||||
precision: "u32",
|
||||
primary_key: false,
|
||||
required: false,
|
||||
system: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
{
|
||||
id: "mbf_field_to_delete",
|
||||
op: "delete"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "mbf_field_to_delete",
|
||||
op: "delete",
|
||||
},
|
||||
],
|
||||
}
|
||||
example += ` \\\n -d '${JSON.stringify(sampleUpdate, null, 2)}'`
|
||||
}
|
||||
@@ -211,345 +347,113 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
const generateResponseExample = () => {
|
||||
if (operation === "list") {
|
||||
// List schemas - NOT paginated, returns direct array
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: [
|
||||
{
|
||||
created: "2025-12-05 02:08:06",
|
||||
id: "mbt_7691163245302450708",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: [],
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_16766180539469268884",
|
||||
name: "avatar",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
type: "files",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_7691163245302450708",
|
||||
name: "test_new",
|
||||
rules: {
|
||||
add: { expr: "", mode: "" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-10 23:24:46"
|
||||
},
|
||||
{
|
||||
created: "2025-12-12 16:21:45",
|
||||
id: "mbt_15118982290295364091",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_15118982290295364091",
|
||||
name: "test",
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-12 16:21:45"
|
||||
}
|
||||
],
|
||||
error: "",
|
||||
status: 200
|
||||
const sampleSchema = {
|
||||
created: "2026-01-15T10:00:00Z",
|
||||
id: "mbt_7691163245302450708",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: { default_value: null, max_value: null, min_value: null, validator: "@password" },
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
constraints: { default_value: null, max_value: null, min_value: null, validator: null },
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
constraints: { default_value: null, max_value: null, min_value: null, validator: null },
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
constraints: { default_value: 0, max_value: null, min_value: null, validator: null },
|
||||
id: "mbf_16766180539469268884",
|
||||
name: "count",
|
||||
precision: "i32",
|
||||
primary_key: false,
|
||||
required: false,
|
||||
system: false,
|
||||
type: "int",
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_7691163245302450708",
|
||||
name: "example_entity",
|
||||
rules: {
|
||||
add: { expr: "", mode: "auth" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
system: false,
|
||||
type: "base",
|
||||
},
|
||||
updated: "2026-01-15T10:00:00Z",
|
||||
}
|
||||
|
||||
if (operation === "list") {
|
||||
return JSON.stringify({ status: 200, data: [sampleSchema], error: "" }, null, 2)
|
||||
}
|
||||
|
||||
if (operation === "delete") {
|
||||
return "Status: 204 No Content"
|
||||
return JSON.stringify({ status: 200, data: null, error: "" }, null, 2)
|
||||
}
|
||||
|
||||
// Single schema response (get, create, or update)
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: {
|
||||
created: "2025-12-05 02:08:06",
|
||||
id: "mbt_7691163245302450708",
|
||||
schema: {
|
||||
fields: [
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: "@password"
|
||||
},
|
||||
id: "mbf_14258576900392064537",
|
||||
name: "id",
|
||||
primary_key: true,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "string",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_13735287961322938256",
|
||||
name: "created",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_9124719522053273721",
|
||||
name: "updated",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: true,
|
||||
type: "date",
|
||||
unique: false
|
||||
},
|
||||
{
|
||||
constraints: {
|
||||
default_value: [],
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null
|
||||
},
|
||||
id: "mbf_16766180539469268884",
|
||||
name: "avatar",
|
||||
primary_key: false,
|
||||
required: true,
|
||||
system: false,
|
||||
type: "files",
|
||||
unique: false
|
||||
}
|
||||
],
|
||||
has_api: true,
|
||||
id: "mbt_7691163245302450708",
|
||||
name: "test_new",
|
||||
rules: {
|
||||
add: { expr: "", mode: "" },
|
||||
delete: { expr: "", mode: "auth" },
|
||||
get: { expr: "", mode: "auth" },
|
||||
list: { expr: "", mode: "auth" },
|
||||
update: { expr: "", mode: "auth" }
|
||||
},
|
||||
system: false,
|
||||
type: "base"
|
||||
},
|
||||
updated: "2025-12-10 23:24:46"
|
||||
},
|
||||
error: "",
|
||||
status: operation === "create" ? 201 : 200
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
const status = operation === "create" ? 201 : 200
|
||||
return JSON.stringify({ status, data: sampleSchema, error: "" }, null, 2)
|
||||
}
|
||||
|
||||
const requestExample = generateRequestExample()
|
||||
const responseExample = generateResponseExample()
|
||||
|
||||
const errors: Array<{ code: string; message: string }> = [
|
||||
{ code: "400", message: "Bad Request — parsing or validation error" },
|
||||
{ code: "401", message: "Unauthorized — admin token required" },
|
||||
{ code: "403", message: "Forbidden — admin access denied" },
|
||||
{ code: "500", message: "Internal Server Error" },
|
||||
]
|
||||
|
||||
if (operation === "get" || operation === "update" || operation === "delete") {
|
||||
errors.splice(3, 0, { code: "404", message: "Not Found — schema not found" })
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge className={getMethodColor(method)} variant="secondary">
|
||||
{method}
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">{description}</p>
|
||||
<DocEndpointHeader method={method} endpoint={endpoint} description={description} isOpen={isOpen} />
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Request Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(requestExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{requestExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
<h5 className="font-medium mb-2">Request Example</h5>
|
||||
<DocCodeBlock code={requestExample} height={operation === "create" || operation === "update" ? "h-64" : "h-48"} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Response Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(responseExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{responseExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h5 className="font-medium mb-3">Possible Errors</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
400
|
||||
</Badge>
|
||||
<span>Bad Request - Parsing error (message will be provided)</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
403
|
||||
</Badge>
|
||||
<span>Forbidden - Auth error (admin token required)</span>
|
||||
</div>
|
||||
{(operation === "get" || operation === "update" || operation === "delete") && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
404
|
||||
</Badge>
|
||||
<span>Not Found - Resource/item not found</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
500
|
||||
</Badge>
|
||||
<span>Internal Server Error</span>
|
||||
</div>
|
||||
</div>
|
||||
<h5 className="font-medium mb-2">Response Example</h5>
|
||||
<DocCodeBlock code={responseExample} height="h-64" />
|
||||
</div>
|
||||
<DocErrorList errors={errors} />
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { FileText, ChevronDown, ChevronRight, X, Copy, Radio } from "lucide-react"
|
||||
import { ChevronDown, ChevronRight, FileText, Radio, Shield, Upload, X } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
DocCodeBlock,
|
||||
DocCollapsibleSection,
|
||||
DocEndpointHeader,
|
||||
DocErrorList,
|
||||
DocInfoBanner,
|
||||
DocSectionHeading,
|
||||
getMethodColor,
|
||||
} from "@/components/database/api-doc-shared"
|
||||
import type { TableMetadata } from "@/lib/api"
|
||||
import { getApiBaseUrl } from "@/lib/api"
|
||||
|
||||
@@ -17,42 +26,63 @@ interface TableDocsDrawerProps {
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Generate docs based on user defined tables
|
||||
export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerProps) {
|
||||
const handleClose = () => {
|
||||
onClose()
|
||||
}
|
||||
const entityName = table.schema.name
|
||||
const isAuthEntity = table.schema.type === "auth"
|
||||
const hasFileFields = table.schema.fields?.some((f) => f.type === "file" || f.type === "files") ?? false
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={handleClose}>
|
||||
<Drawer open={open} onOpenChange={onClose}>
|
||||
<DrawerContent side="right" className="w-[1000px] max-w-[95vw]">
|
||||
<DrawerHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5" />
|
||||
<DrawerTitle>API Documentation - {table.schema.name}</DrawerTitle>
|
||||
<DrawerTitle>API Documentation — {entityName}</DrawerTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Auto-generated API endpoints and examples</DrawerDescription>
|
||||
<DrawerDescription>
|
||||
Entity record API, realtime subscriptions{isAuthEntity ? ", authentication, API keys, and OAuth" : ""}.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="p-6 space-y-6">
|
||||
<DocInfoBanner>
|
||||
<p className="text-sm text-muted-foreground space-y-2">
|
||||
<span className="block">
|
||||
<strong className="text-foreground">Credentials:</strong> send a JWT from login/refresh or an API
|
||||
key (<code className="bg-background px-1 rounded text-xs">mb_sk_...</code>) as{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">Authorization: Bearer <token></code>.
|
||||
Not every route requires auth — access depends on each entity's rules (
|
||||
<code className="bg-background px-1 rounded text-xs">public</code>,{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">auth</code>,{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">custom</code>, or admin-only empty mode).
|
||||
</span>
|
||||
<span className="block">
|
||||
<strong className="text-foreground">Response envelope:</strong> JSON endpoints return{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">{`{ "status", "data", "error" }`}</code>.
|
||||
</span>
|
||||
</p>
|
||||
</DocInfoBanner>
|
||||
|
||||
<DocSectionHeading>Records</DocSectionHeading>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/entities/${table.schema.name}`}
|
||||
description={`List all records in the ${table.schema.name} table`}
|
||||
endpoint={`/api/v1/entities/${entityName}`}
|
||||
description={`List records in ${entityName}. Supports cursor pagination and optional filters.`}
|
||||
table={table}
|
||||
operation="list"
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="GET"
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
endpoint={`/api/v1/entities/${entityName}/{id}`}
|
||||
description="Get a specific record by ID"
|
||||
table={table}
|
||||
operation="get"
|
||||
@@ -62,23 +92,33 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
<>
|
||||
<ApiEndpointCard
|
||||
method="POST"
|
||||
endpoint={`/api/v1/entities/${table.schema.name}`}
|
||||
description="Create a new record"
|
||||
endpoint={`/api/v1/entities/${entityName}`}
|
||||
description={
|
||||
hasFileFields
|
||||
? "Create a record (JSON or multipart/form-data for file fields)"
|
||||
: "Create a new record"
|
||||
}
|
||||
table={table}
|
||||
operation="create"
|
||||
hasFileFields={hasFileFields}
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="PATCH"
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
description="Update a specific record"
|
||||
endpoint={`/api/v1/entities/${entityName}/{id}`}
|
||||
description={
|
||||
hasFileFields
|
||||
? "Update a record (JSON or multipart/form-data for file fields)"
|
||||
: "Update a specific record"
|
||||
}
|
||||
table={table}
|
||||
operation="update"
|
||||
hasFileFields={hasFileFields}
|
||||
/>
|
||||
|
||||
<ApiEndpointCard
|
||||
method="DELETE"
|
||||
endpoint={`/api/v1/entities/${table.schema.name}/{id}`}
|
||||
endpoint={`/api/v1/entities/${entityName}/{id}`}
|
||||
description="Delete a specific record"
|
||||
table={table}
|
||||
operation="delete"
|
||||
@@ -86,7 +126,12 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
</>
|
||||
)}
|
||||
|
||||
<RealtimeDocCard table={table} />
|
||||
{hasFileFields && <FilesDocCard entityName={entityName} />}
|
||||
|
||||
{isAuthEntity && <AuthDocsSection entityName={entityName} />}
|
||||
|
||||
<DocSectionHeading>Realtime</DocSectionHeading>
|
||||
<RealtimeDocCard entityName={entityName} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
@@ -95,23 +140,318 @@ export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerP
|
||||
)
|
||||
}
|
||||
|
||||
// Realtime (SSE) documentation: connect and update topics for this entity
|
||||
function RealtimeDocCard({ table }: { table: TableMetadata }) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
const entityName = table.schema.name
|
||||
function AuthDocsSection({ entityName }: { entityName: string }) {
|
||||
const baseUrl = getApiBaseUrl()
|
||||
const authPrefix = `/api/v1/auth/${entityName}`
|
||||
|
||||
return (
|
||||
<>
|
||||
<DocSectionHeading>Authentication</DocSectionHeading>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/login`}
|
||||
description="Authenticate against this auth entity and receive a JWT. Rate-limited to 5 attempts/minute per IP. No Bearer token required."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/login" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"identity": "user@example.com",
|
||||
"password": "your_password"
|
||||
}'`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: {
|
||||
token: "eyJhbGciOiJIUzI1NiIs...",
|
||||
user: { id: "019c1b81-364b-7000-8120-b5416b2c42c2", email: "user@example.com" },
|
||||
},
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
errors={[
|
||||
{ code: "400", message: "Bad Request — invalid credentials or input" },
|
||||
{ code: "404", message: "Not Found — entity not found or not auth-enabled" },
|
||||
{ code: "429", message: "Too Many Requests — rate limit exceeded" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/refresh`}
|
||||
description="Refresh the current entity user JWT using the existing token."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/refresh" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: {
|
||||
token: "eyJhbGciOiJIUzI1NiIs...",
|
||||
user: { id: "019c1b81-364b-7000-8120-b5416b2c42c2", email: "user@example.com" },
|
||||
},
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
errors={[{ code: "401", message: "Unauthorized — invalid or expired token" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/logout`}
|
||||
description="Invalidate the current session when the JWT contains a session_id claim."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/logout" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { logged_out: true }, error: "" }, null, 2)}
|
||||
errors={[{ code: "401", message: "Unauthorized — invalid or missing token" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="GET"
|
||||
endpoint="/api/v1/auth/verify"
|
||||
description="Verify that the current JWT or API key is valid. Rate-limited to 5 requests/minute per IP."
|
||||
requestExample={`curl "${baseUrl}/api/v1/auth/verify" \\
|
||||
-H "Authorization: Bearer YOUR_TOKEN"`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { status: "OK" }, error: "" }, null, 2)}
|
||||
errors={[{ code: "401", message: "Unauthorized — invalid or expired credentials" }]}
|
||||
/>
|
||||
|
||||
<DocSectionHeading>API Keys</DocSectionHeading>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="GET"
|
||||
endpoint={`${authPrefix}/api-keys`}
|
||||
description="List API keys for the authenticated user. Raw secrets are never returned in list responses."
|
||||
requestExample={`curl "${baseUrl}${authPrefix}/api-keys" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: [
|
||||
{
|
||||
id: "mbak_123456789",
|
||||
entity_name: entityName,
|
||||
user_id: "019c1b81-364b-7000-8120-b5416b2c42c2",
|
||||
label: "Mobile app",
|
||||
permissions: [],
|
||||
last_used: null,
|
||||
created: "2026-01-15T10:00:00Z",
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
errors={[{ code: "401", message: "Unauthorized" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/api-keys`}
|
||||
description="Create a new API key. The raw mb_sk_... secret is returned once at creation time."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/api-keys" \\
|
||||
-H "Authorization: Bearer YOUR_JWT" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"label": "Mobile app",
|
||||
"permissions": [],
|
||||
"expires_at": ""
|
||||
}'`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 201,
|
||||
data: {
|
||||
id: "mbak_123456789",
|
||||
entity_name: entityName,
|
||||
user_id: "019c1b81-364b-7000-8120-b5416b2c42c2",
|
||||
label: "Mobile app",
|
||||
key: "mb_sk_a1b2c3d4e5f6...",
|
||||
created: "2026-01-15T10:00:00Z",
|
||||
},
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
errors={[{ code: "401", message: "Unauthorized" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="DELETE"
|
||||
endpoint={`${authPrefix}/api-keys/{id}`}
|
||||
description="Revoke an API key by ID."
|
||||
requestExample={`curl -X DELETE "${baseUrl}${authPrefix}/api-keys/mbak_123456789" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { deleted: true }, error: "" }, null, 2)}
|
||||
errors={[
|
||||
{ code: "401", message: "Unauthorized" },
|
||||
{ code: "404", message: "Not Found — key does not exist" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<DocSectionHeading>OAuth</DocSectionHeading>
|
||||
|
||||
<DocCollapsibleSection
|
||||
icon={<Shield className="h-4 w-4 text-muted-foreground" />}
|
||||
title="OAuth login & account linking"
|
||||
description="Browser redirect flow (PKCE) and programmatic account management for enabled providers."
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className={getMethodColor("GET")} variant="secondary">
|
||||
GET
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
|
||||
{authPrefix}/oauth/authorize/{"{provider}"}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Start OAuth login — redirects the browser to the provider authorization URL. Optional{" "}
|
||||
<code className="bg-muted px-1 rounded">redirect_uri</code> query param; defaults to the server callback
|
||||
route.
|
||||
</p>
|
||||
<DocCodeBlock
|
||||
code={`# Browser redirect (no Bearer token)
|
||||
${baseUrl}${authPrefix}/oauth/authorize/google?redirect_uri=https://your-app.com/callback`}
|
||||
height="h-24"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className={getMethodColor("GET")} variant="secondary">
|
||||
GET
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
|
||||
{authPrefix}/oauth/callback/{"{provider}"}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
OAuth callback — handles <code className="bg-muted px-1 rounded">code</code>,{" "}
|
||||
<code className="bg-muted px-1 rounded">state</code>, and provider error query params. Returns JWT and
|
||||
user record on success.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="GET"
|
||||
endpoint={`${authPrefix}/oauth/providers`}
|
||||
description="List all OAuth providers with per-entity status (`enabled_for_entity`). No authentication required."
|
||||
requestExample={`curl "${baseUrl}${authPrefix}/oauth/providers"`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: [{ id: "019c1b81-364b-7000-8120-b5416b2c42c2", name: "google", enabled: true, enabled_for_entity: true }],
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
nested
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="GET"
|
||||
endpoint={`${authPrefix}/oauth/accounts`}
|
||||
description="List OAuth accounts linked to the current authenticated user."
|
||||
requestExample={`curl "${baseUrl}${authPrefix}/oauth/accounts" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: [{ provider: "google", provider_user_id: "123456", linked_at: "2026-01-15T10:00:00Z" }],
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
nested
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/oauth/link/{provider}`}
|
||||
description="Link an OAuth provider to the current user using authorization code and state from the provider."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/oauth/link/google" \\
|
||||
-H "Authorization: Bearer YOUR_JWT" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"code": "provider_auth_code",
|
||||
"state": "csrf_state_value"
|
||||
}'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: {}, error: "" }, null, 2)}
|
||||
nested
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="DELETE"
|
||||
endpoint={`${authPrefix}/oauth/link/{provider}`}
|
||||
description="Unlink an OAuth provider from the current user."
|
||||
requestExample={`curl -X DELETE "${baseUrl}${authPrefix}/oauth/link/google" \\
|
||||
-H "Authorization: Bearer YOUR_JWT"`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { unlinked: true }, error: "" }, null, 2)}
|
||||
nested
|
||||
/>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
OAuth providers are registered by admins via{" "}
|
||||
<code className="bg-muted px-1 rounded">/api/v1/sys/oauth/providers</code> and enabled per entity via{" "}
|
||||
<code className="bg-muted px-1 rounded">/api/v1/sys/oauth/entity-config</code>.
|
||||
</p>
|
||||
</div>
|
||||
</DocCollapsibleSection>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function FilesDocCard({ entityName }: { entityName: string }) {
|
||||
const baseUrl = getApiBaseUrl()
|
||||
const exampleUrl = `${baseUrl}/api/v1/files/${entityName}/uploads/photo.jpg`
|
||||
|
||||
return (
|
||||
<DocCollapsibleSection
|
||||
icon={<Upload className="h-4 w-4 text-muted-foreground" />}
|
||||
title="File uploads"
|
||||
description="Serve uploaded files from file/files fields. Access follows the entity get access rule."
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge className={getMethodColor("GET")} variant="secondary">
|
||||
GET
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">/api/v1/files/{entityName}/{"{file}"}</code>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Returns the stored file binary. The <code className="bg-muted px-1 rounded">file</code> path segment may
|
||||
include subdirectories (e.g. <code className="bg-muted px-1 rounded">uploads/photo.jpg</code>).
|
||||
</p>
|
||||
<DocCodeBlock code={`curl "${exampleUrl}" -H "Authorization: Bearer YOUR_TOKEN"`} height="h-24" />
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
For create/update with file fields, send <code className="bg-muted px-1 rounded">multipart/form-data</code>{" "}
|
||||
instead of JSON. Non-file fields are sent as form fields alongside file parts.
|
||||
</p>
|
||||
</div>
|
||||
</DocCollapsibleSection>
|
||||
)
|
||||
}
|
||||
|
||||
function RealtimeDocCard({ entityName }: { entityName: string }) {
|
||||
const baseUrl = getApiBaseUrl()
|
||||
const wsBase = baseUrl.replace(/^http/, "ws")
|
||||
const sampleRowId = "019c1b81-364b-7000-8120-b5416b2c42c2"
|
||||
|
||||
const connectExample = `# Connect to SSE: subscribe to this entity (all rows) and/or a specific row
|
||||
# Topics: entity name only, or entity:row_id for a single row
|
||||
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
"${baseUrl}/api/v1/realtime?topics=${entityName}"
|
||||
|
||||
# Subscribe to entity + a specific row (comma-separated)
|
||||
const sseConnectExample = `# SSE — subscribe to this entity and/or a specific row
|
||||
curl -N -H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
"${baseUrl}/api/v1/realtime?topics=${entityName},${entityName}:${sampleRowId}"`
|
||||
|
||||
const updateTopicsExample = `# Update topics for an existing SSE session (from the "connected" event client_id)
|
||||
const sseUpdateExample = `# Update topics for an existing SSE session (client_id from the "connected" event)
|
||||
curl -X POST "${baseUrl}/api/v1/realtime" \\
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
@@ -126,86 +466,160 @@ curl -X POST "${baseUrl}/api/v1/realtime" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"client_id": "sse_1769987962000_0abc1", "topics": []}'`
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
const wsExample = `# WebSocket alternative (disabled when MB_REALTIME_WS=false)
|
||||
# Connect, then send JSON messages to subscribe/unsubscribe
|
||||
wscat -c "${wsBase}/api/v1/realtime/ws" \\
|
||||
-H "Authorization: Bearer YOUR_TOKEN"
|
||||
|
||||
# After connecting, send:
|
||||
{"topics": ["${entityName}", "${entityName}:${sampleRowId}"]}
|
||||
|
||||
# Clear subscriptions:
|
||||
{"topics": []}`
|
||||
|
||||
const changeEventExample = JSON.stringify(
|
||||
{
|
||||
action: "update",
|
||||
entity: entityName,
|
||||
row_id: sampleRowId,
|
||||
topic: `${entityName}:${sampleRowId}`,
|
||||
timestamp: 1737014400,
|
||||
data: { id: sampleRowId, title: "Updated value" },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DocCollapsibleSection
|
||||
icon={<Radio className="h-4 w-4 text-muted-foreground" />}
|
||||
title="Server-Sent Events (SSE)"
|
||||
description="Long-lived HTTP stream. Disabled when MB_REALTIME_SSE=false. Topic = entity name (list access) or entity:row_id (get access)."
|
||||
>
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Connect</h5>
|
||||
<DocCodeBlock code={sseConnectExample} height="h-28" />
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Update topics</h5>
|
||||
<DocCodeBlock code={sseUpdateExample} height="h-44" />
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">Event types</h5>
|
||||
<div className="grid grid-cols-1 gap-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
connected
|
||||
</Badge>
|
||||
<span>Sent once when the stream opens; includes client_id and topics.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
ping
|
||||
</Badge>
|
||||
<span>Keep-alive sent periodically.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
change
|
||||
</Badge>
|
||||
<span>Database change with action, entity, row_id, and data payload.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">change event payload</h5>
|
||||
<DocCodeBlock code={changeEventExample} height="h-36" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In browsers, EventSource cannot send Authorization headers — use fetch() with the same URL and read the body
|
||||
as a stream, or use the WebSocket endpoint below.
|
||||
</p>
|
||||
</DocCollapsibleSection>
|
||||
|
||||
<DocCollapsibleSection
|
||||
icon={<Radio className="h-4 w-4 text-muted-foreground" />}
|
||||
title="WebSocket"
|
||||
description="Alternative to SSE at WS /api/v1/realtime/ws. Disabled when MB_REALTIME_WS=false. Same change payload shape as SSE."
|
||||
>
|
||||
<DocCodeBlock code={wsExample} height="h-44" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
After the WebSocket upgrade, send JSON messages with a topics array. Change events arrive as JSON messages
|
||||
using the same RealtimeChangeEvent shape as SSE change events.
|
||||
</p>
|
||||
</DocCollapsibleSection>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function SimpleEndpointDoc({
|
||||
method,
|
||||
endpoint,
|
||||
description,
|
||||
requestExample,
|
||||
responseExample,
|
||||
errors,
|
||||
nested = false,
|
||||
}: {
|
||||
method: string
|
||||
endpoint: string
|
||||
description: string
|
||||
requestExample: string
|
||||
responseExample: string
|
||||
errors?: Array<{ code: string; message: string }>
|
||||
nested?: boolean
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div
|
||||
className={
|
||||
nested ? "cursor-pointer" : "p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
}
|
||||
>
|
||||
{!nested && <DocEndpointHeader method={method} endpoint={endpoint} description={description} isOpen={isOpen} />}
|
||||
{nested && (
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Badge className={getMethodColor(method)} variant="secondary">
|
||||
{method}
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
)}
|
||||
{nested && <p className="text-sm text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className={nested ? "mt-4 space-y-4" : "border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4"}>
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">Request Example</h5>
|
||||
<DocCodeBlock code={requestExample} />
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">Response Example</h5>
|
||||
<DocCodeBlock code={responseExample} />
|
||||
</div>
|
||||
{errors && errors.length > 0 && <DocErrorList errors={errors} />}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</>
|
||||
)
|
||||
|
||||
if (nested) {
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
{content}
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Radio className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">Realtime (SSE)</span>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Subscribe to database changes for this entity (all rows) or a specific row. Connect via GET, then update topics via POST.
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Connect to SSE</h5>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Open a long-lived SSE stream. Use <code className="bg-muted px-1 rounded">topics</code> query param: entity name (e.g. <code className="bg-muted px-1 rounded">{entityName}</code>) for all rows, or <code className="bg-muted px-1 rounded">{entityName}:row_id</code> for a single row. Multiple topics are comma-separated.
|
||||
</p>
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(connectExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-40">
|
||||
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
|
||||
<code>{connectExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-1">Update topics to monitor</h5>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
POST with <code className="bg-muted px-1 rounded">client_id</code> from the <code className="bg-muted px-1 rounded">connected</code> event and a new <code className="bg-muted px-1 rounded">topics</code> array. Send <code className="bg-muted px-1 rounded">topics: []</code> to disconnect.
|
||||
</p>
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(updateTopicsExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border whitespace-pre">
|
||||
<code>{updateTopicsExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium mb-2">SSE event types</h5>
|
||||
<div className="grid grid-cols-1 gap-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">connected</Badge>
|
||||
<span>Sent once when the stream opens; includes <code className="bg-muted px-1 rounded">client_id</code> and <code className="bg-muted px-1 rounded">topics</code>.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">ping</Badge>
|
||||
<span>Keep-alive sent periodically.</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">change</Badge>
|
||||
<span>Database change: <code className="bg-muted px-1 rounded">action</code> (insert/update/delete), <code className="bg-muted px-1 rounded">entity</code>, <code className="bg-muted px-1 rounded">row_id</code>, <code className="bg-muted px-1 rounded">data</code> (row payload or null for delete).</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
Access uses the same rules as entity <strong>list</strong> (topic = entity name) and <strong>get</strong> (topic = entity:row_id). In browsers, <code className="bg-muted px-1 rounded">EventSource</code> cannot send <code className="bg-muted px-1 rounded">Authorization</code>; use <code className="bg-muted px-1 rounded">fetch()</code> with the same URL and headers, then read the body as a stream to process SSE events.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
{content}
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
@@ -216,37 +630,27 @@ function ApiEndpointCard({
|
||||
description,
|
||||
table,
|
||||
operation,
|
||||
hasFileFields = false,
|
||||
}: {
|
||||
method: string
|
||||
endpoint: string
|
||||
description: string
|
||||
table: TableMetadata
|
||||
operation: string
|
||||
hasFileFields?: boolean
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
|
||||
const getMethodColor = (method: string) => {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
|
||||
case "POST":
|
||||
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
|
||||
case "PATCH":
|
||||
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
|
||||
case "DELETE":
|
||||
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200"
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
}
|
||||
const baseUrl = getApiBaseUrl()
|
||||
|
||||
const generateRequestExample = () => {
|
||||
const baseUrl = getApiBaseUrl()
|
||||
let example = `curl -X ${method} "${baseUrl}${endpoint}"`
|
||||
let url = `${baseUrl}${endpoint}`
|
||||
|
||||
if (operation === "list") {
|
||||
const filter = encodeURIComponent(JSON.stringify({ status: "active" }))
|
||||
url += `?limit=50&after=last_record_id&filter=${filter}`
|
||||
}
|
||||
|
||||
let example = `curl -X ${method} "${url}"`
|
||||
|
||||
if (method !== "GET") {
|
||||
example += ` \\\n -H "Content-Type: application/json"`
|
||||
@@ -255,9 +659,10 @@ function ApiEndpointCard({
|
||||
example += ` \\\n -H "Authorization: Bearer YOUR_TOKEN"`
|
||||
|
||||
if (operation === "create" || operation === "update") {
|
||||
const sampleData: any = {}
|
||||
const sampleData: Record<string, string> = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
if (field.name === "id" || field.name === "created" || field.name === "updated") return
|
||||
if (field.type === "file" || field.type === "files") return
|
||||
if (field.name === "email") {
|
||||
sampleData[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
@@ -268,37 +673,47 @@ function ApiEndpointCard({
|
||||
})
|
||||
|
||||
example += ` \\\n -d '${JSON.stringify(sampleData, null, 2)}'`
|
||||
|
||||
if (hasFileFields) {
|
||||
example += `\n\n# Or use multipart/form-data for file fields:\n# curl -X ${method} "${baseUrl}${endpoint}" \\\n# -H "Authorization: Bearer YOUR_TOKEN" \\\n# -F "title=My post" \\\n# -F "avatar=@/path/to/photo.jpg"`
|
||||
}
|
||||
}
|
||||
|
||||
return example
|
||||
}
|
||||
|
||||
const generateResponseExample = () => {
|
||||
if (operation === "list") {
|
||||
const sampleRecord: any = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
if (field.name === "id") {
|
||||
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
|
||||
} else if (field.name === "created" || field.name === "updated") {
|
||||
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
|
||||
} else if (field.name === "email") {
|
||||
sampleRecord[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
return // Don't include password in response
|
||||
} else {
|
||||
sampleRecord[field.name] = `sample_${field.name}`
|
||||
}
|
||||
})
|
||||
const sampleRecord: Record<string, string> = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
if (field.name === "id") {
|
||||
sampleRecord[field.name] = "019c1b81-364b-7000-8120-b5416b2c42c2"
|
||||
} else if (field.name === "created" || field.name === "updated") {
|
||||
sampleRecord[field.name] = "2026-01-15T10:00:00Z"
|
||||
} else if (field.name === "email") {
|
||||
sampleRecord[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
return
|
||||
} else if (field.type === "file") {
|
||||
sampleRecord[field.name] = "uploads/photo.jpg"
|
||||
} else if (field.type === "files") {
|
||||
sampleRecord[field.name] = "uploads/photo.jpg,uploads/doc.pdf"
|
||||
} else {
|
||||
sampleRecord[field.name] = `sample_${field.name}`
|
||||
}
|
||||
})
|
||||
|
||||
if (operation === "list") {
|
||||
return JSON.stringify(
|
||||
{
|
||||
data: [sampleRecord],
|
||||
pagination: {
|
||||
page: 1,
|
||||
limit: 20,
|
||||
total: 1,
|
||||
pages: 1,
|
||||
status: 200,
|
||||
data: {
|
||||
items: [sampleRecord],
|
||||
items_count: 1,
|
||||
limit: 50,
|
||||
has_more: false,
|
||||
cursor: null,
|
||||
},
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
@@ -306,116 +721,55 @@ function ApiEndpointCard({
|
||||
}
|
||||
|
||||
if (operation === "delete") {
|
||||
return JSON.stringify({ success: true }, null, 2)
|
||||
return JSON.stringify({ status: 200, data: null, error: "" }, null, 2)
|
||||
}
|
||||
|
||||
// Single record response
|
||||
const sampleRecord: any = {}
|
||||
table.schema.fields?.forEach((field) => {
|
||||
if (field.name === "id") {
|
||||
sampleRecord[field.name] = "123e4567-e89b-12d3-a456-426614174000"
|
||||
} else if (field.name === "created" || field.name === "updated") {
|
||||
sampleRecord[field.name] = "2024-01-15T10:00:00Z"
|
||||
} else if (field.name === "email") {
|
||||
sampleRecord[field.name] = "user@example.com"
|
||||
} else if (field.name === "password") {
|
||||
return // Don't include password in response
|
||||
} else {
|
||||
sampleRecord[field.name] = `sample_${field.name}`
|
||||
}
|
||||
})
|
||||
|
||||
return JSON.stringify(sampleRecord, null, 2)
|
||||
const status = operation === "create" ? 201 : 200
|
||||
return JSON.stringify({ status, data: sampleRecord, error: "" }, null, 2)
|
||||
}
|
||||
|
||||
const requestExample = generateRequestExample()
|
||||
const responseExample = generateResponseExample()
|
||||
|
||||
const errors: Array<{ code: string; message: string }> = [
|
||||
{ code: "400", message: "Bad Request — invalid input data" },
|
||||
{ code: "401", message: "Unauthorized — invalid or missing token" },
|
||||
{ code: "403", message: "Forbidden — access denied by entity rules" },
|
||||
{ code: "500", message: "Internal Server Error" },
|
||||
]
|
||||
|
||||
if (operation === "get" || operation === "update" || operation === "delete") {
|
||||
errors.splice(3, 0, { code: "404", message: "Not Found — record does not exist" })
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge className={getMethodColor(method)} variant="secondary">
|
||||
{method}
|
||||
</Badge>
|
||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">{endpoint}</code>
|
||||
{isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2">{description}</p>
|
||||
<DocEndpointHeader method={method} endpoint={endpoint} description={description} isOpen={isOpen} />
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="border-l-2 border-muted ml-4 pl-6 space-y-6 mt-4">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Request Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(requestExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
{operation === "list" && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
Query params: <code className="bg-muted px-1 rounded">limit</code> (1–500, default 50),{" "}
|
||||
<code className="bg-muted px-1 rounded">after</code> (cursor — id of last item from previous page),{" "}
|
||||
<code className="bg-muted px-1 rounded">filter</code> (URL-encoded JSON object of field equality
|
||||
filters). Results ordered by id ascending.
|
||||
</p>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{requestExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
)}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h5 className="font-medium">Response Example</h5>
|
||||
<Button variant="outline" size="sm" onClick={() => copyToClipboard(responseExample)} className="h-8">
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-48">
|
||||
<pre className="bg-muted p-4 rounded text-sm border">
|
||||
<code>{responseExample}</code>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
<h5 className="font-medium mb-2">Request Example</h5>
|
||||
<DocCodeBlock code={requestExample} height={operation === "list" || hasFileFields ? "h-56" : "h-48"} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h5 className="font-medium mb-3">Possible Errors</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
400
|
||||
</Badge>
|
||||
<span>Bad Request - Invalid input data</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
401
|
||||
</Badge>
|
||||
<span>Unauthorized - Invalid or missing token</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
403
|
||||
</Badge>
|
||||
<span>Forbidden - Access denied by rules</span>
|
||||
</div>
|
||||
{(operation === "get" || operation === "update" || operation === "delete") && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
404
|
||||
</Badge>
|
||||
<span>Not Found - Record does not exist</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
500
|
||||
</Badge>
|
||||
<span>Internal Server Error - Server error</span>
|
||||
</div>
|
||||
</div>
|
||||
<h5 className="font-medium mb-2">Response Example</h5>
|
||||
<DocCodeBlock code={responseExample} />
|
||||
</div>
|
||||
<DocErrorList errors={errors} />
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
@@ -9,7 +9,6 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { loginWithPassword } from "@/lib/api"
|
||||
|
||||
const DEMO_EMAIL = "test@test.com"
|
||||
const DEMO_PASSWORD = "123456789"
|
||||
@@ -22,7 +21,7 @@ function isDemoMode(): boolean {
|
||||
}
|
||||
|
||||
interface LoginFormProps {
|
||||
onLogin: (token: string) => void
|
||||
onLogin: (email: string, password: string) => Promise<void>
|
||||
}
|
||||
|
||||
export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
@@ -39,9 +38,7 @@ export function LoginForm({ onLogin }: LoginFormProps) {
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const data = await loginWithPassword(email, password)
|
||||
localStorage.setItem("admin_token", data.token)
|
||||
onLogin(data.token)
|
||||
await onLogin(email, password)
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Invalid email or password")
|
||||
} finally {
|
||||
|
||||
@@ -1,145 +1,20 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertTriangle } from "lucide-react"
|
||||
import { LoginForm } from "@/components/login-form"
|
||||
import { SetupForm } from "@/components/setup-form"
|
||||
import { AdminDashboard } from "@/components/admin-dashboard"
|
||||
import { Toaster } from "@/components/ui/toaster"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { AppStateProvider } from "@/lib/app-state"
|
||||
import { useRouter } from "@/lib/router"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
|
||||
import { Logo } from "./logo"
|
||||
import { AppRouterProvider, AppRoutes } from "@/components/app-routes"
|
||||
|
||||
export default function MainPage() {
|
||||
const [token, setToken] = React.useState<string | null>(null)
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const { route, navigate } = useRouter()
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
|
||||
// Get saved token safely
|
||||
try {
|
||||
const savedToken = localStorage.getItem("admin_token")
|
||||
if (savedToken) {
|
||||
setToken(savedToken)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to get saved token:", error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (mounted) {
|
||||
try {
|
||||
const currentPath = route.path
|
||||
const isSetupRoute = currentPath === "/setup"
|
||||
|
||||
// Setup route doesn't require authentication
|
||||
if (isSetupRoute) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!token && currentPath !== "/login") {
|
||||
navigate("/login", undefined, undefined)
|
||||
} else if (token && currentPath === "/login") {
|
||||
navigate("/entities", undefined, undefined)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle route change:", error)
|
||||
}
|
||||
}
|
||||
}, [token, route.path, mounted, navigate])
|
||||
|
||||
const handleLogin = (newToken: string) => {
|
||||
try {
|
||||
setToken(newToken)
|
||||
navigate("/entities", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle login:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
try {
|
||||
setToken(null)
|
||||
localStorage.removeItem("admin_token")
|
||||
navigate("/login", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle logout:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSetupComplete = () => {
|
||||
try {
|
||||
navigate("/login", undefined, undefined)
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle setup complete:", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isSetupRoute = route.path === "/setup"
|
||||
const setupToken = route.queryParams.token
|
||||
|
||||
// Show error if on setup route but no token provided
|
||||
if (isSetupRoute && !setupToken) {
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
|
||||
<AppStateProvider>
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Logo className="h-12 w-12 text-primary" size={48} />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Setup Access Required</CardTitle>
|
||||
<CardDescription>An access token is required to access the setup page</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Missing Access Token</AlertTitle>
|
||||
<AlertDescription>
|
||||
This page requires an access token to be provided via the query parameter.
|
||||
Please ensure you have a valid setup token in the URL (e.g., /setup?token=your-token-here).
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Toaster />
|
||||
</AppStateProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem storageKey="mantis-admin-theme" disableTransitionOnChange>
|
||||
<AppStateProvider>
|
||||
{isSetupRoute && setupToken ? (
|
||||
<SetupForm token={setupToken} onSetupComplete={handleSetupComplete} />
|
||||
) : route.path === "/login" || !token ? (
|
||||
<LoginForm onLogin={handleLogin} />
|
||||
) : (
|
||||
<AdminDashboard token={token} onLogout={handleLogout} />
|
||||
)}
|
||||
<AppRouterProvider>
|
||||
<AppRoutes />
|
||||
</AppRouterProvider>
|
||||
<Toaster />
|
||||
</AppStateProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
162
components/oauth/create-oauth-provider-dialog.tsx
Normal file
162
components/oauth/create-oauth-provider-dialog.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import {
|
||||
SYS_OAUTH_PROVIDERS_API,
|
||||
getApiClientError,
|
||||
type ApiClient,
|
||||
type OAuthProvider,
|
||||
} from "@/lib/api"
|
||||
|
||||
interface CreateOAuthProviderDialogProps {
|
||||
open: boolean
|
||||
apiClient: ApiClient
|
||||
onClose: () => void
|
||||
onCreated: (provider: OAuthProvider) => void
|
||||
}
|
||||
|
||||
export function CreateOAuthProviderDialog({
|
||||
open,
|
||||
apiClient,
|
||||
onClose,
|
||||
onCreated,
|
||||
}: CreateOAuthProviderDialogProps) {
|
||||
const [name, setName] = React.useState("")
|
||||
const [clientId, setClientId] = React.useState("")
|
||||
const [clientSecret, setClientSecret] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setName("")
|
||||
setClientId("")
|
||||
setClientSecret("")
|
||||
setError("")
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
|
||||
const trimmedName = name.trim()
|
||||
const trimmedClientId = clientId.trim()
|
||||
const trimmedSecret = clientSecret.trim()
|
||||
|
||||
if (!trimmedName || !trimmedClientId || !trimmedSecret) {
|
||||
setError("Name, client ID, and client secret are required")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const created = await apiClient.call<OAuthProvider>(SYS_OAUTH_PROVIDERS_API, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: trimmedName,
|
||||
client_id: trimmedClientId,
|
||||
client_secret: trimmedSecret,
|
||||
}),
|
||||
})
|
||||
|
||||
const apiError = getApiClientError(created)
|
||||
if (apiError) {
|
||||
throw new Error(apiError)
|
||||
}
|
||||
|
||||
if (!created?.id) {
|
||||
throw new Error("Provider was created but no ID was returned")
|
||||
}
|
||||
|
||||
onCreated(created)
|
||||
onClose()
|
||||
} catch (submitError) {
|
||||
console.error("Failed to create OAuth provider:", submitError)
|
||||
setError(submitError instanceof Error ? submitError.message : "Failed to create OAuth provider")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add OAuth Provider</DialogTitle>
|
||||
<DialogDescription>
|
||||
Register a global OAuth provider. Enable it for this entity after creation.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="oauth-provider-name">Provider name</Label>
|
||||
<Input
|
||||
id="oauth-provider-name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="google"
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Used in OAuth routes as <code className="bg-muted px-1 rounded">{`{provider}`}</code> (e.g. google,
|
||||
github).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="oauth-client-id">Client ID</Label>
|
||||
<Input
|
||||
id="oauth-client-id"
|
||||
value={clientId}
|
||||
onChange={(event) => setClientId(event.target.value)}
|
||||
placeholder="your-client-id"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="oauth-client-secret">Client secret</Label>
|
||||
<Input
|
||||
id="oauth-client-secret"
|
||||
type="password"
|
||||
value={clientSecret}
|
||||
onChange={(event) => setClientSecret(event.target.value)}
|
||||
placeholder="your-client-secret"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Creating..." : "Add Provider"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
160
components/oauth/edit-oauth-provider-dialog.tsx
Normal file
160
components/oauth/edit-oauth-provider-dialog.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import {
|
||||
SYS_OAUTH_PROVIDERS_API,
|
||||
getApiClientError,
|
||||
type ApiClient,
|
||||
type OAuthProvider,
|
||||
} from "@/lib/api"
|
||||
|
||||
interface EditOAuthProviderDialogProps {
|
||||
open: boolean
|
||||
provider: OAuthProvider | null
|
||||
apiClient: ApiClient
|
||||
onClose: () => void
|
||||
onUpdated: (provider: OAuthProvider) => void
|
||||
}
|
||||
|
||||
export function EditOAuthProviderDialog({
|
||||
open,
|
||||
provider,
|
||||
apiClient,
|
||||
onClose,
|
||||
onUpdated,
|
||||
}: EditOAuthProviderDialogProps) {
|
||||
const [name, setName] = React.useState("")
|
||||
const [clientId, setClientId] = React.useState("")
|
||||
const [clientSecret, setClientSecret] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && provider) {
|
||||
setName(provider.name ?? "")
|
||||
setClientId(typeof provider.client_id === "string" ? provider.client_id : "")
|
||||
setClientSecret("")
|
||||
setError("")
|
||||
}
|
||||
}, [open, provider])
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
|
||||
if (!provider) {
|
||||
return
|
||||
}
|
||||
|
||||
const trimmedName = name.trim()
|
||||
const trimmedClientId = clientId.trim()
|
||||
const trimmedSecret = clientSecret.trim()
|
||||
|
||||
if (!trimmedName || !trimmedClientId) {
|
||||
setError("Name and client ID are required")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const body: Record<string, string> = {
|
||||
name: trimmedName,
|
||||
client_id: trimmedClientId,
|
||||
}
|
||||
|
||||
if (trimmedSecret) {
|
||||
body.client_secret = trimmedSecret
|
||||
}
|
||||
|
||||
const updated = await apiClient.call<OAuthProvider>(`${SYS_OAUTH_PROVIDERS_API}/${provider.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
const apiError = getApiClientError(updated)
|
||||
if (apiError) {
|
||||
throw new Error(apiError)
|
||||
}
|
||||
|
||||
onUpdated({ ...provider, ...updated, name: trimmedName, client_id: trimmedClientId })
|
||||
onClose()
|
||||
} catch (submitError) {
|
||||
console.error("Failed to update OAuth provider:", submitError)
|
||||
setError(submitError instanceof Error ? submitError.message : "Failed to update OAuth provider")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit OAuth Provider</DialogTitle>
|
||||
<DialogDescription>Update provider credentials. Leave client secret blank to keep the current value.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-oauth-provider-name">Provider name</Label>
|
||||
<Input
|
||||
id="edit-oauth-provider-name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-oauth-client-id">Client ID</Label>
|
||||
<Input
|
||||
id="edit-oauth-client-id"
|
||||
value={clientId}
|
||||
onChange={(event) => setClientId(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-oauth-client-secret">Client secret</Label>
|
||||
<Input
|
||||
id="edit-oauth-client-secret"
|
||||
type="password"
|
||||
value={clientSecret}
|
||||
onChange={(event) => setClientSecret(event.target.value)}
|
||||
placeholder="Leave blank to keep current secret"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading || !provider}>
|
||||
{isLoading ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
389
components/oauth/oauth-entity-panel.tsx
Normal file
389
components/oauth/oauth-entity-panel.tsx
Normal file
@@ -0,0 +1,389 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import {
|
||||
SYS_OAUTH_ENTITY_CONFIG_API,
|
||||
SYS_OAUTH_PROVIDERS_API,
|
||||
SYS_SETTINGS_CONFIG_API,
|
||||
entityOAuthProvidersApi,
|
||||
extractListItems,
|
||||
getApiBaseUrl,
|
||||
getApiClientError,
|
||||
getOAuthProviderId,
|
||||
type ApiClient,
|
||||
type AppSettings,
|
||||
type EntityOAuthProvider,
|
||||
type OAuthEntityConfigResult,
|
||||
type OAuthProvider,
|
||||
} from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { CreateOAuthProviderDialog } from "./create-oauth-provider-dialog"
|
||||
import { EditOAuthProviderDialog } from "./edit-oauth-provider-dialog"
|
||||
|
||||
interface OAuthEntityPanelProps {
|
||||
entityName: string
|
||||
apiClient: ApiClient
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
function isGloballyEnabled(provider: EntityOAuthProvider): boolean {
|
||||
return provider.enabled !== false
|
||||
}
|
||||
|
||||
function isEnabledForEntity(provider: EntityOAuthProvider): boolean {
|
||||
return provider.enabled_for_entity === true
|
||||
}
|
||||
|
||||
function toOAuthProvider(provider: EntityOAuthProvider): OAuthProvider {
|
||||
return {
|
||||
id: getOAuthProviderId(provider),
|
||||
name: provider.name,
|
||||
client_id: provider.client_id,
|
||||
enabled: provider.enabled,
|
||||
}
|
||||
}
|
||||
|
||||
function updateProviderEntityEnabled(
|
||||
providers: EntityOAuthProvider[],
|
||||
providerId: string,
|
||||
enabledForEntity: boolean,
|
||||
): EntityOAuthProvider[] {
|
||||
return providers.map((provider) =>
|
||||
getOAuthProviderId(provider) === providerId ? { ...provider, enabled_for_entity: enabledForEntity } : provider,
|
||||
)
|
||||
}
|
||||
|
||||
export function OAuthEntityPanel({ entityName, apiClient, isActive }: OAuthEntityPanelProps) {
|
||||
const { toast } = useToast()
|
||||
const [providers, setProviders] = React.useState<EntityOAuthProvider[]>([])
|
||||
const [siteDomain, setSiteDomain] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [togglingProviderId, setTogglingProviderId] = React.useState<string | null>(null)
|
||||
const [creating, setCreating] = React.useState(false)
|
||||
const [editingProvider, setEditingProvider] = React.useState<OAuthProvider | null>(null)
|
||||
const [deletingProvider, setDeletingProvider] = React.useState<EntityOAuthProvider | null>(null)
|
||||
|
||||
const loadOAuthConfig = React.useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
|
||||
const [providersResponse, settings] = await Promise.all([
|
||||
apiClient.call<unknown>(entityOAuthProvidersApi(entityName)),
|
||||
apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API).catch(() => null),
|
||||
])
|
||||
|
||||
const providersError = getApiClientError(providersResponse)
|
||||
if (providersError) {
|
||||
throw new Error(providersError)
|
||||
}
|
||||
|
||||
setProviders(extractListItems<EntityOAuthProvider>(providersResponse))
|
||||
|
||||
if (settings?.siteDomain) {
|
||||
setSiteDomain(settings.siteDomain)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load OAuth configuration:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to load OAuth providers.",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [apiClient, entityName, toast])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isActive) {
|
||||
loadOAuthConfig()
|
||||
}
|
||||
}, [isActive, loadOAuthConfig])
|
||||
|
||||
const handleToggleProvider = async (provider: EntityOAuthProvider, enabled: boolean) => {
|
||||
const providerId = getOAuthProviderId(provider)
|
||||
if (!providerId) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Provider ID is missing.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setTogglingProviderId(providerId)
|
||||
|
||||
try {
|
||||
const body = JSON.stringify({
|
||||
entity_name: entityName,
|
||||
provider_id: providerId,
|
||||
})
|
||||
|
||||
const response = await apiClient.call<OAuthEntityConfigResult | null>(SYS_OAUTH_ENTITY_CONFIG_API, {
|
||||
method: enabled ? "POST" : "DELETE",
|
||||
body,
|
||||
})
|
||||
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
if (!enabled && error.toLowerCase().includes("not found")) {
|
||||
setProviders((current) => updateProviderEntityEnabled(current, providerId, false))
|
||||
return
|
||||
}
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
setProviders((current) => updateProviderEntityEnabled(current, providerId, enabled))
|
||||
|
||||
toast({
|
||||
title: enabled ? "OAuth Enabled" : "OAuth Disabled",
|
||||
description: `${provider.name} is ${enabled ? "enabled" : "disabled"} for ${entityName}.`,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update OAuth entity config:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: `Failed to ${enabled ? "enable" : "disable"} ${provider.name}.`,
|
||||
})
|
||||
await loadOAuthConfig()
|
||||
} finally {
|
||||
setTogglingProviderId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleProviderCreated = async (_provider: OAuthProvider) => {
|
||||
toast({
|
||||
title: "Provider Added",
|
||||
description: `"${_provider.name}" was registered. Enable it for this entity when ready.`,
|
||||
})
|
||||
await loadOAuthConfig()
|
||||
}
|
||||
|
||||
const handleProviderUpdated = async (provider: OAuthProvider) => {
|
||||
toast({
|
||||
title: "Provider Updated",
|
||||
description: `"${provider.name}" settings were saved.`,
|
||||
})
|
||||
await loadOAuthConfig()
|
||||
}
|
||||
|
||||
const handleDeleteProvider = async () => {
|
||||
if (!deletingProvider) {
|
||||
return
|
||||
}
|
||||
|
||||
const providerId = getOAuthProviderId(deletingProvider)
|
||||
|
||||
try {
|
||||
const response = await apiClient.call(`${SYS_OAUTH_PROVIDERS_API}/${providerId}`, {
|
||||
method: "DELETE",
|
||||
})
|
||||
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Provider Removed",
|
||||
description: `"${deletingProvider.name}" was deleted from the global registry.`,
|
||||
})
|
||||
await loadOAuthConfig()
|
||||
} catch (error) {
|
||||
console.error("Failed to delete OAuth provider:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to delete OAuth provider.",
|
||||
})
|
||||
} finally {
|
||||
setDeletingProvider(null)
|
||||
}
|
||||
}
|
||||
|
||||
const baseUrl = siteDomain || getApiBaseUrl()
|
||||
const callbackExample = `${baseUrl.replace(/\/+$/, "")}/api/v1/auth/${entityName}/oauth/callback/google`
|
||||
const enabledCount = providers.filter(isEnabledForEntity).length
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<Label className="text-base font-medium">OAuth Providers</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isLoading && providers.length === 0
|
||||
? "Loading OAuth configuration..."
|
||||
: `${enabledCount} of ${providers.length} provider${providers.length === 1 ? "" : "s"} enabled for this entity`}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setCreating(true)} disabled={isLoading}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground space-y-2">
|
||||
<p>
|
||||
Register OAuth providers, then enable them for this auth entity. User login requires the provider to be
|
||||
globally enabled and enabled for this entity.
|
||||
</p>
|
||||
<p>
|
||||
Users sign in via{" "}
|
||||
<code className="bg-background px-1 rounded text-xs">/auth/{entityName}/oauth/authorize/{"{provider}"}</code>.
|
||||
</p>
|
||||
<p>
|
||||
<strong className="text-foreground">Callback URL pattern:</strong>{" "}
|
||||
<code className="bg-background px-1 rounded text-xs break-all">{callbackExample}</code>
|
||||
</p>
|
||||
{!siteDomain && (
|
||||
<p>
|
||||
Set <strong className="text-foreground">Site Domain</strong> in Settings for accurate OAuth redirect URLs
|
||||
in production.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Provider</TableHead>
|
||||
<TableHead>Client ID</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Enabled for entity</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading && providers.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground">
|
||||
Loading OAuth providers...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : providers.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground">
|
||||
No OAuth providers registered yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
providers.map((provider) => {
|
||||
const providerId = getOAuthProviderId(provider)
|
||||
const enabledForEntity = isEnabledForEntity(provider)
|
||||
const globallyEnabled = isGloballyEnabled(provider)
|
||||
const isToggling = togglingProviderId === providerId
|
||||
|
||||
return (
|
||||
<TableRow key={providerId || provider.name}>
|
||||
<TableCell className="font-medium">{provider.name}</TableCell>
|
||||
<TableCell className="font-mono text-sm">
|
||||
{typeof provider.client_id === "string" ? provider.client_id : "—"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{globallyEnabled ? (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Global
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
Global off
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={enabledForEntity}
|
||||
disabled={isToggling || isLoading || !providerId || !globallyEnabled}
|
||||
onCheckedChange={(checked) => handleToggleProvider(provider, checked)}
|
||||
aria-label={`Enable ${provider.name} for ${entityName}`}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditingProvider(toOAuthProvider(provider))}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => setDeletingProvider(provider)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<CreateOAuthProviderDialog
|
||||
open={creating}
|
||||
apiClient={apiClient}
|
||||
onClose={() => setCreating(false)}
|
||||
onCreated={handleProviderCreated}
|
||||
/>
|
||||
|
||||
<EditOAuthProviderDialog
|
||||
open={!!editingProvider}
|
||||
provider={editingProvider}
|
||||
apiClient={apiClient}
|
||||
onClose={() => setEditingProvider(null)}
|
||||
onUpdated={handleProviderUpdated}
|
||||
/>
|
||||
|
||||
<AlertDialog open={!!deletingProvider} onOpenChange={(open) => !open && setDeletingProvider(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete OAuth Provider</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Remove <span className="font-medium text-foreground">{deletingProvider?.name}</span> from the global
|
||||
registry? This removes it from all entities and cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProvider}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,129 +1,226 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, Save } from "lucide-react"
|
||||
import { Mail, RefreshCw, Save } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import type { ApiClient, AppSettings } from "@/lib/api"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import {
|
||||
SYS_SETTINGS_CONFIG_API,
|
||||
type ApiClient,
|
||||
type AppSettings,
|
||||
type SmtpConfig,
|
||||
} from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAppState, type AppMode } from "@/lib/app-state"
|
||||
import { SmtpTestDialog } from "./smtp-test-dialog"
|
||||
|
||||
interface SettingsSectionProps {
|
||||
apiClient: ApiClient
|
||||
settings: AppSettings | null
|
||||
onSettingsUpdate: (settings: AppSettings) => void
|
||||
onModeChange: (mode: AppMode, baseUrl?: string) => void
|
||||
}
|
||||
|
||||
export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeChange }: SettingsSectionProps) {
|
||||
type SettingsCard = "general" | "file" | "features" | "smtp"
|
||||
|
||||
const BYTES_PER_MB = 1024 * 1024
|
||||
|
||||
function corsOriginsToText(origins: string[]): string {
|
||||
return origins.join("\n")
|
||||
}
|
||||
|
||||
function textToCorsOrigins(text: string): string[] {
|
||||
return text.split("\n").map((line) => line.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
function smtpEqual(a: SmtpConfig, b: SmtpConfig, ignorePassword = false): boolean {
|
||||
return (
|
||||
a.host === b.host &&
|
||||
a.port === b.port &&
|
||||
a.user === b.user &&
|
||||
a.from === b.from &&
|
||||
a.tls === b.tls &&
|
||||
(ignorePassword || a.password === b.password)
|
||||
)
|
||||
}
|
||||
|
||||
export function SettingsSection({ apiClient }: SettingsSectionProps) {
|
||||
const { toast } = useToast()
|
||||
const { mode, setMode } = useAppState()
|
||||
const [formData, setFormData] = React.useState<AppSettings | null>(null)
|
||||
const [originalData, setOriginalData] = React.useState<AppSettings | null>(null)
|
||||
const [corsOriginsText, setCorsOriginsText] = React.useState("")
|
||||
const [originalCorsOriginsText, setOriginalCorsOriginsText] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState<Record<string, boolean>>({})
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
||||
const [isBootstrapping, setIsBootstrapping] = React.useState(true)
|
||||
const [smtpTestOpen, setSmtpTestOpen] = React.useState(false)
|
||||
|
||||
const applySettings = React.useCallback((settings: AppSettings) => {
|
||||
const normalized: AppSettings = {
|
||||
...settings,
|
||||
corsAllowedOrigins: settings.corsAllowedOrigins ?? [],
|
||||
smtp: {
|
||||
host: "",
|
||||
port: 587,
|
||||
user: "",
|
||||
password: "",
|
||||
from: "",
|
||||
tls: true,
|
||||
...settings.smtp,
|
||||
},
|
||||
}
|
||||
const corsText = corsOriginsToText(normalized.corsAllowedOrigins)
|
||||
setFormData(normalized)
|
||||
setOriginalData(normalized)
|
||||
setCorsOriginsText(corsText)
|
||||
setOriginalCorsOriginsText(corsText)
|
||||
}, [])
|
||||
|
||||
const loadSettings = React.useCallback(async () => {
|
||||
const settings = await apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API)
|
||||
applySettings(settings)
|
||||
return settings
|
||||
}, [apiClient, applySettings])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (settings) {
|
||||
const data = { ...settings, mode }
|
||||
setFormData(data)
|
||||
setOriginalData(data)
|
||||
}
|
||||
}, [settings, mode])
|
||||
let cancelled = false
|
||||
|
||||
// Track changes per card section
|
||||
const getCardChanges = (cardType: "general" | "file" | "features"): boolean => {
|
||||
const bootstrap = async () => {
|
||||
try {
|
||||
await loadSettings()
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
console.error("Failed to load settings:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to load settings. Please try again.",
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsBootstrapping(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bootstrap()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [loadSettings, toast])
|
||||
|
||||
const getCardChanges = (cardType: SettingsCard): boolean => {
|
||||
if (!formData || !originalData) return false
|
||||
|
||||
|
||||
if (cardType === "general") {
|
||||
return (
|
||||
formData.appName !== originalData.appName ||
|
||||
formData.baseUrl !== originalData.baseUrl
|
||||
formData.orgName !== originalData.orgName ||
|
||||
formData.siteDomain !== originalData.siteDomain ||
|
||||
corsOriginsText !== originalCorsOriginsText
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (cardType === "file") {
|
||||
return (
|
||||
formData.maxFileSize !== originalData.maxFileSize ||
|
||||
formData.logRetentionDays !== originalData.logRetentionDays ||
|
||||
formData.sessionTimeout !== originalData.sessionTimeout ||
|
||||
formData.adminSessionTimeout !== originalData.adminSessionTimeout
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (cardType === "features") {
|
||||
return (
|
||||
formData.maintenanceMode !== originalData.maintenanceMode ||
|
||||
formData.allowRegistration !== originalData.allowRegistration ||
|
||||
formData.emailVerificationRequired !== originalData.emailVerificationRequired
|
||||
formData.disableAdminRegistration !== originalData.disableAdminRegistration ||
|
||||
formData.disableSchemaMutations !== originalData.disableSchemaMutations ||
|
||||
formData.emailVerificationRequired !== originalData.emailVerificationRequired ||
|
||||
formData.jwtEnableSetIssuer !== originalData.jwtEnableSetIssuer ||
|
||||
formData.jwtEnableSetAudience !== originalData.jwtEnableSetAudience
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (cardType === "smtp") {
|
||||
return !smtpEqual(formData.smtp, originalData.smtp)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const resetCardChanges = (cardType: "general" | "file" | "features") => {
|
||||
if (!formData || !originalData) return
|
||||
|
||||
const buildPatchPayload = (cardType: SettingsCard): Partial<AppSettings> => {
|
||||
if (!formData) return {}
|
||||
|
||||
if (cardType === "general") {
|
||||
setFormData({
|
||||
...formData,
|
||||
appName: originalData.appName,
|
||||
baseUrl: originalData.baseUrl,
|
||||
})
|
||||
return {
|
||||
orgName: formData.orgName,
|
||||
siteDomain: formData.siteDomain,
|
||||
corsAllowedOrigins: textToCorsOrigins(corsOriginsText),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (cardType === "file") {
|
||||
setFormData({
|
||||
...formData,
|
||||
maxFileSize: originalData.maxFileSize,
|
||||
sessionTimeout: originalData.sessionTimeout,
|
||||
adminSessionTimeout: originalData.adminSessionTimeout,
|
||||
})
|
||||
return {
|
||||
maxFileSize: formData.maxFileSize,
|
||||
logRetentionDays: formData.logRetentionDays,
|
||||
sessionTimeout: formData.sessionTimeout,
|
||||
adminSessionTimeout: formData.adminSessionTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (cardType === "features") {
|
||||
setFormData({
|
||||
...formData,
|
||||
maintenanceMode: originalData.maintenanceMode,
|
||||
allowRegistration: originalData.allowRegistration,
|
||||
emailVerificationRequired: originalData.emailVerificationRequired,
|
||||
})
|
||||
return {
|
||||
disableAdminRegistration: formData.disableAdminRegistration,
|
||||
disableSchemaMutations: formData.disableSchemaMutations,
|
||||
emailVerificationRequired: formData.emailVerificationRequired,
|
||||
jwtEnableSetIssuer: formData.jwtEnableSetIssuer,
|
||||
jwtEnableSetAudience: formData.jwtEnableSetAudience,
|
||||
}
|
||||
}
|
||||
|
||||
const smtpPatch: Partial<SmtpConfig> = {
|
||||
host: formData.smtp.host,
|
||||
port: formData.smtp.port,
|
||||
user: formData.smtp.user,
|
||||
from: formData.smtp.from,
|
||||
tls: formData.smtp.tls,
|
||||
}
|
||||
|
||||
if (formData.smtp.password.length > 0) {
|
||||
smtpPatch.password = formData.smtp.password
|
||||
}
|
||||
|
||||
return { smtp: smtpPatch as SmtpConfig }
|
||||
}
|
||||
|
||||
const handleInputChange = (field: keyof AppSettings, value: any) => {
|
||||
const handleInputChange = <K extends keyof AppSettings>(field: K, value: AppSettings[K]) => {
|
||||
if (!formData) return
|
||||
setFormData({ ...formData, [field]: value })
|
||||
}
|
||||
|
||||
const handleSmtpChange = <K extends keyof SmtpConfig>(field: K, value: SmtpConfig[K]) => {
|
||||
if (!formData) return
|
||||
setFormData({
|
||||
...formData,
|
||||
[field]: value,
|
||||
smtp: { ...formData.smtp, [field]: value },
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = async (cardType: "general" | "file" | "features") => {
|
||||
const handleSave = async (cardType: SettingsCard) => {
|
||||
if (!formData) return
|
||||
|
||||
setIsLoading({ ...isLoading, [cardType]: true })
|
||||
setIsLoading((prev) => ({ ...prev, [cardType]: true }))
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config", {
|
||||
const updatedSettings = await apiClient.call<AppSettings>(SYS_SETTINGS_CONFIG_API, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(formData),
|
||||
body: JSON.stringify(buildPatchPayload(cardType)),
|
||||
})
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedSettings?.error?.length > 0) throw updatedSettings.error
|
||||
|
||||
const data = { ...updatedSettings, mode }
|
||||
setFormData(data)
|
||||
setOriginalData(data)
|
||||
onSettingsUpdate(updatedSettings)
|
||||
applySettings(updatedSettings)
|
||||
|
||||
toast({
|
||||
title: "Settings Saved",
|
||||
description: `${cardType.charAt(0).toUpperCase() + cardType.slice(1)} settings have been updated successfully.`,
|
||||
description: `${cardType.charAt(0).toUpperCase()}${cardType.slice(1)} settings have been updated successfully.`,
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -134,32 +231,56 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
description: "Failed to save settings. Please try again.",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading({ ...isLoading, [cardType]: false })
|
||||
setIsLoading((prev) => ({ ...prev, [cardType]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const updatedSettings = await apiClient.call<AppSettings>("/api/v1/settings/config")
|
||||
|
||||
// If the request failed, throw the error here
|
||||
if (updatedSettings?.error?.length > 0) throw updatedSettings.error
|
||||
|
||||
onSettingsUpdate(updatedSettings)
|
||||
await loadSettings()
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh settings:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Failed to refresh settings. Please try again.",
|
||||
})
|
||||
} finally {
|
||||
setIsRefreshing(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Show loading if we don't have formData yet
|
||||
if (!formData) {
|
||||
const renderSaveButton = (cardType: SettingsCard) => {
|
||||
if (!getCardChanges(cardType)) return null
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave(cardType)}
|
||||
disabled={isLoading[cardType]}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading[cardType] ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
if (isBootstrapping || !formData) {
|
||||
return (
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"></div>
|
||||
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
|
||||
<p className="text-muted-foreground">Loading settings...</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -168,11 +289,18 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
|
||||
return (
|
||||
<div className="space-y-8 p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Settings</h1>
|
||||
<p className="text-muted-foreground">Manage your application configuration and preferences</p>
|
||||
<p className="text-muted-foreground">
|
||||
Manage your application configuration and preferences
|
||||
{formData.mantisVersion ? (
|
||||
<>
|
||||
{" "}
|
||||
· Server <span className="font-mono text-foreground">{formData.mantisVersion}</span>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="icon" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
|
||||
@@ -180,213 +308,280 @@ export function SettingsSection({ apiClient, settings, onSettingsUpdate, onModeC
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* General Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>General</CardTitle>
|
||||
<CardDescription>Basic application information and configuration</CardDescription>
|
||||
<CardDescription>Organization details, public site URL, and CORS origins</CardDescription>
|
||||
</div>
|
||||
{getCardChanges("general") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("general")}
|
||||
disabled={isLoading.general}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.general ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{renderSaveButton("general")}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="app-name">Application Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={formData?.appName || ""}
|
||||
onChange={(e) => handleInputChange("appName", e.target.value)}
|
||||
placeholder="My Application"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="version">Version</Label>
|
||||
<Input
|
||||
id="version"
|
||||
value={formData?.mantisVersion || ""}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="base-url">Base URL</Label>
|
||||
<Label htmlFor="org-name">Organization Name</Label>
|
||||
<Input
|
||||
id="base-url"
|
||||
value={formData?.baseUrl || ""}
|
||||
onChange={(e) => handleInputChange("baseUrl", e.target.value)}
|
||||
placeholder="https://your-api-domain.com"
|
||||
id="org-name"
|
||||
value={formData.orgName}
|
||||
onChange={(e) => handleInputChange("orgName", e.target.value)}
|
||||
placeholder="ACME Corp"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{mode === "PROD"
|
||||
? "The base URL for your API endpoints in production mode"
|
||||
: "Not used in test mode - API calls go to external server"}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="site-domain">Site Domain</Label>
|
||||
<Input
|
||||
id="site-domain"
|
||||
value={formData.siteDomain}
|
||||
onChange={(e) => handleInputChange("siteDomain", e.target.value)}
|
||||
placeholder="https://acme.example.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cors-origins">CORS Allowed Origins</Label>
|
||||
<Textarea
|
||||
id="cors-origins"
|
||||
value={corsOriginsText}
|
||||
onChange={(e) => setCorsOriginsText(e.target.value)}
|
||||
placeholder={"http://localhost:3000\nhttp://127.0.0.1:3000"}
|
||||
rows={4}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">Enter one origin per line.</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* File & Session Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>File & Sessions</CardTitle>
|
||||
<CardDescription>Configure file upload limits and session timeouts</CardDescription>
|
||||
<CardDescription>Upload limits, log retention, and session timeouts</CardDescription>
|
||||
</div>
|
||||
{getCardChanges("file") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("file")}
|
||||
disabled={isLoading.file}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.file ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{renderSaveButton("file")}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
|
||||
<Input
|
||||
id="max-file-size"
|
||||
type="number"
|
||||
value={formData?.maxFileSize?.toString() || 10}
|
||||
onChange={(e) => handleInputChange("maxFileSize", Number.parseInt(e.target.value) || 10)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="session-timeout">Session Timeout (s)</Label>
|
||||
<Input
|
||||
id="session-timeout"
|
||||
type="number"
|
||||
value={formData?.sessionTimeout?.toString() || 86400}
|
||||
onChange={(e) => handleInputChange("sessionTimeout", Number.parseInt(e.target.value) || 86400)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="admin-session-timeout">Admin Session (s)</Label>
|
||||
<Input
|
||||
id="admin-session-timeout"
|
||||
type="number"
|
||||
value={formData?.adminSessionTimeout?.toString() || 3600}
|
||||
onChange={(e) => handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value) || 3600)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-file-size">Max File Size (MB)</Label>
|
||||
<Input
|
||||
id="max-file-size"
|
||||
type="number"
|
||||
value={Math.round(formData.maxFileSize / BYTES_PER_MB)}
|
||||
onChange={(e) =>
|
||||
handleInputChange(
|
||||
"maxFileSize",
|
||||
(Number.parseInt(e.target.value, 10) || 1) * BYTES_PER_MB,
|
||||
)
|
||||
}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="log-retention-days">Log Retention (days)</Label>
|
||||
<Input
|
||||
id="log-retention-days"
|
||||
type="number"
|
||||
value={formData.logRetentionDays}
|
||||
onChange={(e) =>
|
||||
handleInputChange("logRetentionDays", Number.parseInt(e.target.value, 10) || 1)
|
||||
}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="session-timeout">Session Timeout (s)</Label>
|
||||
<Input
|
||||
id="session-timeout"
|
||||
type="number"
|
||||
value={formData.sessionTimeout}
|
||||
onChange={(e) =>
|
||||
handleInputChange("sessionTimeout", Number.parseInt(e.target.value, 10) || 1)
|
||||
}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="admin-session-timeout">Admin Session (s)</Label>
|
||||
<Input
|
||||
id="admin-session-timeout"
|
||||
type="number"
|
||||
value={formData.adminSessionTimeout}
|
||||
onChange={(e) =>
|
||||
handleInputChange("adminSessionTimeout", Number.parseInt(e.target.value, 10) || 1)
|
||||
}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Feature Toggles */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Features</CardTitle>
|
||||
<CardDescription>Enable or disable application features</CardDescription>
|
||||
<CardDescription>Registration, schema changes, email verification, and JWT options</CardDescription>
|
||||
</div>
|
||||
{getCardChanges("features") && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSave("features")}
|
||||
disabled={isLoading.features}
|
||||
className="gap-2"
|
||||
>
|
||||
{isLoading.features ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{renderSaveButton("features")}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Maintenance Mode</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Temporarily disable access to the application
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.maintenanceMode || false}
|
||||
onCheckedChange={(checked) => handleInputChange("maintenanceMode", checked)}
|
||||
/>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Disable Admin Registration</Label>
|
||||
<p className="text-sm text-muted-foreground">Prevent creation of new admin accounts</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.disableAdminRegistration}
|
||||
onCheckedChange={(checked) => handleInputChange("disableAdminRegistration", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Allow Registration</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Allow new users to create accounts
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.allowRegistration || false}
|
||||
onCheckedChange={(checked) => handleInputChange("allowRegistration", checked)}
|
||||
/>
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Disable Schema Mutations</Label>
|
||||
<p className="text-sm text-muted-foreground">Block create, update, and delete operations on schemas</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.disableSchemaMutations}
|
||||
onCheckedChange={(checked) => handleInputChange("disableSchemaMutations", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Email Verification</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Require email verification for new accounts
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData?.emailVerificationRequired || false}
|
||||
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Email Verification Required</Label>
|
||||
<p className="text-sm text-muted-foreground">Require email verification for new accounts</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.emailVerificationRequired}
|
||||
onCheckedChange={(checked) => handleInputChange("emailVerificationRequired", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">JWT Set Issuer</Label>
|
||||
<p className="text-sm text-muted-foreground">Include issuer claim when signing JWTs</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.jwtEnableSetIssuer}
|
||||
onCheckedChange={(checked) => handleInputChange("jwtEnableSetIssuer", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">JWT Set Audience</Label>
|
||||
<p className="text-sm text-muted-foreground">Include audience claim when signing JWTs</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.jwtEnableSetAudience}
|
||||
onCheckedChange={(checked) => handleInputChange("jwtEnableSetAudience", checked)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle>SMTP</CardTitle>
|
||||
<CardDescription>Outbound email delivery configuration</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSmtpTestOpen(true)}
|
||||
className="gap-2"
|
||||
>
|
||||
<Mail className="h-4 w-4" />
|
||||
Test SMTP
|
||||
</Button>
|
||||
{renderSaveButton("smtp")}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="smtp-host">Host</Label>
|
||||
<Input
|
||||
id="smtp-host"
|
||||
value={formData.smtp.host}
|
||||
onChange={(e) => handleSmtpChange("host", e.target.value)}
|
||||
placeholder="smtp.example.com"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="smtp-port">Port</Label>
|
||||
<Input
|
||||
id="smtp-port"
|
||||
type="number"
|
||||
value={formData.smtp.port}
|
||||
onChange={(e) => handleSmtpChange("port", Number.parseInt(e.target.value, 10) || 587)}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="smtp-user">Username</Label>
|
||||
<Input
|
||||
id="smtp-user"
|
||||
value={formData.smtp.user}
|
||||
onChange={(e) => handleSmtpChange("user", e.target.value)}
|
||||
placeholder="smtp-user"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="smtp-password">Password</Label>
|
||||
<Input
|
||||
id="smtp-password"
|
||||
type="password"
|
||||
value={formData.smtp.password}
|
||||
onChange={(e) => handleSmtpChange("password", e.target.value)}
|
||||
placeholder="Leave blank to keep current password"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 sm:col-span-2">
|
||||
<Label htmlFor="smtp-from">From Address</Label>
|
||||
<Input
|
||||
id="smtp-from"
|
||||
value={formData.smtp.from}
|
||||
onChange={(e) => handleSmtpChange("from", e.target.value)}
|
||||
placeholder="noreply@example.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base">Use TLS</Label>
|
||||
<p className="text-sm text-muted-foreground">Enable TLS for SMTP connections</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.smtp.tls}
|
||||
onCheckedChange={(checked) => handleSmtpChange("tls", checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Test SMTP uses the configuration already saved on the server. Save any changes before testing.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<SmtpTestDialog open={smtpTestOpen} apiClient={apiClient} onClose={() => setSmtpTestOpen(false)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
133
components/settings/smtp-test-dialog.tsx
Normal file
133
components/settings/smtp-test-dialog.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Mail } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import {
|
||||
SYS_SETTINGS_SMTP_TEST_API,
|
||||
getApiClientError,
|
||||
type ApiClient,
|
||||
type SmtpTestResult,
|
||||
} from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface SmtpTestDialogProps {
|
||||
open: boolean
|
||||
apiClient: ApiClient
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function isValidEmail(value: string): boolean {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
|
||||
}
|
||||
|
||||
export function SmtpTestDialog({ open, apiClient, onClose }: SmtpTestDialogProps) {
|
||||
const { toast } = useToast()
|
||||
const [email, setEmail] = React.useState("")
|
||||
const [isLoading, setIsLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState("")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setEmail("")
|
||||
setError("")
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
|
||||
const trimmed = email.trim()
|
||||
if (!trimmed || !isValidEmail(trimmed)) {
|
||||
setError("Enter a valid email address")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
const result = await apiClient.call<SmtpTestResult>(SYS_SETTINGS_SMTP_TEST_API, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
})
|
||||
|
||||
const apiError = getApiClientError(result)
|
||||
if (apiError) {
|
||||
throw new Error(apiError)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Test Email Sent",
|
||||
description: result?.message || `A test message was sent to ${trimmed}.`,
|
||||
duration: 5000,
|
||||
})
|
||||
onClose()
|
||||
} catch (submitError) {
|
||||
console.error("Failed to send SMTP test email:", submitError)
|
||||
setError(submitError instanceof Error ? submitError.message : "Failed to send test email")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5" />
|
||||
Send Test Email
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Sends a message using the SMTP settings already saved on the server. Unsaved form changes are not used.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="smtp-test-email">Recipient email</Label>
|
||||
<Input
|
||||
id="smtp-test-email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Limited to 3 test messages per recipient per hour.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{isLoading ? "Sending..." : "Send Test Email"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -32,9 +32,9 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
|
||||
const apiClient = React.useMemo(() => {
|
||||
return new ApiClient(
|
||||
token,
|
||||
() => {},
|
||||
(error) => setError(error)
|
||||
(error) => setError(error),
|
||||
token,
|
||||
)
|
||||
}, [token])
|
||||
|
||||
@@ -57,7 +57,7 @@ export function SetupForm({ token, onSetupComplete }: SetupFormProps) {
|
||||
|
||||
try {
|
||||
// Create admin account using the setup token
|
||||
const response: any = await apiClient.call("/api/v1/auth/setup/admin", {
|
||||
const response: any = await apiClient.call("/api/v1/sys/admins/setup", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
|
||||
@@ -44,7 +44,7 @@ const TabsContent = React.forwardRef<
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-[state=inactive]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
294
lib/api.ts
294
lib/api.ts
@@ -1,9 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import type { AppMode } from "./app-state"
|
||||
|
||||
|
||||
// Updated interfaces to match the API response format
|
||||
export interface FieldConstraints {
|
||||
default_value: any
|
||||
max_value: number | null
|
||||
@@ -25,6 +21,7 @@ export interface TableField {
|
||||
required: boolean
|
||||
system: boolean
|
||||
type: string
|
||||
precision?: string | null
|
||||
unique: boolean
|
||||
constraints: FieldConstraints
|
||||
foreign_key?: ForeignKeyConfig // optional foreign key configuration
|
||||
@@ -71,6 +68,161 @@ export interface Admin {
|
||||
/** System admin REST API (list, CRUD). Login: `${SYS_ADMINS_API}/login`. */
|
||||
export const SYS_ADMINS_API = "/api/v1/sys/admins" as const
|
||||
|
||||
/** Application settings (GET/PATCH). */
|
||||
export const SYS_SETTINGS_CONFIG_API = "/api/v1/sys/settings/config" as const
|
||||
|
||||
/** Send a test email using the saved SMTP configuration. */
|
||||
export const SYS_SETTINGS_SMTP_TEST_API = "/api/v1/sys/settings/smtp/test" as const
|
||||
|
||||
/** Admin API keys (list, create, update, revoke). */
|
||||
export const SYS_API_KEYS_API = "/api/v1/sys/api-keys" as const
|
||||
|
||||
/** OAuth provider registry (list, create, update, remove). */
|
||||
export const SYS_OAUTH_PROVIDERS_API = "/api/v1/sys/oauth/providers" as const
|
||||
|
||||
/** Enable or disable OAuth providers per auth entity. */
|
||||
export const SYS_OAUTH_ENTITY_CONFIG_API = "/api/v1/sys/oauth/entity-config" as const
|
||||
|
||||
export interface AdminApiKey {
|
||||
id: string
|
||||
entity_name: string
|
||||
user_id: string
|
||||
label: string
|
||||
permissions: unknown[]
|
||||
last_used: string | null
|
||||
created: string
|
||||
expires_at: string | null
|
||||
}
|
||||
|
||||
export interface AdminApiKeyCreated extends AdminApiKey {
|
||||
key: string
|
||||
}
|
||||
|
||||
export interface AdminApiKeyCreateRequest {
|
||||
user_id: string
|
||||
label?: string
|
||||
permissions?: unknown[]
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
export interface ApiKeyUser {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Entity auth user API keys (list, create, revoke). */
|
||||
export function entityApiKeysApi(entityName: string): string {
|
||||
return `/api/v1/auth/${encodeURIComponent(entityName)}/api-keys`
|
||||
}
|
||||
|
||||
/** OAuth providers enabled for an auth entity (public list). */
|
||||
export function entityOAuthProvidersApi(entityName: string): string {
|
||||
return `/api/v1/auth/${encodeURIComponent(entityName)}/oauth/providers`
|
||||
}
|
||||
|
||||
/** Provider row from GET /auth/{entity}/oauth/providers (includes entity enablement). */
|
||||
export interface EntityOAuthProvider {
|
||||
id: string
|
||||
name: string
|
||||
client_id?: string
|
||||
enabled?: boolean
|
||||
enabled_for_entity?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface OAuthProvider {
|
||||
id: string
|
||||
name: string
|
||||
client_id?: string
|
||||
enabled?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface OAuthProviderCreateRequest {
|
||||
name: string
|
||||
client_id: string
|
||||
client_secret: string
|
||||
}
|
||||
|
||||
export interface OAuthProviderUpdateRequest {
|
||||
name?: string
|
||||
client_id?: string
|
||||
client_secret?: string
|
||||
}
|
||||
|
||||
export interface OAuthEntityConfigRequest {
|
||||
entity_name: string
|
||||
provider_id: string
|
||||
}
|
||||
|
||||
export interface OAuthEntityConfigResult {
|
||||
entity_name: string
|
||||
provider_id: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
/** Resolve provider UUID used in entity-config requests. */
|
||||
export function getOAuthProviderId(provider: { id?: string; provider_id?: string }): string {
|
||||
return provider.id ?? provider.provider_id ?? ""
|
||||
}
|
||||
|
||||
/** Build URL to download or display an uploaded entity file. */
|
||||
export function buildEntityFileUrl(entityName: string, fileName: string): string {
|
||||
return `${getApiBaseUrl()}/api/v1/files/${encodeURIComponent(entityName)}/${encodeURIComponent(fileName)}`
|
||||
}
|
||||
|
||||
export interface AdminApiKeyUpdateRequest {
|
||||
label?: string
|
||||
expires_at?: string | null
|
||||
}
|
||||
|
||||
/** Extract list items from direct arrays or paginated API responses. */
|
||||
export function extractListItems<T>(response: unknown): T[] {
|
||||
if (Array.isArray(response)) {
|
||||
return response
|
||||
}
|
||||
|
||||
if (response && typeof response === "object") {
|
||||
const record = response as Record<string, unknown>
|
||||
if (Array.isArray(record.items)) {
|
||||
return record.items as T[]
|
||||
}
|
||||
|
||||
const data = record.data
|
||||
if (Array.isArray(data)) {
|
||||
return data as T[]
|
||||
}
|
||||
if (data && typeof data === "object") {
|
||||
const nested = data as Record<string, unknown>
|
||||
if (Array.isArray(nested.items)) {
|
||||
return nested.items as T[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
/** Detect error objects returned by ApiClient.call's catch handler. */
|
||||
export function getApiClientError(response: unknown): string | null {
|
||||
if (!response || typeof response !== "object") {
|
||||
return null
|
||||
}
|
||||
|
||||
const record = response as { error?: unknown; status?: unknown }
|
||||
if (typeof record.error === "string" && record.error.length > 0) {
|
||||
const status = typeof record.status === "number" ? record.status : 0
|
||||
if (status >= 400 || status <= 0) {
|
||||
return record.error
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** HttpOnly cookie name set by the MantisBase backend on admin login/refresh; cleared on logout. */
|
||||
export const ADMIN_SESSION_COOKIE = "admin_token" as const
|
||||
|
||||
/** Backend API base URL. Override with NEXT_PUBLIC_MANTIS_BASE_URL (e.g. https://api.example.com) to use an external backend. */
|
||||
export function getApiBaseUrl(): string {
|
||||
const override = process.env.NEXT_PUBLIC_MANTIS_BASE_URL
|
||||
@@ -78,31 +230,49 @@ export function getApiBaseUrl(): string {
|
||||
return override.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
const mode = process?.env?.NODE_ENV || "production"
|
||||
const port = process?.env?.MANTIS_PORT || 7070
|
||||
|
||||
if (mode === "development") {
|
||||
return `http://localhost:${port}`
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
return `http://localhost:${port}`
|
||||
const port = process?.env?.MANTIS_PORT || 7070
|
||||
return `http://127.0.0.1:${port}`
|
||||
}
|
||||
|
||||
export interface SmtpConfig {
|
||||
host: string
|
||||
port: number
|
||||
user: string
|
||||
password: string
|
||||
from: string
|
||||
tls: boolean
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
allowRegistration: boolean
|
||||
appName: string
|
||||
baseUrl: string
|
||||
orgName: string
|
||||
siteDomain: string
|
||||
corsAllowedOrigins: string[]
|
||||
maxFileSize: number
|
||||
logRetentionDays: number
|
||||
disableAdminRegistration: boolean
|
||||
disableSchemaMutations: boolean
|
||||
emailVerificationRequired: boolean
|
||||
maintenanceMode: boolean
|
||||
maxFileSize: Number
|
||||
mode: AppMode
|
||||
sessionTimeout: Number
|
||||
adminSessionTimeout: Number
|
||||
mantisVersion: string
|
||||
sessionTimeout: number
|
||||
adminSessionTimeout: number
|
||||
jwtEnableSetIssuer: boolean
|
||||
jwtEnableSetAudience: boolean
|
||||
smtp: SmtpConfig
|
||||
/** Running MantisBase server version (read-only from GET settings). */
|
||||
mantisVersion?: string
|
||||
}
|
||||
|
||||
export interface SmtpTestRequest {
|
||||
email: string
|
||||
}
|
||||
|
||||
export interface SmtpTestResult {
|
||||
to: string
|
||||
subject: string
|
||||
message: string
|
||||
}
|
||||
|
||||
// API Response interface
|
||||
@@ -112,17 +282,31 @@ interface ApiResponse<T> {
|
||||
status: number
|
||||
}
|
||||
|
||||
function buildRequestHeaders(body: BodyInit | null | undefined, bearerToken?: string): Record<string, string> {
|
||||
const headers: Record<string, string> = {}
|
||||
|
||||
if (bearerToken) {
|
||||
headers.Authorization = `Bearer ${bearerToken}`
|
||||
}
|
||||
|
||||
if (!(body instanceof FormData)) {
|
||||
headers["Content-Type"] = "application/json"
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
export class ApiClient {
|
||||
private token: string
|
||||
private bearerToken?: string
|
||||
private onUnauthorized: (error: string) => void
|
||||
private onError?: (error: string, type?: "error" | "warning") => void
|
||||
|
||||
constructor(
|
||||
token: string,
|
||||
onUnauthorized: (reason?: string | "") => void,
|
||||
onError?: (error: string, type?: "error" | "warning") => void,
|
||||
bearerToken?: string,
|
||||
) {
|
||||
this.token = token
|
||||
this.bearerToken = bearerToken
|
||||
this.onUnauthorized = onUnauthorized
|
||||
this.onError = onError
|
||||
}
|
||||
@@ -130,18 +314,15 @@ export class ApiClient {
|
||||
private async realApiCall<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
|
||||
try {
|
||||
const url = `${getApiBaseUrl()}${endpoint}`
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
};
|
||||
|
||||
// only set content-type if body is not FormData
|
||||
if (!(options.body instanceof FormData)) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
const headers = buildRequestHeaders(options.body, this.bearerToken)
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
credentials: "include",
|
||||
headers: {
|
||||
...headers,
|
||||
...(options.headers as Record<string, string> | undefined),
|
||||
},
|
||||
})
|
||||
|
||||
// DELETE or No Content
|
||||
@@ -229,7 +410,6 @@ export class ApiClient {
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string
|
||||
user: Admin
|
||||
}
|
||||
|
||||
@@ -240,6 +420,7 @@ export async function loginWithPassword(
|
||||
try {
|
||||
const response = await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}/login`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
identity: email,
|
||||
@@ -255,17 +436,15 @@ export async function loginWithPassword(
|
||||
throw new Error("Invalid response from server")
|
||||
}
|
||||
|
||||
// Handle response structure: { status, data: { token, user }, error }
|
||||
if (responseData.status === 200 && responseData.data && responseData.data.token) {
|
||||
// Session cookie is set by the backend via Set-Cookie; JS must not read or store the token.
|
||||
if (responseData.status === 200 && responseData.data?.user) {
|
||||
return {
|
||||
token: responseData.data.token,
|
||||
user: responseData.data.user
|
||||
user: responseData.data.user,
|
||||
}
|
||||
} else {
|
||||
// Handle error response
|
||||
const errorMessage = responseData.error || responseData.message || "Login failed"
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
|
||||
const errorMessage = responseData.error || responseData.message || "Login failed"
|
||||
throw new Error(errorMessage)
|
||||
} catch (error: any) {
|
||||
// Re-throw if it's already an Error with a message
|
||||
if (error instanceof Error) {
|
||||
@@ -274,3 +453,34 @@ export async function loginWithPassword(
|
||||
throw new Error(error.message || "Network error occurred")
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkAuthSession(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}`, {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
})
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return false
|
||||
}
|
||||
|
||||
const responseData = await response.json()
|
||||
return responseData.status === 200
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function logoutSession(): Promise<void> {
|
||||
try {
|
||||
await fetch(`${getApiBaseUrl()}${SYS_ADMINS_API}/logout`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn("Failed to clear admin session cookie:", error)
|
||||
}
|
||||
}
|
||||
|
||||
93
lib/auth.tsx
Normal file
93
lib/auth.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { checkAuthSession, loginWithPassword, logoutSession, type Admin } from "@/lib/api"
|
||||
|
||||
interface AuthContextValue {
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
user: Admin | null
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
refreshSession: () => Promise<boolean>
|
||||
}
|
||||
|
||||
const AuthContext = React.createContext<AuthContextValue | null>(null)
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [isAuthenticated, setIsAuthenticated] = React.useState(false)
|
||||
const [isLoading, setIsLoading] = React.useState(true)
|
||||
const [user, setUser] = React.useState<Admin | null>(null)
|
||||
|
||||
const refreshSession = React.useCallback(async (): Promise<boolean> => {
|
||||
const authenticated = await checkAuthSession()
|
||||
setIsAuthenticated(authenticated)
|
||||
if (!authenticated) {
|
||||
setUser(null)
|
||||
}
|
||||
return authenticated
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
const bootstrap = async () => {
|
||||
try {
|
||||
const authenticated = await checkAuthSession()
|
||||
if (!cancelled) {
|
||||
setIsAuthenticated(authenticated)
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bootstrap()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = React.useCallback(async (email: string, password: string) => {
|
||||
const result = await loginWithPassword(email, password)
|
||||
const authenticated = await checkAuthSession()
|
||||
if (!authenticated) {
|
||||
throw new Error(
|
||||
"Login succeeded but the session cookie was not established. Ensure the admin UI and API share the same origin.",
|
||||
)
|
||||
}
|
||||
setUser(result.user)
|
||||
setIsAuthenticated(true)
|
||||
}, [])
|
||||
|
||||
const logout = React.useCallback(async () => {
|
||||
await logoutSession()
|
||||
setUser(null)
|
||||
setIsAuthenticated(false)
|
||||
}, [])
|
||||
|
||||
const value = React.useMemo(
|
||||
() => ({
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
user,
|
||||
login,
|
||||
logout,
|
||||
refreshSession,
|
||||
}),
|
||||
[isAuthenticated, isLoading, user, login, logout, refreshSession],
|
||||
)
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = React.useContext(AuthContext)
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used within an AuthProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -1,24 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
// Set expected data types, this should map what the database expects
|
||||
// our column data types to be.
|
||||
export const dataTypes = [
|
||||
"xml",
|
||||
"string",
|
||||
"double",
|
||||
"date",
|
||||
"int8",
|
||||
"uint8",
|
||||
"int16",
|
||||
"uint16",
|
||||
"int32",
|
||||
"uint32",
|
||||
"int64",
|
||||
"uint64",
|
||||
"json",
|
||||
"bool",
|
||||
"file",
|
||||
"files"
|
||||
]
|
||||
export { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/field-types"
|
||||
|
||||
28
lib/entity-users.ts
Normal file
28
lib/entity-users.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { ApiKeyUser } from "@/lib/api"
|
||||
|
||||
const DEFAULT_LABEL_FIELDS = ["email", "name", "username"] as const
|
||||
|
||||
export function getEntityUserLabel(
|
||||
user: Record<string, unknown>,
|
||||
preferredFields: readonly string[] = DEFAULT_LABEL_FIELDS,
|
||||
): string {
|
||||
for (const field of preferredFields) {
|
||||
const value = user[field]
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
if (user.id !== undefined && user.id !== null) {
|
||||
return String(user.id)
|
||||
}
|
||||
|
||||
return "Unknown user"
|
||||
}
|
||||
|
||||
export function toApiKeyUsers(records: Record<string, unknown>[]): ApiKeyUser[] {
|
||||
return records.map((record) => ({
|
||||
id: String(record.id),
|
||||
label: getEntityUserLabel(record),
|
||||
}))
|
||||
}
|
||||
150
lib/field-types.ts
Normal file
150
lib/field-types.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
/** Supported entity field types in the schema editor. */
|
||||
export const dataTypes = [
|
||||
"string",
|
||||
"double",
|
||||
"date",
|
||||
"int",
|
||||
"json",
|
||||
"bool",
|
||||
"file",
|
||||
"files",
|
||||
] as const
|
||||
|
||||
/** Legacy types removed from the editor; normalized to `string` when loading schemas. */
|
||||
const LEGACY_STRING_TYPES = new Set(["xml", "blob"])
|
||||
|
||||
export function isLegacyStringFieldType(type: string): boolean {
|
||||
return LEGACY_STRING_TYPES.has(type)
|
||||
}
|
||||
|
||||
/** Integer precision sizes for fields with type `int`. */
|
||||
export const intPrecisions = [
|
||||
"u8",
|
||||
"u16",
|
||||
"u32",
|
||||
"u64",
|
||||
"i8",
|
||||
"i16",
|
||||
"i32",
|
||||
"i64",
|
||||
] as const
|
||||
|
||||
export type IntPrecision = (typeof intPrecisions)[number]
|
||||
|
||||
export const DEFAULT_INT_PRECISION: IntPrecision = "i32"
|
||||
|
||||
const LEGACY_INT_TYPE_TO_PRECISION: Record<string, IntPrecision> = {
|
||||
int8: "i8",
|
||||
int16: "i16",
|
||||
int32: "i32",
|
||||
int64: "i64",
|
||||
uint8: "u8",
|
||||
uint16: "u16",
|
||||
uint32: "u32",
|
||||
uint64: "u64",
|
||||
}
|
||||
|
||||
const LEGACY_INT_TYPES = new Set(Object.keys(LEGACY_INT_TYPE_TO_PRECISION))
|
||||
|
||||
export function isIntFieldType(type: string): boolean {
|
||||
return type === "int" || LEGACY_INT_TYPES.has(type)
|
||||
}
|
||||
|
||||
export function isNumericFieldType(type: string): boolean {
|
||||
return isIntFieldType(type) || type === "double"
|
||||
}
|
||||
|
||||
export function isUnsignedPrecision(precision: string | null | undefined): boolean {
|
||||
return precision?.startsWith("u") ?? false
|
||||
}
|
||||
|
||||
export function resolveFieldPrecision(field: {
|
||||
type: string
|
||||
precision?: string | null
|
||||
}): string | null {
|
||||
if (field.type === "int") {
|
||||
return field.precision ?? DEFAULT_INT_PRECISION
|
||||
}
|
||||
|
||||
return LEGACY_INT_TYPE_TO_PRECISION[field.type] ?? null
|
||||
}
|
||||
|
||||
export function formatFieldTypeDisplay(field: {
|
||||
type: string
|
||||
precision?: string | null
|
||||
}): string {
|
||||
if (field.type === "int") {
|
||||
const precision = field.precision ?? DEFAULT_INT_PRECISION
|
||||
return `int(${precision})`
|
||||
}
|
||||
|
||||
return field.type
|
||||
}
|
||||
|
||||
export function normalizeFieldTypeForEditor(field: {
|
||||
type: string
|
||||
precision?: string | null
|
||||
}): { type: string; precision: string | null } {
|
||||
if (field.type === "int") {
|
||||
return {
|
||||
type: "int",
|
||||
precision: field.precision ?? DEFAULT_INT_PRECISION,
|
||||
}
|
||||
}
|
||||
|
||||
const legacyPrecision = LEGACY_INT_TYPE_TO_PRECISION[field.type]
|
||||
if (legacyPrecision) {
|
||||
return {
|
||||
type: "int",
|
||||
precision: legacyPrecision,
|
||||
}
|
||||
}
|
||||
|
||||
if (LEGACY_STRING_TYPES.has(field.type)) {
|
||||
return {
|
||||
type: "string",
|
||||
precision: null,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type: field.type,
|
||||
precision: field.precision ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export function applyFieldTypeChange(
|
||||
currentType: string,
|
||||
nextType: string,
|
||||
currentPrecision?: string | null,
|
||||
): { type: string; precision: string | null } {
|
||||
if (nextType === "int") {
|
||||
return {
|
||||
type: "int",
|
||||
precision: currentType === "int" ? (currentPrecision ?? DEFAULT_INT_PRECISION) : DEFAULT_INT_PRECISION,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type: nextType,
|
||||
precision: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function appendPrecisionToFieldPayload(
|
||||
fieldData: Record<string, unknown>,
|
||||
field: { type: string; precision?: string | null },
|
||||
): void {
|
||||
if (field.type === "int") {
|
||||
fieldData.precision = field.precision ?? DEFAULT_INT_PRECISION
|
||||
}
|
||||
}
|
||||
|
||||
/** True when a field still uses a removed legacy type from the API. */
|
||||
export function fieldNeedsTypeMigration(field: { type: string }): boolean {
|
||||
return LEGACY_INT_TYPES.has(field.type) || LEGACY_STRING_TYPES.has(field.type)
|
||||
}
|
||||
|
||||
export function schemaFieldsNeedMigration(fields: { type: string }[]): boolean {
|
||||
return fields.some(fieldNeedsTypeMigration)
|
||||
}
|
||||
238
lib/router.ts
238
lib/router.ts
@@ -1,238 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
export interface RouteParams {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
export interface ParsedRoute {
|
||||
path: string
|
||||
pathParams: RouteParams
|
||||
queryParams: RouteParams
|
||||
}
|
||||
|
||||
// Use a custom event system for route changes
|
||||
const ROUTE_CHANGE_EVENT = "custom-route-change"
|
||||
|
||||
let currentRoute: ParsedRoute = { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
|
||||
// Resolve default base path when env is not set (shared for server and client fallback)
|
||||
function getDefaultBasePath(): string {
|
||||
return process.env.NODE_ENV === "production" ? "/mb" : ""
|
||||
}
|
||||
|
||||
// Get the base path for the application. Env var overrides for both build and runtime; empty string = no base path.
|
||||
export function getBasePath(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined"
|
||||
? process.env.NEXT_PUBLIC_BASE_PATH
|
||||
: getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Client-side: env var wins when set (including empty string)
|
||||
if (typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined") {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH
|
||||
}
|
||||
|
||||
// Infer from current location when env not set: if we're under /mb, use /mb
|
||||
const pathname = window.location.pathname
|
||||
if (pathname === "/mb" || pathname.startsWith("/mb/")) {
|
||||
return "/mb"
|
||||
}
|
||||
|
||||
return getDefaultBasePath()
|
||||
}
|
||||
|
||||
// Strip base path from a full pathname
|
||||
function stripBasePath(pathname: string): string {
|
||||
const basePath = getBasePath()
|
||||
if (pathname.startsWith(basePath)) {
|
||||
return pathname.slice(basePath.length) || "/"
|
||||
}
|
||||
return pathname
|
||||
}
|
||||
|
||||
// Parse path params from route pattern (e.g., "/entities/:name" -> { name: "test" })
|
||||
function parsePathParams(pattern: string, path: string): RouteParams {
|
||||
const params: RouteParams = {}
|
||||
const patternParts = pattern.split("/")
|
||||
const pathParts = path.split("/")
|
||||
|
||||
if (patternParts.length !== pathParts.length) {
|
||||
return params
|
||||
}
|
||||
|
||||
for (let i = 0; i < patternParts.length; i++) {
|
||||
if (patternParts[i].startsWith(":")) {
|
||||
const paramName = patternParts[i].slice(1)
|
||||
params[paramName] = pathParts[i]
|
||||
}
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
export function parseRoute(pathname: string, search: string = ""): ParsedRoute {
|
||||
try {
|
||||
// Strip base path from the pathname first
|
||||
const pathWithoutBase = stripBasePath(pathname)
|
||||
|
||||
// Remove leading slash if present for consistency
|
||||
let cleanPath = pathWithoutBase.startsWith("/") ? pathWithoutBase : `/${pathWithoutBase}`
|
||||
|
||||
// Remove trailing slash for consistency
|
||||
if (cleanPath.endsWith("/") && cleanPath !== "/") {
|
||||
cleanPath = cleanPath.slice(0, -1)
|
||||
}
|
||||
|
||||
// If empty, default to /entities
|
||||
if (!cleanPath || cleanPath === "/") {
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
|
||||
// Parse query parameters from search string
|
||||
const queryParams: RouteParams = {}
|
||||
if (search) {
|
||||
try {
|
||||
const searchParams = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search)
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
queryParams[key] = value
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to parse query parameters:", error)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract path params based on known route patterns
|
||||
const pathParams: RouteParams = {}
|
||||
|
||||
// Match /entities/:name pattern
|
||||
const entitiesMatch = cleanPath.match(/^\/entities\/([^/]+)$/)
|
||||
if (entitiesMatch) {
|
||||
pathParams.name = entitiesMatch[1]
|
||||
return { path: "/entities/:name", pathParams, queryParams }
|
||||
}
|
||||
|
||||
return {
|
||||
path: cleanPath,
|
||||
pathParams,
|
||||
queryParams,
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to parse route:", error)
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRoute(path: string, pathParams?: RouteParams, queryParams?: RouteParams): string {
|
||||
try {
|
||||
let route = path.startsWith("/") ? path : `/${path}`
|
||||
|
||||
// Replace path params (e.g., /entities/:name -> /entities/test)
|
||||
if (pathParams) {
|
||||
for (const [key, value] of Object.entries(pathParams)) {
|
||||
route = route.replace(`:${key}`, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Add query parameters
|
||||
if (queryParams && Object.keys(queryParams).length > 0) {
|
||||
const searchParams = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(queryParams)) {
|
||||
if (value) {
|
||||
searchParams.set(key, value)
|
||||
}
|
||||
}
|
||||
const queryString = searchParams.toString()
|
||||
if (queryString) {
|
||||
route += `?${queryString}`
|
||||
}
|
||||
}
|
||||
|
||||
// Prepend base path
|
||||
const basePath = getBasePath()
|
||||
return basePath + route
|
||||
} catch (error) {
|
||||
console.warn("Failed to build route:", error)
|
||||
const basePath = getBasePath()
|
||||
return basePath + "/entities"
|
||||
}
|
||||
}
|
||||
|
||||
// Custom event dispatcher
|
||||
function dispatchRouteChange(route: ParsedRoute) {
|
||||
const event = new CustomEvent(ROUTE_CHANGE_EVENT, { detail: route })
|
||||
window.dispatchEvent(event)
|
||||
}
|
||||
|
||||
export function useRouter() {
|
||||
const [route, setRoute] = React.useState<ParsedRoute>(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
const initialRoute = parseRoute(window.location.pathname, window.location.search)
|
||||
currentRoute = initialRoute
|
||||
return initialRoute
|
||||
} catch (error) {
|
||||
console.warn("Failed to get initial route:", error)
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
}
|
||||
}
|
||||
return { path: "/entities", pathParams: {}, queryParams: {} }
|
||||
})
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleCustomRouteChange = (event: CustomEvent) => {
|
||||
try {
|
||||
const newRoute = event.detail as ParsedRoute
|
||||
setRoute(newRoute)
|
||||
currentRoute = newRoute
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle route change:", error)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePopState = () => {
|
||||
try {
|
||||
const newRoute = parseRoute(window.location.pathname, window.location.search)
|
||||
setRoute(newRoute)
|
||||
currentRoute = newRoute
|
||||
} catch (error) {
|
||||
console.warn("Failed to handle pop state:", error)
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for our custom events
|
||||
window.addEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
|
||||
window.addEventListener("popstate", handlePopState)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
|
||||
window.removeEventListener("popstate", handlePopState)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const navigate = React.useCallback((path: string, pathParams?: RouteParams, queryParams?: RouteParams) => {
|
||||
try {
|
||||
const routePath = buildRoute(path, pathParams, queryParams)
|
||||
const newRoute = parseRoute(routePath.split("?")[0], routePath.includes("?") ? routePath.split("?")[1] : "")
|
||||
|
||||
// Update URL using pushState for clean paths
|
||||
if (window.location.pathname + window.location.search !== routePath) {
|
||||
window.history.pushState(null, "", routePath)
|
||||
}
|
||||
|
||||
// Dispatch our custom event
|
||||
dispatchRouteChange(newRoute)
|
||||
} catch (error) {
|
||||
console.warn("Failed to navigate:", error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { route, navigate }
|
||||
}
|
||||
|
||||
// Helper function to get current route without hooks
|
||||
export function getCurrentRoute(): ParsedRoute {
|
||||
return currentRoute
|
||||
}
|
||||
49
lib/routes.ts
Normal file
49
lib/routes.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
"use client"
|
||||
|
||||
/** Admin dashboard route paths (without basePath). */
|
||||
export const ROUTES = {
|
||||
home: "/",
|
||||
login: "/login",
|
||||
setup: "/setup",
|
||||
entities: "/entities",
|
||||
entityDetail: "/entities/:name",
|
||||
logs: "/logs",
|
||||
admins: "/admins",
|
||||
settings: "/settings",
|
||||
} as const
|
||||
|
||||
export type DashboardSection = "entities" | "logs" | "admins" | "settings" | "sync"
|
||||
|
||||
const DASHBOARD_SECTIONS = new Set<string>(["entities", "logs", "admins", "settings", "sync"])
|
||||
|
||||
function getDefaultBasePath(): string {
|
||||
return process.env.NODE_ENV === "production" ? "/mb" : ""
|
||||
}
|
||||
|
||||
/** Application base path (e.g. `/mb` in production). */
|
||||
export function getBasePath(): string {
|
||||
if (typeof process.env.NEXT_PUBLIC_BASE_PATH !== "undefined") {
|
||||
return process.env.NEXT_PUBLIC_BASE_PATH
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
const pathname = window.location.pathname
|
||||
if (pathname === "/mb" || pathname.startsWith("/mb/")) {
|
||||
return "/mb"
|
||||
}
|
||||
}
|
||||
|
||||
return getDefaultBasePath()
|
||||
}
|
||||
|
||||
export function entityDetailPath(name: string): string {
|
||||
return `/entities/${encodeURIComponent(name)}`
|
||||
}
|
||||
|
||||
export function getDashboardSection(pathname: string): DashboardSection {
|
||||
const segment = pathname.split("/").filter(Boolean)[0] || "entities"
|
||||
if (DASHBOARD_SECTIONS.has(segment)) {
|
||||
return segment as DashboardSection
|
||||
}
|
||||
return "entities"
|
||||
}
|
||||
@@ -4,22 +4,9 @@
|
||||
*/
|
||||
|
||||
import type { FieldConstraints } from "@/lib/api"
|
||||
import { isIntFieldType, isUnsignedPrecision } from "@/lib/field-types"
|
||||
|
||||
const INTEGER_TYPES = new Set([
|
||||
"int8",
|
||||
"int16",
|
||||
"int32",
|
||||
"int64",
|
||||
"uint8",
|
||||
"uint16",
|
||||
"uint32",
|
||||
"uint64",
|
||||
])
|
||||
|
||||
const NUMERIC_TYPES = new Set([
|
||||
...INTEGER_TYPES,
|
||||
"double",
|
||||
])
|
||||
const NUMERIC_TYPES = new Set(["double", "int"])
|
||||
|
||||
export interface RawConstraintsInput {
|
||||
default_value: unknown
|
||||
@@ -66,7 +53,19 @@ function validateMinMaxOrder(min: number | null, max: number | null): string | n
|
||||
return null
|
||||
}
|
||||
|
||||
function parseDefaultValue(fieldType: string, raw: unknown): { ok: true; value: unknown } | { ok: false; message: string } {
|
||||
function isUnsignedIntegerField(fieldType: string, precision?: string | null): boolean {
|
||||
if (fieldType === "int") {
|
||||
return isUnsignedPrecision(precision)
|
||||
}
|
||||
|
||||
return fieldType.startsWith("uint")
|
||||
}
|
||||
|
||||
function parseDefaultValue(
|
||||
fieldType: string,
|
||||
raw: unknown,
|
||||
precision?: string | null,
|
||||
): { ok: true; value: unknown } | { ok: false; message: string } {
|
||||
if (raw === null || raw === undefined) {
|
||||
return { ok: true, value: null }
|
||||
}
|
||||
@@ -80,10 +79,12 @@ function parseDefaultValue(fieldType: string, raw: unknown): { ok: true; value:
|
||||
|
||||
switch (fieldType) {
|
||||
case "string":
|
||||
case "xml": {
|
||||
case "xml":
|
||||
case "blob": {
|
||||
return { ok: true, value: typeof raw === "string" ? raw : String(raw) }
|
||||
}
|
||||
|
||||
case "int":
|
||||
case "int8":
|
||||
case "int16":
|
||||
case "int32":
|
||||
@@ -99,7 +100,7 @@ function parseDefaultValue(fieldType: string, raw: unknown): { ok: true; value:
|
||||
if (!Number.isInteger(n)) {
|
||||
return { ok: false, message: "Default value must be an integer for this field type." }
|
||||
}
|
||||
if (fieldType.startsWith("uint") && n < 0) {
|
||||
if (isUnsignedIntegerField(fieldType, precision) && n < 0) {
|
||||
return { ok: false, message: "Default value must be non-negative for unsigned integer fields." }
|
||||
}
|
||||
return { ok: true, value: n }
|
||||
@@ -192,6 +193,7 @@ export function formatConstraintDefaultForInput(fieldType: string, value: unknow
|
||||
export function normalizeConstraintsForFieldType(
|
||||
fieldType: string,
|
||||
input: RawConstraintsInput,
|
||||
precision?: string | null,
|
||||
): ConstraintsNormalizeResult {
|
||||
const minR = normalizeConstraintBound(input.min_value)
|
||||
if (!minR.ok) {
|
||||
@@ -207,13 +209,14 @@ export function normalizeConstraintsForFieldType(
|
||||
return { ok: false, message: orderErr }
|
||||
}
|
||||
|
||||
if (NUMERIC_TYPES.has(fieldType)) {
|
||||
const minInt = minR.value !== null && INTEGER_TYPES.has(fieldType) && !Number.isInteger(minR.value)
|
||||
const maxInt = maxR.value !== null && INTEGER_TYPES.has(fieldType) && !Number.isInteger(maxR.value)
|
||||
if (NUMERIC_TYPES.has(fieldType) || isIntFieldType(fieldType)) {
|
||||
const isInteger = isIntFieldType(fieldType)
|
||||
const minInt = minR.value !== null && isInteger && !Number.isInteger(minR.value)
|
||||
const maxInt = maxR.value !== null && isInteger && !Number.isInteger(maxR.value)
|
||||
if (minInt || maxInt) {
|
||||
return { ok: false, message: "Min/max for integer types must be whole numbers." }
|
||||
}
|
||||
if (fieldType.startsWith("uint")) {
|
||||
if (isUnsignedIntegerField(fieldType, precision)) {
|
||||
if (minR.value !== null && minR.value < 0) {
|
||||
return { ok: false, message: "Min cannot be negative for unsigned integer fields." }
|
||||
}
|
||||
@@ -223,7 +226,7 @@ export function normalizeConstraintsForFieldType(
|
||||
}
|
||||
}
|
||||
|
||||
const defR = parseDefaultValue(fieldType, input.default_value)
|
||||
const defR = parseDefaultValue(fieldType, input.default_value, precision)
|
||||
if (!defR.ok) {
|
||||
return { ok: false, message: defR.message }
|
||||
}
|
||||
|
||||
112
lib/schema-migration.ts
Normal file
112
lib/schema-migration.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import type { ApiClient, TableField, TableMetadata } from "@/lib/api"
|
||||
import {
|
||||
appendPrecisionToFieldPayload,
|
||||
normalizeFieldTypeForEditor,
|
||||
schemaFieldsNeedMigration,
|
||||
} from "@/lib/field-types"
|
||||
|
||||
export function normalizeSchemaField(field: TableField): TableField {
|
||||
const { type, precision } = normalizeFieldTypeForEditor(field)
|
||||
const normalized: TableField = { ...field, type }
|
||||
|
||||
if (type === "int") {
|
||||
normalized.precision = precision
|
||||
} else {
|
||||
normalized.precision = undefined
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function normalizeTableSchema(table: TableMetadata): TableMetadata {
|
||||
if (!table.schema?.fields) {
|
||||
return table
|
||||
}
|
||||
|
||||
return {
|
||||
...table,
|
||||
schema: {
|
||||
...table.schema,
|
||||
fields: table.schema.fields.map(normalizeSchemaField),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function buildFieldPatchPayload(field: TableField): Record<string, unknown> {
|
||||
const normalized = normalizeSchemaField(field)
|
||||
const fieldData: Record<string, unknown> = {
|
||||
id: field.id,
|
||||
name: field.name,
|
||||
type: normalized.type,
|
||||
primary_key: field.primary_key,
|
||||
required: field.required,
|
||||
system: field.system ?? false,
|
||||
unique: field.unique ?? false,
|
||||
constraints: field.constraints ?? {
|
||||
default_value: null,
|
||||
max_value: null,
|
||||
min_value: null,
|
||||
validator: null,
|
||||
},
|
||||
}
|
||||
|
||||
appendPrecisionToFieldPayload(fieldData, normalized)
|
||||
|
||||
if (field.foreign_key?.entity && field.foreign_key?.field) {
|
||||
fieldData.foreign_key = field.foreign_key
|
||||
}
|
||||
|
||||
return fieldData
|
||||
}
|
||||
|
||||
export async function migrateSchemaFieldsIfNeeded(
|
||||
apiClient: ApiClient,
|
||||
table: TableMetadata,
|
||||
): Promise<TableMetadata | null> {
|
||||
const fields = table.schema?.fields ?? []
|
||||
if (!schemaFieldsNeedMigration(fields)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/schemas/${table.schema.name}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({
|
||||
fields: fields.map(buildFieldPatchPayload),
|
||||
}),
|
||||
})
|
||||
|
||||
if ((updatedTable as { error?: unknown[] })?.error?.length) {
|
||||
throw (updatedTable as { error: unknown[] }).error
|
||||
}
|
||||
|
||||
return normalizeTableSchema(updatedTable)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize schemas in memory and persist legacy field-type migrations to the backend.
|
||||
*/
|
||||
export async function applySchemaListMigration(
|
||||
apiClient: ApiClient,
|
||||
tables: TableMetadata[],
|
||||
onTableMigrated?: (table: TableMetadata) => void,
|
||||
): Promise<TableMetadata[]> {
|
||||
let result = tables.map(normalizeTableSchema)
|
||||
|
||||
for (const table of tables) {
|
||||
if (!schemaFieldsNeedMigration(table.schema?.fields ?? [])) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const migrated = await migrateSchemaFieldsIfNeeded(apiClient, table)
|
||||
if (migrated) {
|
||||
result = result.map((entry) => (entry.id === migrated.id ? migrated : entry))
|
||||
onTableMigrated?.(migrated)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to migrate schema "${table.schema.name}":`, error)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -26,6 +26,21 @@ const nextConfig = {
|
||||
// This allows dynamic routes to work in development
|
||||
...(process.env.NODE_ENV === 'production' && { output: 'export' }),
|
||||
trailingSlash: true,
|
||||
async rewrites() {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return []
|
||||
}
|
||||
|
||||
const port = process.env.MANTIS_PORT || '7070'
|
||||
const target = (process.env.MANTIS_PROXY_URL || `http://127.0.0.1:${port}`).replace(/\/+$/, '')
|
||||
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
destination: `${target}/api/:path*`,
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
2077
openapi.yaml
Normal file
2077
openapi.yaml
Normal file
File diff suppressed because it is too large
Load Diff
46
package-lock.json
generated
46
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.8",
|
||||
"version": "0.3.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.9",
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@radix-ui/react-accordion": "1.2.2",
|
||||
@@ -51,6 +51,7 @@
|
||||
"react-dom": "^18.2",
|
||||
"react-hook-form": "^7.54.1",
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"react-router-dom": "^6.30.4",
|
||||
"recharts": "2.15.0",
|
||||
"sonner": "^1.7.1",
|
||||
"tailwind-merge": "^2.5.5",
|
||||
@@ -3031,6 +3032,15 @@
|
||||
"integrity": "sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@remix-run/router": {
|
||||
"version": "1.23.3",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
|
||||
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/counter": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
|
||||
@@ -4648,6 +4658,38 @@
|
||||
"react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "6.30.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
|
||||
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "6.30.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
|
||||
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.3",
|
||||
"react-router": "6.30.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8",
|
||||
"react-dom": ">=16.8"
|
||||
}
|
||||
},
|
||||
"node_modules/react-smooth": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
@@ -53,6 +53,7 @@
|
||||
"react-dom": "^18.2",
|
||||
"react-hook-form": "^7.54.1",
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"react-router-dom": "^6.30.4",
|
||||
"recharts": "2.15.0",
|
||||
"sonner": "^1.7.1",
|
||||
"tailwind-merge": "^2.5.5",
|
||||
|
||||
Reference in New Issue
Block a user