mirror of
https://github.com/allankoechke/mantisbase-admin.git
synced 2026-12-01 01:15:36 +00:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 90969110f7 | |||
| 6d3e109ca6 | |||
| 064e6db700 | |||
| 5c96ed6770 | |||
| c3b1da50d2 | |||
| b3c38067f4 | |||
| 846cdc1631 | |||
| 82d5716848 | |||
| 6111fb5321 | |||
| 367246f6ba | |||
| 0c8b9183f1 | |||
| 7134c7df5b | |||
| 3b227cb720 | |||
| 84333ea981 |
19
README.md
19
README.md
@@ -131,9 +131,9 @@ This repo includes an `mb-admins` branch with **built static files**, integrated
|
||||
|
||||
- List, create, and open entities
|
||||
- **Entity types:** `base`, `auth`, and `view` (read-only SQL views)
|
||||
- **Configure drawer** (three tabs):
|
||||
- **Configure drawer**:
|
||||
- **Fields** — schema editor with constraints, validators, foreign keys
|
||||
- **OAuth** — register providers and enable/disable per auth entity (see below)
|
||||
- **Auth** (auth entities) — toggles for password, email OTP, and OAuth login methods; OAuth provider registry appears only when OAuth is enabled
|
||||
- **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
|
||||
@@ -149,14 +149,17 @@ 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`
|
||||
- **Login methods** — `auth.password` / `auth.otp` / `auth.oauth` on the schema (defaults: password on, OTP/OAuth off). Public apps read `GET /api/v1/auth/{entity}/methods`.
|
||||
- **Email verification** — `auth.requireEmailVerification` (default off). Auth records include system field `email_verified` (admin-editable). Apps use `/verify-email` and `/verify-email/request`.
|
||||
- **Password reset** — auth row actions can send a reset email via `/password-reset/request`. Users complete the flow with `/password-reset` (HTML form or JSON `{ token, password }`).
|
||||
- **OAuth providers** — shown under Auth only when `auth.oauth` is on; per-provider enablement via `enabled_for_entity`
|
||||
|
||||
OAuth workflow:
|
||||
Auth / 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
|
||||
1. Enable the desired methods under **Configure → Auth**
|
||||
2. For OTP or required email verification, configure SMTP (and Site Domain for verification links) under Settings
|
||||
3. For OAuth, register providers and toggle **Enabled for entity**
|
||||
4. Client apps should call `/methods` and only show enabled options / verification UX when flagged
|
||||
|
||||
### Admins
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from 'next'
|
||||
import { ScriptHeaders } from '@/lib/script-headers'
|
||||
import './globals.css'
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -16,6 +17,7 @@ export default function RootLayout({
|
||||
<head>
|
||||
<link rel="icon" href="/mantisbase.svg" type="image/svg+xml" />
|
||||
<link rel="alternate icon" href="/favicon.ico" />
|
||||
<ScriptHeaders />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
|
||||
@@ -18,9 +18,11 @@ 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 { isFieldRequiredInForm } from "@/lib/auth-fields"
|
||||
import { isNumericFieldType } from "@/lib/field-types"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { PasswordFieldInput } from "./password-field-input"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -284,7 +286,7 @@ export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, on
|
||||
<div key={field.name} className="space-y-2">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium">
|
||||
{field.name}
|
||||
{(field.required || field.system) && <span className="text-red-500 ml-1">*</span>}
|
||||
{isFieldRequiredInForm(field, table.schema.type) && <span className="text-red-500 ml-1">*</span>}
|
||||
</Label>
|
||||
{isFkField ? (
|
||||
<Select
|
||||
@@ -313,14 +315,29 @@ export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, on
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : field.type === "bool" ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!formData[field.name]}
|
||||
onCheckedChange={(checked: any) => handleFieldChange(field.name, checked)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
/>
|
||||
<span>{formData[field.name] === true ? "True" : "False"}</span>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!formData[field.name]}
|
||||
onCheckedChange={(checked: any) => handleFieldChange(field.name, checked)}
|
||||
disabled={field.type === "view" || isSystemGeneratedField(field)}
|
||||
/>
|
||||
<span>
|
||||
{field.name === "email_verified"
|
||||
? formData[field.name]
|
||||
? "Verified"
|
||||
: "Unverified"
|
||||
: formData[field.name] === true
|
||||
? "True"
|
||||
: "False"}
|
||||
</span>
|
||||
</div>
|
||||
{table.schema.type === "auth" && field.name === "email_verified" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Defaults to unverified. After creating the user, open Edit to send a verification email.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : field.type === "file" ? (
|
||||
<Input
|
||||
@@ -350,15 +367,25 @@ export function AddItemDrawer({ table, apiClient, entityCollectionPath, open, on
|
||||
placeholder={`Enter '${field.name}' value`}
|
||||
/>
|
||||
) : field.name === "password" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
type="password"
|
||||
value={formData[field.name] ?? ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={(field.type === "view" || isSystemGeneratedField(field))}
|
||||
className={`w-full ${(field.type === "view" || isSystemGeneratedField(field)) ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${field.name}' value`}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<PasswordFieldInput
|
||||
id={field.name}
|
||||
value={formData[field.name] ?? ""}
|
||||
onChange={(next) => handleFieldChange(field.name, next)}
|
||||
disabled={field.type === "view" || isSystemGeneratedField(field)}
|
||||
className={field.type === "view" || isSystemGeneratedField(field) ? "bg-muted" : ""}
|
||||
placeholder={
|
||||
table.schema.type === "auth"
|
||||
? "Optional — leave blank for OAuth-only users"
|
||||
: "Enter password"
|
||||
}
|
||||
/>
|
||||
{table.schema.type === "auth" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Optional for auth entities. OAuth users may have no password.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : field.type === "date" ? (
|
||||
<Input
|
||||
id={field.name}
|
||||
|
||||
@@ -224,9 +224,9 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
name: "password",
|
||||
type: "string",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
nullable: true,
|
||||
system: true,
|
||||
required: true,
|
||||
required: false,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: 6,
|
||||
@@ -235,6 +235,22 @@ export function AddTableDialog({ apiClient, onTablesUpdate, tables = [], childre
|
||||
validator: "@password"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "mbf_14924781257948638420",
|
||||
name: "email_verified",
|
||||
type: "bool",
|
||||
primary_key: false,
|
||||
nullable: false,
|
||||
system: true,
|
||||
required: true,
|
||||
unique: false,
|
||||
constraints: {
|
||||
min_value: null,
|
||||
max_value: null,
|
||||
default_value: false,
|
||||
validator: null
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,8 +18,11 @@ import {
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { ApiClient, TableMetadata, TableField, buildEntityFileUrl } from "@/lib/api"
|
||||
import { isFieldRequiredInForm } from "@/lib/auth-fields"
|
||||
import { formatFieldTypeDisplay, isNumericFieldType } from "@/lib/field-types"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { PasswordFieldInput } from "./password-field-input"
|
||||
import { SendVerificationButton } from "./send-verification-button"
|
||||
|
||||
interface EditItemDrawerProps {
|
||||
table: TableMetadata
|
||||
@@ -393,7 +396,7 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
<div key={field.name} className="space-y-2">
|
||||
<Label htmlFor={field.name} className="text-sm font-medium">
|
||||
{field.name}
|
||||
{field.required && <span className="text-red-500 ml-1">*</span>}
|
||||
{isFieldRequiredInForm(field, table.schema.type) && <span className="text-red-500 ml-1">*</span>}
|
||||
</Label>
|
||||
|
||||
{/* FOREIGN KEY FIELD */}
|
||||
@@ -433,14 +436,37 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
table={table}
|
||||
/>
|
||||
) : field.type === "bool" ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!value}
|
||||
onCheckedChange={(checked) => handleFieldChange(field.name, checked)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<span>{formData[field.name] === true ? "True" : "False"}</span>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={!!value}
|
||||
onCheckedChange={(checked) => handleFieldChange(field.name, checked)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<span>
|
||||
{field.name === "email_verified"
|
||||
? formData[field.name]
|
||||
? "Verified"
|
||||
: "Unverified"
|
||||
: formData[field.name] === true
|
||||
? "True"
|
||||
: "False"}
|
||||
</span>
|
||||
</div>
|
||||
{table.schema.type === "auth" && field.name === "email_verified" && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Admins can set this flag. Changing the email clears verification unless you also set
|
||||
email_verified in the same save.
|
||||
</p>
|
||||
<SendVerificationButton
|
||||
entityName={table.schema.name}
|
||||
email={formData.email}
|
||||
apiClient={apiClient}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : field.type === "date" || field.type === "datetime" || field.type === "timestamp" ? (
|
||||
<Input
|
||||
@@ -461,10 +487,30 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
className={`w-full ${isDisabled ? "bg-muted" : ""}`}
|
||||
placeholder={`Enter '${formatFieldTypeDisplay(field)}' value`}
|
||||
/>
|
||||
) : field.name === "password" ? (
|
||||
<div className="space-y-2">
|
||||
<PasswordFieldInput
|
||||
id={field.name}
|
||||
value={value ?? ""}
|
||||
onChange={(next) => handleFieldChange(field.name, next)}
|
||||
disabled={isDisabled}
|
||||
className={isDisabled ? "bg-muted" : ""}
|
||||
placeholder={
|
||||
table.schema.type === "auth"
|
||||
? "Leave blank to keep current / OAuth-only"
|
||||
: "Enter password"
|
||||
}
|
||||
/>
|
||||
{table.schema.type === "auth" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Optional. Leave blank to keep the current password. Responses redact password values.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
id={field.name}
|
||||
type={field.name === "password" ? "password" : "text"}
|
||||
type="text"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => handleFieldChange(field.name, e.target.value)}
|
||||
disabled={isDisabled}
|
||||
@@ -476,9 +522,6 @@ export function EditItemDrawer({ table, item, apiClient, open, onClose, onItemUp
|
||||
{isDisabled && (
|
||||
<p className="text-xs text-muted-foreground">System generated field - cannot be modified</p>
|
||||
)}
|
||||
{table.schema.type === "auth" && field.name === "password" && (
|
||||
<p className="text-xs text-muted-foreground">Password fields are redacted in API responses.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
110
components/database/password-field-input.tsx
Normal file
110
components/database/password-field-input.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Check, Copy, Eye, EyeOff, RefreshCw } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { generateRandomPassword } from "@/lib/auth-fields"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface PasswordFieldInputProps {
|
||||
id?: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
export function PasswordFieldInput({
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
className,
|
||||
placeholder = "Enter password or generate one",
|
||||
}: PasswordFieldInputProps) {
|
||||
const { toast } = useToast()
|
||||
const [visible, setVisible] = React.useState(false)
|
||||
const [copied, setCopied] = React.useState(false)
|
||||
|
||||
const handleGenerate = () => {
|
||||
const next = generateRandomPassword()
|
||||
onChange(next)
|
||||
setVisible(true)
|
||||
toast({
|
||||
title: "Password Generated",
|
||||
description: "A random password was filled in. Copy it before saving if you need to share it.",
|
||||
duration: 3000,
|
||||
})
|
||||
}
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (!value) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Nothing to copy",
|
||||
description: "Generate or enter a password first.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
setCopied(true)
|
||||
toast({
|
||||
title: "Copied",
|
||||
description: "Password copied to clipboard.",
|
||||
duration: 2000,
|
||||
})
|
||||
window.setTimeout(() => setCopied(false), 1500)
|
||||
} catch {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Copy failed",
|
||||
description: "Could not copy to clipboard.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
id={id}
|
||||
type={visible ? "text" : "password"}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
disabled={disabled}
|
||||
className={cn("pr-10", className)}
|
||||
placeholder={placeholder}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2"
|
||||
onClick={() => setVisible((current) => !current)}
|
||||
disabled={disabled}
|
||||
aria-label={visible ? "Hide password" : "Show password"}
|
||||
>
|
||||
{visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleGenerate} disabled={disabled}>
|
||||
<RefreshCw className="mr-2 h-3.5 w-3.5" />
|
||||
Generate
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleCopy} disabled={disabled || !value}>
|
||||
{copied ? <Check className="mr-2 h-3.5 w-3.5" /> : <Copy className="mr-2 h-3.5 w-3.5" />}
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
85
components/database/send-verification-button.tsx
Normal file
85
components/database/send-verification-button.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Mail } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { getApiClientError, type ApiClient } from "@/lib/api"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
interface SendVerificationButtonProps {
|
||||
entityName: string
|
||||
email: string | null | undefined
|
||||
apiClient: ApiClient
|
||||
variant?: "default" | "outline" | "ghost" | "secondary"
|
||||
size?: "default" | "sm" | "lg" | "icon"
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function SendVerificationButton({
|
||||
entityName,
|
||||
email,
|
||||
apiClient,
|
||||
variant = "outline",
|
||||
size = "sm",
|
||||
className,
|
||||
}: SendVerificationButtonProps) {
|
||||
const { toast } = useToast()
|
||||
const [isSending, setIsSending] = React.useState(false)
|
||||
const trimmedEmail = typeof email === "string" ? email.trim() : ""
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!trimmedEmail) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Email required",
|
||||
description: "This user has no email address to send a verification link to.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsSending(true)
|
||||
try {
|
||||
const response = await apiClient.call<{ sent?: boolean }>(
|
||||
`/api/v1/auth/${encodeURIComponent(entityName)}/verify-email/request`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email: trimmedEmail }),
|
||||
},
|
||||
)
|
||||
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Verification Email Requested",
|
||||
description: "If an account exists for that email, we sent a verification link.",
|
||||
duration: 4000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to send verification email:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Could not send verification",
|
||||
description: error instanceof Error ? error.message : "Failed to send verification email.",
|
||||
})
|
||||
} finally {
|
||||
setIsSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={className}
|
||||
onClick={handleSend}
|
||||
disabled={isSending || !trimmedEmail}
|
||||
>
|
||||
<Mail className="mr-2 h-3.5 w-3.5" />
|
||||
{isSending ? "Sending..." : "Send verification email"}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -31,7 +31,9 @@ import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
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 { Switch } from "@/components/ui/switch"
|
||||
import type { ApiClient, AuthMethods, TableMetadata, ForeignKeyConfig } from "@/lib/api"
|
||||
import { authMethodLabel, getApiClientError, normalizeAuthMethods } from "@/lib/api"
|
||||
import { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/constants"
|
||||
import {
|
||||
appendPrecisionToFieldPayload,
|
||||
@@ -74,6 +76,32 @@ interface TableConfigDrawerProps {
|
||||
}
|
||||
*/
|
||||
|
||||
function transformFieldsForEditor(fields: TableMetadata["schema"]["fields"] | undefined) {
|
||||
return (
|
||||
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,
|
||||
foreign_key: col.foreign_key,
|
||||
}
|
||||
}) || []
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeRuleMode(mode: string | undefined) {
|
||||
// Convert empty string to "admin" for UI (Select doesn't allow empty string values)
|
||||
return mode === "" || !mode ? "admin" : mode
|
||||
}
|
||||
|
||||
// NOTE: We don't support changing of field names yet!
|
||||
export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpdate, onTablesUpdate, tables = [] }: TableConfigDrawerProps) {
|
||||
const [columns, setColumns] = React.useState<any[]>([])
|
||||
@@ -97,6 +125,11 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
const [deletedColumns, setDeletedColumns] = React.useState<string[]>([]) // Track deleted field IDs
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
|
||||
const [isDeleting, setIsDeleting] = React.useState(false)
|
||||
const [authMethods, setAuthMethods] = React.useState<AuthMethods>(() =>
|
||||
normalizeAuthMethods(table.schema.auth),
|
||||
)
|
||||
const [savingAuthMethod, setSavingAuthMethod] = React.useState<keyof AuthMethods | null>(null)
|
||||
const wasOpenRef = React.useRef(false)
|
||||
const { toast } = useToast()
|
||||
const navigate = useNavigate()
|
||||
const isAuthEntity = table.schema.type === "auth"
|
||||
@@ -104,80 +137,66 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
// Get unique key for field (use id if exists, otherwise generate one)
|
||||
const getFieldKey = (field: any, index: number) => field.id || `temp-${index}`
|
||||
|
||||
// Only hydrate drawer state when it opens. Parent table updates (auth toggles,
|
||||
// schema saves) must not reset the active tab or feel like a close/reopen.
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
// Transform API format (with constraints) to UI format (flat camelCase)
|
||||
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,
|
||||
const justOpened = open && !wasOpenRef.current
|
||||
wasOpenRef.current = open
|
||||
if (!justOpened) {
|
||||
return
|
||||
}
|
||||
|
||||
setColumns(transformFieldsForEditor(table.schema?.fields))
|
||||
setRules({
|
||||
list: {
|
||||
mode: normalizeRuleMode(table.schema.rules?.list?.mode),
|
||||
expr: table.schema.rules?.list?.expr || "",
|
||||
},
|
||||
get: {
|
||||
mode: normalizeRuleMode(table.schema.rules?.get?.mode),
|
||||
expr: table.schema.rules?.get?.expr || "",
|
||||
},
|
||||
add: {
|
||||
mode: normalizeRuleMode(table.schema.rules?.add?.mode),
|
||||
expr: table.schema.rules?.add?.expr || "",
|
||||
},
|
||||
update: {
|
||||
mode: normalizeRuleMode(table.schema.rules?.update?.mode),
|
||||
expr: table.schema.rules?.update?.expr || "",
|
||||
},
|
||||
delete: {
|
||||
mode: normalizeRuleMode(table.schema.rules?.delete?.mode),
|
||||
expr: table.schema.rules?.delete?.expr || "",
|
||||
},
|
||||
})
|
||||
setAuthMethods(normalizeAuthMethods(table.schema.auth))
|
||||
setActiveTab("schema")
|
||||
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
|
||||
}
|
||||
}) || []
|
||||
setColumns(transformedColumns)
|
||||
// Initialize rules with mode and expr from API
|
||||
// Convert empty string to "admin" for UI (Select doesn't allow empty string values)
|
||||
const normalizeMode = (mode: string | undefined) => {
|
||||
return mode === "" || !mode ? "admin" : mode
|
||||
}
|
||||
setRules({
|
||||
list: {
|
||||
mode: normalizeMode(table.schema.rules?.list?.mode),
|
||||
expr: table.schema.rules?.list?.expr || "",
|
||||
},
|
||||
get: {
|
||||
mode: normalizeMode(table.schema.rules?.get?.mode),
|
||||
expr: table.schema.rules?.get?.expr || "",
|
||||
},
|
||||
add: {
|
||||
mode: normalizeMode(table.schema.rules?.add?.mode),
|
||||
expr: table.schema.rules?.add?.expr || "",
|
||||
},
|
||||
update: {
|
||||
mode: normalizeMode(table.schema.rules?.update?.mode),
|
||||
expr: table.schema.rules?.update?.expr || "",
|
||||
},
|
||||
delete: {
|
||||
mode: normalizeMode(table.schema.rules?.delete?.mode),
|
||||
expr: table.schema.rules?.delete?.expr || "",
|
||||
},
|
||||
})
|
||||
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)
|
||||
const migrated = await migrateSchemaFieldsIfNeeded(apiClient, fresh)
|
||||
if (migrated) {
|
||||
setColumns(transformFieldsForEditor(migrated.schema?.fields))
|
||||
onTableUpdate(migrated)
|
||||
} else {
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
})()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to migrate legacy field types:", error)
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
})()
|
||||
}, [open, table, apiClient, onTableUpdate])
|
||||
|
||||
const addColumn = () => {
|
||||
@@ -338,6 +357,8 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
if ((updatedTable as any)?.error?.length > 0) throw (updatedTable as any).error
|
||||
|
||||
onTableUpdate(updatedTable)
|
||||
setColumns(transformFieldsForEditor(updatedTable.schema?.fields))
|
||||
setDeletedColumns([])
|
||||
setHasUnsavedChanges(false)
|
||||
toast({
|
||||
title: "Table Updated",
|
||||
@@ -418,6 +439,53 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleAuthMethodToggle = async (method: keyof AuthMethods, enabled: boolean) => {
|
||||
const previous = authMethods
|
||||
setAuthMethods({ ...authMethods, [method]: enabled })
|
||||
setSavingAuthMethod(method)
|
||||
|
||||
try {
|
||||
const updatedTable = await apiClient.call<TableMetadata>(`/api/v1/schemas/${table.schema.name}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({
|
||||
auth: { [method]: enabled },
|
||||
}),
|
||||
})
|
||||
|
||||
const apiError = getApiClientError(updatedTable)
|
||||
if (apiError) {
|
||||
throw new Error(apiError)
|
||||
}
|
||||
|
||||
const nextMethods = normalizeAuthMethods(updatedTable.schema?.auth ?? { ...previous, [method]: enabled })
|
||||
setAuthMethods(nextMethods)
|
||||
onTableUpdate({
|
||||
...updatedTable,
|
||||
schema: {
|
||||
...updatedTable.schema,
|
||||
auth: nextMethods,
|
||||
},
|
||||
})
|
||||
|
||||
toast({
|
||||
title: enabled ? "Setting Enabled" : "Setting Disabled",
|
||||
description: `${authMethodLabel(method)} ${enabled ? "enabled" : "disabled"} for ${table.schema.name}.`,
|
||||
duration: 3000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to update auth methods:", error)
|
||||
setAuthMethods(previous)
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error instanceof Error ? error.message : "Failed to update auth methods",
|
||||
variant: "destructive",
|
||||
duration: 5000,
|
||||
})
|
||||
} finally {
|
||||
setSavingAuthMethod(null)
|
||||
}
|
||||
}
|
||||
|
||||
const isSystemColumn = (column: any) => {
|
||||
return column.system
|
||||
}
|
||||
@@ -504,16 +572,20 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DrawerDescription>Manage entity fields, OAuth providers, and access control rules</DrawerDescription>
|
||||
<DrawerDescription>
|
||||
{isAuthEntity
|
||||
? "Manage fields, login methods, OAuth providers, and access rules"
|
||||
: "Manage entity fields 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-3 mb-6">
|
||||
<TabsList className={`grid w-full mb-6 ${isAuthEntity ? "grid-cols-3" : "grid-cols-2"}`}>
|
||||
<TabsTrigger value="schema">Fields</TabsTrigger>
|
||||
<TabsTrigger value="oauth">OAuth</TabsTrigger>
|
||||
{isAuthEntity && <TabsTrigger value="auth">Auth</TabsTrigger>}
|
||||
<TabsTrigger value="rules">Access Rules</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -882,22 +954,121 @@ 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.
|
||||
{isAuthEntity && (
|
||||
<TabsContent value="auth" className="space-y-6">
|
||||
<div>
|
||||
<Label className="text-base font-medium">Login methods</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Control which sign-in options are available for this auth entity. Changes save immediately and
|
||||
only affect new logins.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5 pr-4">
|
||||
<Label className="text-base">Password</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Email/identity and password via <code className="bg-muted px-1 rounded text-xs">/login</code>
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={authMethods.password}
|
||||
disabled={savingAuthMethod !== null}
|
||||
onCheckedChange={(checked) => handleAuthMethodToggle("password", checked)}
|
||||
aria-label="Enable password login"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5 pr-4">
|
||||
<Label className="text-base">Email sign-in codes (OTP)</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Send a 6-digit code to the user's email. Requires SMTP in application settings.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={authMethods.otp}
|
||||
disabled={savingAuthMethod !== null}
|
||||
onCheckedChange={(checked) => handleAuthMethodToggle("otp", checked)}
|
||||
aria-label="Enable email sign-in codes"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5 pr-4">
|
||||
<Label className="text-base">OAuth</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Third-party providers. After enabling, configure and enable providers below.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={authMethods.oauth}
|
||||
disabled={savingAuthMethod !== null}
|
||||
onCheckedChange={(checked) => handleAuthMethodToggle("oauth", checked)}
|
||||
aria-label="Enable OAuth login"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-base font-medium">Email verification</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Require users to verify their email before a new login. Existing sessions keep working.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5 pr-4">
|
||||
<Label className="text-base">Require email verification</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
When on, password, OTP, and OAuth logins return{" "}
|
||||
<code className="bg-muted px-1 rounded text-xs">403</code> until{" "}
|
||||
<code className="bg-muted px-1 rounded text-xs">email_verified</code> is true. Needs SMTP and
|
||||
Site Domain for verification emails.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={authMethods.requireEmailVerification}
|
||||
disabled={savingAuthMethod !== null}
|
||||
onCheckedChange={(checked) => handleAuthMethodToggle("requireEmailVerification", checked)}
|
||||
aria-label="Require email verification before login"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{(authMethods.otp || authMethods.requireEmailVerification) && (
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground space-y-1">
|
||||
{authMethods.otp && (
|
||||
<p>
|
||||
OTP requires SMTP (<strong className="text-foreground">host</strong> and{" "}
|
||||
<strong className="text-foreground">from</strong>) under Settings.
|
||||
</p>
|
||||
)}
|
||||
{authMethods.requireEmailVerification && (
|
||||
<p>
|
||||
Verification emails also need <strong className="text-foreground">Site Domain</strong> set
|
||||
under Settings (General).
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{authMethods.oauth ? (
|
||||
<div className="space-y-4 pt-2 border-t">
|
||||
<OAuthEntityPanel
|
||||
entityName={table.schema.name}
|
||||
apiClient={apiClient}
|
||||
isActive={open && activeTab === "auth"}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground">
|
||||
Enable <strong className="text-foreground">OAuth</strong> above to register providers and turn
|
||||
them on for this entity.
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
<TabsContent value="rules" className="space-y-6">
|
||||
<div>
|
||||
@@ -1152,7 +1323,7 @@ export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpda
|
||||
Delete Entity
|
||||
</Button>
|
||||
)}
|
||||
{activeTab !== "oauth" && (
|
||||
{activeTab !== "auth" && (
|
||||
<Button
|
||||
onClick={activeTab === "schema" ? handleSaveSchema : handleSaveRules}
|
||||
disabled={isLoading}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, Key, MoreHorizontal } from "lucide-react"
|
||||
import { RefreshCw, Cog, FileText, Trash2, Search, Plus, Key, KeyRound, Mail, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
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"
|
||||
@@ -10,9 +11,10 @@ import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
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 { ApiClient, TableMetadata, buildEntityFileUrl, entityApiKeysApi, getApiClientError } from "@/lib/api"
|
||||
import { toApiKeyUsers } from "@/lib/entity-users"
|
||||
import { ApiKeysPanel, openCreateApiKeyDialog } from "@/components/api-keys/api-keys-panel"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { TableConfigDrawer } from "./table-config-drawer"
|
||||
import { TableRecordDocsDrawer } from "./table-records-docs-drawer"
|
||||
import { EditItemDrawer } from "./edit-item-drawer"
|
||||
@@ -50,6 +52,7 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
const [apiKeysReloadRequested, setApiKeysReloadRequested] = React.useState(0)
|
||||
const [apiKeysLoading, setApiKeysLoading] = React.useState(false)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const { toast } = useToast()
|
||||
|
||||
const isAuthEntity = table.schema.type === "auth"
|
||||
const entityUsers = React.useMemo(() => toApiKeyUsers(tableData), [tableData])
|
||||
@@ -223,6 +226,84 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
}
|
||||
}
|
||||
|
||||
const handleSendVerificationEmail = async (row: { email?: string }) => {
|
||||
const email = typeof row.email === "string" ? row.email.trim() : ""
|
||||
if (!email) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Email required",
|
||||
description: "This user has no email address.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.call(
|
||||
`/api/v1/auth/${encodeURIComponent(table.schema.name)}/verify-email/request`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email }),
|
||||
},
|
||||
)
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Verification Email Requested",
|
||||
description: "If an account exists for that email, we sent a verification link.",
|
||||
duration: 4000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to send verification email:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Could not send verification",
|
||||
description: error instanceof Error ? error.message : "Failed to send verification email.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleSendPasswordResetEmail = async (row: { email?: string }) => {
|
||||
const email = typeof row.email === "string" ? row.email.trim() : ""
|
||||
if (!email) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Email required",
|
||||
description: "This user has no email address.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.call(
|
||||
`/api/v1/auth/${encodeURIComponent(table.schema.name)}/password-reset/request`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email }),
|
||||
},
|
||||
)
|
||||
const error = getApiClientError(response)
|
||||
if (error) {
|
||||
throw new Error(error)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Password Reset Email Requested",
|
||||
description: "If an account exists for that email, we sent a password reset link.",
|
||||
duration: 4000,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to send password reset email:", error)
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Could not send password reset",
|
||||
description: error instanceof Error ? error.message : "Failed to send password reset email.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateApiKeyForUser = (userId: string) => {
|
||||
openCreateApiKeyDialog(setCreateApiKeyForUserId, setCreateApiKeyRequested, userId)
|
||||
setActiveTab("api-keys")
|
||||
@@ -237,8 +318,17 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
|
||||
switch (field.type) {
|
||||
case "bool":
|
||||
case "boolean":
|
||||
return value === true || value === "true" || value === 1 ? "true" : "false"
|
||||
case "boolean": {
|
||||
const isTrue = value === true || value === "true" || value === 1
|
||||
if (field.name === "email_verified") {
|
||||
return (
|
||||
<Badge variant={isTrue ? "secondary" : "outline"} className="text-xs">
|
||||
{isTrue ? "Verified" : "Unverified"}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
return isTrue ? "true" : "false"
|
||||
}
|
||||
|
||||
case "json":
|
||||
try {
|
||||
@@ -383,6 +473,14 @@ export function TableDetailView({ table, onBack, apiClient, onTableUpdate, onTab
|
||||
<Key className="mr-2 h-4 w-4" />
|
||||
Create API Key
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleSendVerificationEmail(row)}>
|
||||
<Mail className="mr-2 h-4 w-4" />
|
||||
Send verification email
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleSendPasswordResetEmail(row)}>
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
Reset password
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
|
||||
@@ -120,7 +120,7 @@ function SchemaReferenceSection() {
|
||||
const entityTypesExample = JSON.stringify(
|
||||
{
|
||||
base: "Standard CRUD entity with configurable access rules",
|
||||
auth: "User authentication entity — enables /auth/{name}/login, API keys, and OAuth",
|
||||
auth: "User authentication entity — login methods, email verification, API keys, and OAuth providers",
|
||||
view: "Read-only SQL view — requires view_query, mutations rejected",
|
||||
},
|
||||
null,
|
||||
|
||||
@@ -148,15 +148,133 @@ function AuthDocsSection({ entityName }: { entityName: string }) {
|
||||
<>
|
||||
<DocSectionHeading>Authentication</DocSectionHeading>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="GET"
|
||||
endpoint={`${authPrefix}/methods`}
|
||||
description="Public. Returns login method flags plus requireEmailVerification. Fetch this before login/register screens."
|
||||
requestExample={`curl "${baseUrl}${authPrefix}/methods"`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
status: 200,
|
||||
data: { password: true, otp: false, oauth: false, requireEmailVerification: false },
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
/>
|
||||
|
||||
<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."
|
||||
description="Password login with identity (email or user id) and password. Returns 403 when password is disabled or email verification is required and unfinished."
|
||||
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",
|
||||
email_verified: true,
|
||||
},
|
||||
},
|
||||
error: "",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
errors={[
|
||||
{ code: "400", message: "Bad Request — invalid credentials or OAuth-only account" },
|
||||
{ code: "403", message: "Method disabled, or verify email before signing in" },
|
||||
{ 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}/verify-email/request`}
|
||||
description="Resend verification email. Always returns sent:true (including unknown/already-verified addresses). Needs SMTP and siteDomain."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/verify-email/request" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{ "email": "user@example.com" }'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { sent: true }, error: "" }, null, 2)}
|
||||
errors={[
|
||||
{ code: "400", message: "Invalid email, SMTP missing, or siteDomain unset" },
|
||||
{ code: "429", message: "Rate limited" },
|
||||
{ code: "502", message: "Failed to send the verification email" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/verify-email`}
|
||||
description="Complete verification with the token from the email link (app-owned verify page). GET with ?token= returns HTML instead."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/verify-email" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{ "token": "verification_token_from_link" }'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { verified: true }, error: "" }, null, 2)}
|
||||
errors={[{ code: "400", message: "Invalid or expired verification link" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/password-reset/request`}
|
||||
description="Email a password reset link. Always returns sent:true (including unknown addresses). Needs SMTP and siteDomain. Link expires in 1 hour."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/password-reset/request" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{ "email": "user@example.com" }'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { sent: true }, error: "" }, null, 2)}
|
||||
errors={[
|
||||
{ code: "400", message: "Invalid email, SMTP missing, or siteDomain unset" },
|
||||
{ code: "429", message: "Rate limited" },
|
||||
{ code: "502", message: "Failed to send the password reset email" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/password-reset`}
|
||||
description="Set a new password with the token from the email link. GET with ?token= shows an HTML form."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/password-reset" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{ "token": "reset_token_from_link", "password": "new-secure-password" }'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { reset: true }, error: "" }, null, 2)}
|
||||
errors={[{ code: "400", message: "Invalid/expired link or weak password" }]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/otp/request`}
|
||||
description="Request a 6-digit email sign-in code. Always returns sent:true (even for unknown emails). Requires auth.otp and SMTP."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/otp/request" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{ "email": "user@example.com" }'`}
|
||||
responseExample={JSON.stringify({ status: 200, data: { sent: true }, error: "" }, null, 2)}
|
||||
errors={[
|
||||
{ code: "400", message: "Invalid email or SMTP not configured" },
|
||||
{ code: "403", message: "OTP login disabled" },
|
||||
{ code: "429", message: "Rate limited (IP or recipient)" },
|
||||
{ code: "502", message: "Failed to send the sign-in code" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<SimpleEndpointDoc
|
||||
method="POST"
|
||||
endpoint={`${authPrefix}/otp/login`}
|
||||
description="Exchange email + 6-digit OTP for a JWT. Code lasts 10 minutes; 5 wrong attempts invalidate it."
|
||||
requestExample={`curl -X POST "${baseUrl}${authPrefix}/otp/login" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"email": "user@example.com",
|
||||
"otp": "483920"
|
||||
}'`}
|
||||
responseExample={JSON.stringify(
|
||||
{
|
||||
@@ -171,9 +289,10 @@ function AuthDocsSection({ entityName }: { entityName: string }) {
|
||||
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" },
|
||||
{ code: "400", message: "Missing/invalid email or OTP format" },
|
||||
{ code: "401", message: "Invalid or expired sign-in code" },
|
||||
{ code: "403", message: "OTP login disabled" },
|
||||
{ code: "429", message: "Too Many Requests" },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -298,7 +417,7 @@ function AuthDocsSection({ entityName }: { entityName: string }) {
|
||||
<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."
|
||||
description="Only available when auth.oauth is true (see GET /methods). Browser redirect flow (PKCE) and account linking."
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
|
||||
55
lib/api.ts
55
lib/api.ts
@@ -40,6 +40,59 @@ export interface SchemaRules {
|
||||
update: RuleConfig
|
||||
}
|
||||
|
||||
/** Login methods and verification policy for auth-type entities (PATCH via schema `auth`). */
|
||||
export interface AuthMethods {
|
||||
password: boolean
|
||||
otp: boolean
|
||||
oauth: boolean
|
||||
requireEmailVerification: boolean
|
||||
}
|
||||
|
||||
export const DEFAULT_AUTH_METHODS: AuthMethods = {
|
||||
password: true,
|
||||
otp: false,
|
||||
oauth: false,
|
||||
requireEmailVerification: false,
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize schema auth flags for UI/API use.
|
||||
* Backward compatible: when `auth` is null/undefined (older schemas), password is ON
|
||||
* and otp/oauth/requireEmailVerification are OFF — matching pre-method-flag password-only login.
|
||||
*/
|
||||
export function normalizeAuthMethods(auth?: Partial<AuthMethods> | null): AuthMethods {
|
||||
if (auth == null) {
|
||||
return { ...DEFAULT_AUTH_METHODS }
|
||||
}
|
||||
|
||||
return {
|
||||
// Missing password key on a partial auth object also defaults to ON.
|
||||
password: auth.password ?? true,
|
||||
otp: auth.otp ?? false,
|
||||
oauth: auth.oauth ?? false,
|
||||
requireEmailVerification: auth.requireEmailVerification ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
export function authMethodLabel(method: keyof AuthMethods): string {
|
||||
switch (method) {
|
||||
case "otp":
|
||||
return "Email sign-in codes"
|
||||
case "oauth":
|
||||
return "OAuth"
|
||||
case "requireEmailVerification":
|
||||
return "Require email verification"
|
||||
case "password":
|
||||
default:
|
||||
return "Password login"
|
||||
}
|
||||
}
|
||||
|
||||
/** Public login-method flags for an auth entity. */
|
||||
export function entityAuthMethodsApi(entityName: string): string {
|
||||
return `/api/v1/auth/${encodeURIComponent(entityName)}/methods`
|
||||
}
|
||||
|
||||
export interface TableSchema {
|
||||
fields: TableField[]
|
||||
has_api: boolean
|
||||
@@ -48,6 +101,8 @@ export interface TableSchema {
|
||||
rules: SchemaRules
|
||||
system: boolean
|
||||
type: "base" | "auth" | "view"
|
||||
/** Present on auth entities: which login methods are enabled. */
|
||||
auth?: AuthMethods
|
||||
sql?: string
|
||||
}
|
||||
|
||||
|
||||
52
lib/auth-fields.ts
Normal file
52
lib/auth-fields.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { TableField } from "@/lib/api"
|
||||
|
||||
/** Auth-entity fields that are optional when OAuth (or other methods) can create accounts. */
|
||||
const OPTIONAL_AUTH_FIELD_NAMES = new Set(["password", "avatar"])
|
||||
|
||||
export function isOptionalAuthField(fieldName: string): boolean {
|
||||
return OPTIONAL_AUTH_FIELD_NAMES.has(fieldName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a field must be filled in the admin record form.
|
||||
* Password and avatar are never required on auth entities (OAuth-capable accounts).
|
||||
*/
|
||||
export function isFieldRequiredInForm(
|
||||
field: Pick<TableField, "name" | "required">,
|
||||
entityType: string,
|
||||
): boolean {
|
||||
if (entityType === "auth" && isOptionalAuthField(field.name)) {
|
||||
return false
|
||||
}
|
||||
return Boolean(field.required)
|
||||
}
|
||||
|
||||
/** Normalize auth schema field flags for UI (does not PATCH the server). */
|
||||
export function normalizeAuthSchemaField<T extends Pick<TableField, "name" | "required" | "system">>(
|
||||
field: T,
|
||||
entityType: string,
|
||||
): T {
|
||||
if (entityType !== "auth" || !isOptionalAuthField(field.name)) {
|
||||
return field
|
||||
}
|
||||
|
||||
return {
|
||||
...field,
|
||||
required: false,
|
||||
}
|
||||
}
|
||||
|
||||
const PASSWORD_ALPHABET =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*-_=+"
|
||||
|
||||
/** Cryptographically random password suitable for admin-created auth users. */
|
||||
export function generateRandomPassword(length = 20): string {
|
||||
const size = Math.max(12, Math.min(length, 64))
|
||||
const bytes = new Uint8Array(size)
|
||||
crypto.getRandomValues(bytes)
|
||||
let result = ""
|
||||
for (let i = 0; i < size; i++) {
|
||||
result += PASSWORD_ALPHABET[bytes[i]! % PASSWORD_ALPHABET.length]
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { ApiClient, TableField, TableMetadata } from "@/lib/api"
|
||||
import { normalizeAuthMethods } from "@/lib/api"
|
||||
import { normalizeAuthSchemaField } from "@/lib/auth-fields"
|
||||
import {
|
||||
appendPrecisionToFieldPayload,
|
||||
normalizeFieldTypeForEditor,
|
||||
@@ -19,16 +21,26 @@ export function normalizeSchemaField(field: TableField): TableField {
|
||||
}
|
||||
|
||||
export function normalizeTableSchema(table: TableMetadata): TableMetadata {
|
||||
if (!table.schema?.fields) {
|
||||
if (!table.schema) {
|
||||
return table
|
||||
}
|
||||
|
||||
const schema = {
|
||||
...table.schema,
|
||||
fields: table.schema.fields?.map((field) => {
|
||||
const typed = normalizeSchemaField(field)
|
||||
return normalizeAuthSchemaField(typed, table.schema.type)
|
||||
}) ?? table.schema.fields,
|
||||
}
|
||||
|
||||
// Older auth entities may omit `auth`; treat as password-only login.
|
||||
if (schema.type === "auth") {
|
||||
schema.auth = normalizeAuthMethods(schema.auth)
|
||||
}
|
||||
|
||||
return {
|
||||
...table,
|
||||
schema: {
|
||||
...table.schema,
|
||||
fields: table.schema.fields.map(normalizeSchemaField),
|
||||
},
|
||||
schema,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
42
lib/script-headers.tsx
Normal file
42
lib/script-headers.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
const HEAD_SCRIPTS =
|
||||
process.env.HEAD_SCRIPTS?.trim() ??
|
||||
process.env.NEXT_PUBLIC_HEAD_SCRIPTS?.trim() ??
|
||||
''
|
||||
|
||||
function parseScriptTags(html: string) {
|
||||
return html.match(/<script[\s\S]*?<\/script>/gi) ?? []
|
||||
}
|
||||
|
||||
function renderScriptTag(tag: string, index: number) {
|
||||
const src = tag.match(/\bsrc="([^"]+)"/)?.[1]
|
||||
const defer = /\bdefer\b/.test(tag)
|
||||
const dataDomain = tag.match(/\bdata-domain="([^"]+)"/)?.[1]
|
||||
const inline = tag.match(/<script[^>]*>([\s\S]*?)<\/script>/i)?.[1]?.trim()
|
||||
|
||||
if (src) {
|
||||
return (
|
||||
<script
|
||||
key={index}
|
||||
defer={defer || undefined}
|
||||
data-domain={dataDomain}
|
||||
src={src}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (inline) {
|
||||
return (
|
||||
<script key={index} dangerouslySetInnerHTML={{ __html: inline }} />
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function ScriptHeaders() {
|
||||
if (!HEAD_SCRIPTS) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <>{parseScriptTags(HEAD_SCRIPTS).map(renderScriptTag)}</>
|
||||
}
|
||||
452
openapi.yaml
452
openapi.yaml
@@ -91,13 +91,43 @@ paths:
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/methods:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: List enabled login methods
|
||||
description: |
|
||||
Public endpoint. Returns which login methods are enabled for this auth entity,
|
||||
plus `requireEmailVerification`.
|
||||
Defaults: `password` true; `otp`, `oauth`, and `requireEmailVerification` false.
|
||||
Clients should fetch this before rendering a login or register screen.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
responses:
|
||||
"200":
|
||||
description: Method flags
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
$ref: "#/components/schemas/AuthMethods"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/login:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Entity user login
|
||||
summary: Entity user password login
|
||||
description: |
|
||||
Authenticate against an auth-type entity and receive a JWT. Rate-limited to 5 attempts/minute per IP.
|
||||
The entity must be type `auth`, API-enabled, and not a system entity.
|
||||
Authenticate with identity (email or user id) and password. Rate-limited to 5 attempts/minute per IP.
|
||||
Returns **403** when `auth.password` is disabled, or when `requireEmailVerification` is on and
|
||||
`email_verified` is false (`Verify your email before signing in.`).
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
@@ -121,6 +151,12 @@ paths:
|
||||
$ref: "#/components/schemas/AuthTokenResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"403":
|
||||
description: Password login disabled for this entity
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"429":
|
||||
@@ -128,6 +164,372 @@ paths:
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/otp/request:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Request email sign-in code
|
||||
description: |
|
||||
Sends a 6-digit OTP to the given email when an account exists. Always returns
|
||||
`{ "sent": true }` for unknown emails as well (no account enumeration).
|
||||
Requires `auth.otp` enabled and SMTP configured. Rate-limited: 5/min per IP;
|
||||
3 emails/hour per recipient.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [email]
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
responses:
|
||||
"200":
|
||||
description: Request accepted (sent or silently ignored for unknown email)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
sent:
|
||||
type: boolean
|
||||
example: true
|
||||
"400":
|
||||
description: Invalid email or SMTP not configured
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"403":
|
||||
description: OTP login disabled for this entity
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"429":
|
||||
$ref: "#/components/responses/TooManyRequests"
|
||||
"502":
|
||||
description: Failed to send the sign-in code
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/otp/login:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Login with email sign-in code
|
||||
description: |
|
||||
Exchange a 6-digit OTP for a JWT (same shape as password login). Code lifetime is
|
||||
10 minutes; 5 wrong attempts invalidate the code. Single-use on success.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [email, otp]
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
otp:
|
||||
type: string
|
||||
pattern: "^[0-9]{6}$"
|
||||
description: Exactly 6 digits as a string (preserves leading zeros)
|
||||
responses:
|
||||
"200":
|
||||
description: Login successful
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
$ref: "#/components/schemas/AuthTokenResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
description: Invalid or expired sign-in code
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"403":
|
||||
description: OTP login disabled for this entity
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"429":
|
||||
$ref: "#/components/responses/TooManyRequests"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/verify-email:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Verify email via link (HTML)
|
||||
description: |
|
||||
Opens from the verification email link (`?token=`). Returns a short HTML success/failure page.
|
||||
Token lasts 24 hours and is single-use. Prefer this when the app does not own a verify page.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
- name: token
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: HTML verification result page
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
"400":
|
||||
description: Invalid or expired verification link
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Verify email with token (JSON)
|
||||
description: |
|
||||
App-owned verify flow. Body contains the token from the email link query string.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [token]
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: Email verified
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
verified:
|
||||
type: boolean
|
||||
example: true
|
||||
"400":
|
||||
description: Invalid or expired verification link
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/verify-email/request:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Resend email verification link
|
||||
description: |
|
||||
Always returns `{ "sent": true }` for unknown or already-verified addresses (no enumeration).
|
||||
Requires SMTP and `siteDomain`. Rate-limited like OTP (5/min per IP; 3 emails/hour per recipient).
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [email]
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
responses:
|
||||
"200":
|
||||
description: Request accepted
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
sent:
|
||||
type: boolean
|
||||
example: true
|
||||
"400":
|
||||
description: Invalid email, SMTP missing, or siteDomain unset
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"429":
|
||||
$ref: "#/components/responses/TooManyRequests"
|
||||
"502":
|
||||
description: Failed to send the verification email
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/password-reset/request:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Email a password reset link
|
||||
description: |
|
||||
Always returns `{ "sent": true }` for unknown addresses (no enumeration).
|
||||
Requires SMTP and `siteDomain`. Link expires in 1 hour. Rate-limited like OTP
|
||||
(5/min per IP; 3 emails/hour per recipient).
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [email]
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
responses:
|
||||
"200":
|
||||
description: Request accepted
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
sent:
|
||||
type: boolean
|
||||
example: true
|
||||
"400":
|
||||
description: Invalid email, SMTP missing, or siteDomain unset
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"429":
|
||||
$ref: "#/components/responses/TooManyRequests"
|
||||
"502":
|
||||
description: Failed to send the password reset email
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/password-reset:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Password reset form (HTML)
|
||||
description: |
|
||||
Opens from the reset email link (`?token=`). Shows a form to choose a new password.
|
||||
Token lasts 1 hour and is single-use.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
- name: token
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: HTML password reset form
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
"400":
|
||||
description: Missing token
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Reset password with token (JSON)
|
||||
description: |
|
||||
App-owned or form submit flow. Body contains the token from the email link and the new password
|
||||
(min 8 characters, no whitespace). Existing sessions for the account are invalidated.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [token, password]
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
format: password
|
||||
minLength: 8
|
||||
responses:
|
||||
"200":
|
||||
description: Password updated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiEnvelope"
|
||||
- type: object
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
properties:
|
||||
reset:
|
||||
type: boolean
|
||||
example: true
|
||||
"400":
|
||||
description: Invalid/expired link or weak password
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiEnvelope"
|
||||
"500":
|
||||
$ref: "#/components/responses/InternalError"
|
||||
|
||||
/auth/{entity_name}/refresh:
|
||||
post:
|
||||
tags: [Auth]
|
||||
@@ -268,7 +670,9 @@ paths:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Start OAuth login (redirect)
|
||||
description: Redirects the browser to the OAuth provider authorization URL (PKCE).
|
||||
description: |
|
||||
Redirects the browser to the OAuth provider authorization URL (PKCE).
|
||||
Returns **403** when `auth.oauth` is disabled for the entity.
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/EntityName"
|
||||
@@ -1852,6 +2256,29 @@ components:
|
||||
expr:
|
||||
type: string
|
||||
|
||||
AuthMethods:
|
||||
type: object
|
||||
description: |
|
||||
Login method and verification flags for an auth-type entity.
|
||||
Defaults: password on; otp, oauth, and requireEmailVerification off.
|
||||
When `auth` is omitted on older schemas, treat as password-only login.
|
||||
properties:
|
||||
password:
|
||||
type: boolean
|
||||
default: true
|
||||
otp:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Email sign-in codes
|
||||
oauth:
|
||||
type: boolean
|
||||
default: false
|
||||
requireEmailVerification:
|
||||
type: boolean
|
||||
default: false
|
||||
description: When true, new logins require email_verified until the user verifies.
|
||||
required: [password, otp, oauth, requireEmailVerification]
|
||||
|
||||
EntitySchema:
|
||||
type: object
|
||||
properties:
|
||||
@@ -1880,6 +2307,9 @@ components:
|
||||
$ref: "#/components/schemas/AccessRule"
|
||||
delete:
|
||||
$ref: "#/components/schemas/AccessRule"
|
||||
auth:
|
||||
$ref: "#/components/schemas/AuthMethods"
|
||||
description: Auth-entity login methods. Present when type is `auth`.
|
||||
view_query:
|
||||
type: string
|
||||
description: Required for `view` entities.
|
||||
@@ -1904,6 +2334,8 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: "#/components/schemas/AccessRule"
|
||||
auth:
|
||||
$ref: "#/components/schemas/AuthMethods"
|
||||
view_query:
|
||||
type: string
|
||||
|
||||
@@ -1920,6 +2352,18 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: "#/components/schemas/AccessRule"
|
||||
auth:
|
||||
type: object
|
||||
description: Partial update of login methods / verification. Only sent keys are changed.
|
||||
properties:
|
||||
password:
|
||||
type: boolean
|
||||
otp:
|
||||
type: boolean
|
||||
oauth:
|
||||
type: boolean
|
||||
requireEmailVerification:
|
||||
type: boolean
|
||||
view_query:
|
||||
type: string
|
||||
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"version": "0.4.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.3.9",
|
||||
"version": "0.4.3",
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@radix-ui/react-accordion": "1.2.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mantisbase-admin",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.3",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"export": "next build && next export",
|
||||
|
||||
Reference in New Issue
Block a user