first commit

This commit is contained in:
KodekaTeam committed 2026-06-02 00:17:50 +07:00
1 parent abb09fbea8
commit 72f6d49818
355 files changed
+121239 -3

No files matched your search

@@ -0,0 +1,165 @@
"use client";
import {
SESSION_TIMEOUT_OPTIONS,
THEME_OPTIONS,
TIMEZONE_OPTIONS,
} from "@/app/settings/components/settings-config";
import SettingsFooterActions from "@/app/settings/components/SettingsFooterActions";
import { FieldLabel } from "@/app/settings/components/SettingsPrimitives";
import type {
EditableSettings,
UpdateGeneralField,
} from "@/app/settings/components/settings-types";
interface GeneralSettingsPanelProps {
settings: EditableSettings;
updateGeneral: UpdateGeneralField;
saving: boolean;
resetting: boolean;
onReset: () => void;
onSave: () => void;
}
export default function GeneralSettingsPanel({
settings,
updateGeneral,
saving,
resetting,
onReset,
onSave,
}: GeneralSettingsPanelProps) {
return (
<div
className="card"
style={{ padding: 24, display: "flex", flexDirection: "column", gap: 20 }}
>
<h2
style={{
fontSize: 15,
fontWeight: 700,
color: "var(--text-primary)",
marginBottom: 20,
}}
>
General Settings
</h2>
<div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
gap: 16,
}}
>
<div>
<FieldLabel>Panel Name</FieldLabel>
<input
className="input"
readOnly
disabled
value={settings.general.panelName}
onChange={(event) =>
updateGeneral("panelName", event.target.value)
}
/>
</div>
<div>
<FieldLabel>Panel URL</FieldLabel>
<input
className="input"
readOnly
disabled
value={settings.general.panelUrl}
onChange={(event) =>
updateGeneral("panelUrl", event.target.value)
}
/>
</div>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
gap: 16,
}}
>
<div>
<FieldLabel>Timezone</FieldLabel>
<select
className="input"
style={{ appearance: "none" }}
value={settings.general.timezone}
onChange={(event) =>
updateGeneral("timezone", event.target.value)
}
>
{TIMEZONE_OPTIONS.map((timezone) => (
<option key={timezone} value={timezone}>
{timezone}
</option>
))}
</select>
</div>
<div>
<FieldLabel>Session Timeout</FieldLabel>
<select
className="input"
style={{ appearance: "none" }}
value={settings.general.sessionTimeoutMinutes}
onChange={(event) =>
updateGeneral(
"sessionTimeoutMinutes",
Number(event.target.value),
)
}
>
{SESSION_TIMEOUT_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
</div>
<div>
<FieldLabel>Theme</FieldLabel>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
{THEME_OPTIONS.map((theme) => {
const active = settings.general.theme === theme;
return (
<button
key={theme}
type="button"
onClick={() => updateGeneral("theme", theme)}
style={{
padding: "8px 20px",
borderRadius: 8,
border: `1px solid ${active ? "rgba(37,99,235,0.4)" : "var(--border)"}`,
background: active
? "rgba(37,99,235,0.1)"
: "var(--bg-input)",
color: active ? "#2563eb" : "var(--text-muted)",
fontSize: 13,
fontWeight: 500,
cursor: "pointer",
textTransform: "capitalize",
}}
>
{theme}
</button>
);
})}
</div>
</div>
</div>
<SettingsFooterActions
saving={saving}
resetting={resetting}
activeTabLabel="General"
onReset={onReset}
onSave={onSave}
/>
</div>
);
}
@@ -0,0 +1,461 @@
"use client";
import { useState } from "react";
import Image from "next/image";
import { Loader2, ShieldCheck } from "lucide-react";
import SettingsFooterActions from "@/app/settings/components/SettingsFooterActions";
import {
ActionButton,
FieldLabel,
Toggle,
} from "@/app/settings/components/SettingsPrimitives";
import type {
DisableTwoFactorFormState,
EditableSettings,
PasswordFormState,
SetDisableTwoFactorFormState,
SetEditableSettings,
SetPasswordFormState,
SetTwoFactorCode,
TwoFactorSetupState,
} from "@/app/settings/components/settings-types";
interface SecuritySettingsPanelProps {
settings: EditableSettings;
setSettings: SetEditableSettings;
passwordForm: PasswordFormState;
setPasswordForm: SetPasswordFormState;
passwordSaving: boolean;
actionLoading: string | null;
twoFactorSetup: TwoFactorSetupState | null;
twoFactorCode: string;
setTwoFactorCode: SetTwoFactorCode;
disableTwoFactorForm: DisableTwoFactorFormState;
setDisableTwoFactorForm: SetDisableTwoFactorFormState;
changePassword: () => Promise<void>;
startTwoFactorSetup: () => Promise<void>;
enableTwoFactor: () => Promise<void>;
disableTwoFactor: () => Promise<void>;
updateIpWhitelist: (value: string) => void;
cancelTwoFactorSetup: () => void;
saving: boolean;
resetting: boolean;
onReset: () => void;
onSave: () => void;
}
export default function SecuritySettingsPanel({
settings,
setSettings,
passwordForm,
setPasswordForm,
passwordSaving,
actionLoading,
twoFactorSetup,
twoFactorCode,
setTwoFactorCode,
disableTwoFactorForm,
setDisableTwoFactorForm,
changePassword,
startTwoFactorSetup,
enableTwoFactor,
disableTwoFactor,
updateIpWhitelist,
cancelTwoFactorSetup,
saving,
resetting,
onReset,
onSave,
}: SecuritySettingsPanelProps) {
const [activeSection, setActiveSection] = useState<
"password" | "twoFactor" | "whitelist"
>("password");
const securitySections = [
{ id: "password", label: "Password" },
{ id: "twoFactor", label: "Two-Factor Auth" },
{ id: "whitelist", label: "IP Whitelist" },
] as const;
return (
<div
className="card"
style={{ padding: 24, display: "flex", flexDirection: "column", gap: 20 }}
>
<h2
style={{
fontSize: 15,
fontWeight: 700,
color: "var(--text-primary)",
marginBottom: 20,
}}
>
Security Settings
</h2>
<div
style={{
display: "flex",
gap: 8,
flexWrap: "wrap",
padding: 6,
borderRadius: 12,
background: "var(--bg-input)",
border: "1px solid var(--border)",
alignSelf: "flex-start",
}}
>
{securitySections.map((section) => {
const active = activeSection === section.id;
return (
<button
key={section.id}
type="button"
onClick={() => setActiveSection(section.id)}
style={{
padding: "8px 14px",
borderRadius: 8,
border: active
? "1px solid rgba(37,99,235,0.24)"
: "1px solid transparent",
background: active ? "rgba(37,99,235,0.12)" : "transparent",
color: active ? "#2563eb" : "var(--text-secondary)",
fontSize: 13,
fontWeight: 600,
cursor: "pointer",
}}
>
{section.label}
</button>
);
})}
</div>
{activeSection === "password" ? (
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
<div>
<FieldLabel>Current Password</FieldLabel>
<input
className="input"
type="password"
autoComplete="new-password"
value={passwordForm.currentPassword}
onChange={(event) =>
setPasswordForm((current) => ({
...current,
currentPassword: event.target.value,
}))
}
placeholder="••••••••"
/>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
gap: 16,
}}
>
<div>
<FieldLabel>New Password</FieldLabel>
<input
className="input"
type="password"
autoComplete="new-password"
value={passwordForm.newPassword}
onChange={(event) =>
setPasswordForm((current) => ({
...current,
newPassword: event.target.value,
}))
}
placeholder="••••••••"
/>
</div>
<div>
<FieldLabel>Confirm Password</FieldLabel>
<input
className="input"
type="password"
autoComplete="new-password"
value={passwordForm.confirmPassword}
onChange={(event) =>
setPasswordForm((current) => ({
...current,
confirmPassword: event.target.value,
}))
}
placeholder="••••••••"
/>
</div>
</div>
<div style={{ display: "flex", justifyContent: "flex-end" }}>
<button
className="btn btn-primary"
type="button"
onClick={() => void changePassword()}
disabled={passwordSaving}
style={{ padding: "8px 16px" }}
>
{passwordSaving ? (
<Loader2 size={14} className="animate-spin" />
) : null}
Change Password
</button>
</div>
</div>
) : null}
{activeSection === "twoFactor" ? (
<div
style={{
padding: 16,
background: "var(--bg-input)",
borderRadius: 10,
border: "1px solid var(--border)",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: 16,
marginBottom: 16,
}}
>
<div style={{ display: "flex", gap: 12, alignItems: "center" }}>
<ShieldCheck
size={18}
style={{
color: settings.security.twoFactorEnabled
? "#10b981"
: "#2563eb",
}}
/>
<div>
<p
style={{
fontSize: 13,
fontWeight: 600,
color: "var(--text-primary)",
}}
>
Two-Factor Authentication (TOTP)
</p>
<p style={{ fontSize: 11, color: "var(--text-muted)" }}>
{settings.security.twoFactorEnabled
? "Login now requires your authenticator app code"
: "Generate a QR code and verify one 6-digit code before enabling"}
</p>
</div>
</div>
{!settings.security.twoFactorEnabled ? (
<ActionButton
onClick={() => void startTwoFactorSetup()}
loading={actionLoading === "2fa-setup"}
primary
>
<ShieldCheck size={13} /> Setup 2FA
</ActionButton>
) : null}
</div>
{!settings.security.twoFactorEnabled && twoFactorSetup ? (
<div
style={{
display: "grid",
gridTemplateColumns: "minmax(180px, 220px) 1fr",
gap: 20,
alignItems: "start",
}}
>
<div
style={{
padding: 12,
borderRadius: 10,
background: "white",
width: "fit-content",
}}
>
<Image
src={twoFactorSetup.qrCodeDataUrl}
alt="TOTP QR code"
width={200}
height={200}
style={{ display: "block" }}
unoptimized
/>
</div>
<div
style={{ display: "flex", flexDirection: "column", gap: 12 }}
>
<div style={{ fontSize: 12, color: "var(--text-secondary)" }}>
Manual setup key:{" "}
<strong style={{ color: "var(--text-primary)" }}>
{twoFactorSetup.manualEntryKey}
</strong>
</div>
<div>
<FieldLabel>Verify Authenticator Code</FieldLabel>
<input
className="input"
value={twoFactorCode}
inputMode="numeric"
placeholder="123456"
onChange={(event) =>
setTwoFactorCode(
event.target.value.replace(/\D/g, "").slice(0, 6),
)
}
style={{
maxWidth: 220,
letterSpacing: "0.24em",
fontVariantNumeric: "tabular-nums",
}}
/>
</div>
<div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
<ActionButton
onClick={() => void enableTwoFactor()}
loading={actionLoading === "2fa-enable"}
primary
>
<ShieldCheck size={13} /> Enable 2FA
</ActionButton>
<ActionButton onClick={cancelTwoFactorSetup}>
Cancel Setup
</ActionButton>
</div>
</div>
</div>
) : null}
{settings.security.twoFactorEnabled ? (
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
gap: 16,
}}
>
<div>
<FieldLabel>Current Password</FieldLabel>
<input
className="input"
type="password"
value={disableTwoFactorForm.currentPassword}
onChange={(event) =>
setDisableTwoFactorForm((current) => ({
...current,
currentPassword: event.target.value,
}))
}
/>
</div>
<div>
<FieldLabel>Authenticator Code</FieldLabel>
<input
className="input"
value={disableTwoFactorForm.code}
inputMode="numeric"
placeholder="123456"
onChange={(event) =>
setDisableTwoFactorForm((current) => ({
...current,
code: event.target.value.replace(/\D/g, "").slice(0, 6),
}))
}
style={{
letterSpacing: "0.24em",
fontVariantNumeric: "tabular-nums",
}}
/>
</div>
<div style={{ display: "flex", alignItems: "flex-end" }}>
<ActionButton
onClick={() => void disableTwoFactor()}
loading={actionLoading === "2fa-disable"}
>
Disable 2FA
</ActionButton>
</div>
</div>
) : null}
</div>
) : null}
{activeSection === "whitelist" ? (
<>
<div
style={{
padding: 14,
background: "var(--bg-input)",
borderRadius: 9,
border: "1px solid var(--border)",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: 16,
}}
>
<div>
<p
style={{
fontSize: 13,
fontWeight: 600,
color: "var(--text-primary)",
}}
>
IP Whitelist
</p>
<p style={{ fontSize: 11, color: "var(--text-muted)" }}>
Require approved IP addresses before panel access
</p>
</div>
<Toggle
checked={settings.security.ipWhitelistEnabled}
onChange={() =>
setSettings((current) => ({
...current,
security: {
...current.security,
ipWhitelistEnabled: !current.security.ipWhitelistEnabled,
},
}))
}
/>
</div>
{settings.security.ipWhitelistEnabled ? (
<div style={{ marginTop: 14 }}>
<FieldLabel>Allowed IP Addresses</FieldLabel>
<textarea
className="input"
value={settings.security.ipWhitelist.join("\n")}
onChange={(event) => updateIpWhitelist(event.target.value)}
rows={5}
placeholder={
"One IP or CIDR per line\n203.0.113.10\n10.0.0.0/24"
}
style={{ resize: "vertical", minHeight: 120 }}
/>
</div>
) : null}
</div>
<SettingsFooterActions
saving={saving}
resetting={resetting}
activeTabLabel="Security"
onReset={onReset}
onSave={onSave}
/>
</>
) : null}
</div>
);
}
@@ -0,0 +1,65 @@
"use client";
import { Loader2, RotateCcw, Save } from "lucide-react";
interface SettingsFooterActionsProps {
saving: boolean;
resetting: boolean;
activeTabLabel: string;
onReset: () => void;
onSave: () => void;
}
export default function SettingsFooterActions({
saving,
resetting,
activeTabLabel,
onReset,
onSave,
}: SettingsFooterActionsProps) {
return (
<div
style={{
display: "flex",
justifyContent: "space-between",
gap: 12,
flexWrap: "wrap",
}}
>
<button
type="button"
className="btn btn-ghost"
onClick={onReset}
disabled={resetting || saving}
style={{ padding: "9px 18px", fontSize: 13 }}
>
{resetting ? (
<>
<Loader2 size={13} className="animate-spin" /> Resetting...
</>
) : (
<>
<RotateCcw size={13} /> Reset to Defaults
</>
)}
</button>
<button
className="btn btn-primary"
style={{ padding: "9px 22px", fontSize: 13 }}
onClick={onSave}
disabled={saving || resetting}
>
{saving ? (
<>
<Loader2 size={13} className="animate-spin" /> Saving...
</>
) : (
<>
<Save size={13} /> Save {activeTabLabel}
</>
)}
</button>
</div>
);
}
@@ -0,0 +1,135 @@
"use client";
import type { ReactNode } from "react";
import { Loader2 } from "lucide-react";
export function Toggle({
checked,
onChange,
disabled,
}: {
checked: boolean;
onChange: () => void;
disabled?: boolean;
}) {
return (
<button
type="button"
onClick={onChange}
disabled={disabled}
style={{
width: 42,
height: 24,
borderRadius: 12,
background: checked ? "#2563eb" : "var(--border)",
position: "relative",
cursor: disabled ? "not-allowed" : "pointer",
transition: "background 0.2s",
opacity: disabled ? 0.6 : 1,
border: "none",
}}
>
<span
style={{
position: "absolute",
top: 2,
left: checked ? 20 : 2,
width: 20,
height: 20,
borderRadius: "50%",
background: "white",
transition: "left 0.2s",
boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
}}
/>
</button>
);
}
export function FieldLabel({ children }: { children: ReactNode }) {
return (
<label
style={{
fontSize: 12,
color: "var(--text-secondary)",
marginBottom: 6,
display: "block",
fontWeight: 500,
}}
>
{children}
</label>
);
}
export function Banner({
message,
tone,
}: {
message: string;
tone: "success" | "error";
}) {
return (
<div
style={{
padding: "10px 14px",
borderRadius: 10,
border:
tone === "success"
? "1px solid rgba(16,185,129,0.3)"
: "1px solid rgba(239,68,68,0.3)",
background:
tone === "success"
? "rgba(16,185,129,0.1)"
: "rgba(239,68,68,0.1)",
color: tone === "success" ? "#10b981" : "#ef4444",
fontSize: 13,
}}
>
{message}
</div>
);
}
export function ActionButton({
children,
onClick,
loading,
disabled,
primary,
}: {
children: ReactNode;
onClick: () => void;
loading?: boolean;
disabled?: boolean;
primary?: boolean;
}) {
return (
<button
type="button"
className={primary ? "btn btn-primary" : "btn btn-ghost"}
onClick={onClick}
disabled={disabled || loading}
style={{ padding: "8px 14px", fontSize: 12 }}
>
{loading ? <Loader2 size={13} className="animate-spin" /> : children}
</button>
);
}
export function SettingsLoadingPanel() {
return (
<div
className="card"
style={{
padding: 24,
display: "flex",
alignItems: "center",
gap: 10,
}}
>
<Loader2 size={16} className="animate-spin" />
Loading settings...
</div>
);
}
@@ -0,0 +1,57 @@
"use client";
import { SETTINGS_TABS } from "@/app/settings/components/settings-config";
import type { SettingsTab } from "@/app/settings/components/settings-types";
interface SettingsTabsProps {
activeTab: SettingsTab;
onChange: (tab: SettingsTab) => void;
}
export default function SettingsTabs({
activeTab,
onChange,
}: SettingsTabsProps) {
return (
<div className="card" style={{ padding: 8, width: 200, flexShrink: 0 }}>
{SETTINGS_TABS.map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.id}
type="button"
onClick={() => onChange(tab.id)}
style={{
display: "flex",
alignItems: "center",
gap: 10,
width: "100%",
padding: "9px 12px",
borderRadius: 8,
cursor: "pointer",
background:
activeTab === tab.id ? "rgba(37,99,235,0.12)" : "transparent",
color: activeTab === tab.id ? "#2563eb" : "var(--text-secondary)",
fontSize: 13,
fontWeight: 500,
marginBottom: 2,
textAlign: "left",
border:
activeTab === tab.id
? "1px solid rgba(37,99,235,0.24)"
: "1px solid transparent",
}}
>
<Icon
size={14}
style={{
color: activeTab === tab.id ? "#2563eb" : "var(--text-muted)",
}}
/>
{tab.label}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,34 @@
import { Lock, Settings, type LucideIcon } from "lucide-react";
import type { SettingsTab } from "@/app/settings/components/settings-types";
export const TIMEZONE_OPTIONS = [
"Asia/Jakarta",
"UTC",
"America/New_York",
"Europe/London",
"Asia/Singapore",
];
export const THEME_OPTIONS = ["dark", "light", "system"] as const;
export const SESSION_TIMEOUT_OPTIONS = [
{ label: "30 minutes", value: 30 },
{ label: "1 hour", value: 60 },
{ label: "4 hours", value: 240 },
{ label: "24 hours", value: 1440 },
{ label: "Never", value: 0 },
];
export const SETTINGS_TABS: Array<{
id: SettingsTab;
label: string;
icon: LucideIcon;
}> = [
{ id: "general", label: "General", icon: Settings },
{ id: "security", label: "Security", icon: Lock },
];
export const ACTIVE_TAB_LABELS: Record<SettingsTab, string> = {
general: "General",
security: "Security",
};
@@ -0,0 +1,52 @@
import type { Dispatch, SetStateAction } from "react";
import type { SettingsRecord } from "@/lib/api";
export type SettingsTab = "general" | "security";
export type IntegrationProvider = "cloudflare" | "awsS3" | "github" | "gitlab";
export type EditableSettings = SettingsRecord & {
integrations: {
cloudflare: SettingsRecord["integrations"]["cloudflare"] & {
apiToken: string;
};
awsS3: SettingsRecord["integrations"]["awsS3"] & {
secretAccessKey: string;
};
github: SettingsRecord["integrations"]["github"] & {
token: string;
};
gitlab: SettingsRecord["integrations"]["gitlab"] & {
token: string;
};
};
};
export type PasswordFormState = {
currentPassword: string;
newPassword: string;
confirmPassword: string;
};
export type DisableTwoFactorFormState = {
currentPassword: string;
code: string;
};
export type TwoFactorSetupState = {
qrCodeDataUrl: string;
manualEntryKey: string;
otpauthUrl: string;
};
export type SetEditableSettings = Dispatch<SetStateAction<EditableSettings>>;
export type SetPasswordFormState = Dispatch<SetStateAction<PasswordFormState>>;
export type SetDisableTwoFactorFormState = Dispatch<
SetStateAction<DisableTwoFactorFormState>
>;
export type SetTwoFactorCode = Dispatch<SetStateAction<string>>;
export type UpdateGeneralField = <K extends keyof EditableSettings["general"]>(
key: K,
value: EditableSettings["general"][K],
) => void;
@@ -0,0 +1,102 @@
import type { SettingsRecord, UpdateSettingsBody } from "@/lib/api";
import type { EditableSettings } from "@/app/settings/components/settings-types";
import { resolvePublicAppOrigin } from "@/server/lib/public-url";
export const emptySettings = (): EditableSettings => ({
general: {
panelName: process.env.NEXT_PUBLIC_PANEL_NAME || "DOKTAINER",
panelUrl: resolvePublicAppOrigin(),
timezone: process.env.NEXT_PUBLIC_PANEL_TIMEZONE || "Asia/Jakarta",
theme: "dark",
sessionTimeoutMinutes: 30,
},
notifications: {
providers: [],
},
security: {
twoFactorEnabled: false,
twoFactorPendingSetup: false,
ipWhitelistEnabled: false,
ipWhitelist: [],
},
integrations: {
cloudflare: {
connected: false,
zoneId: "",
hasApiToken: false,
apiToken: "",
},
awsS3: {
connected: false,
accessKeyId: "",
region: "",
bucket: "",
hasSecretAccessKey: false,
secretAccessKey: "",
},
github: {
connected: false,
hasToken: false,
token: "",
},
gitlab: {
connected: false,
hasToken: false,
token: "",
},
},
});
export function toEditableSettings(source: SettingsRecord): EditableSettings {
return {
...source,
integrations: {
cloudflare: {
...source.integrations.cloudflare,
apiToken: "",
},
awsS3: {
...source.integrations.awsS3,
secretAccessKey: "",
},
github: {
...source.integrations.github,
token: "",
},
gitlab: {
...source.integrations.gitlab,
token: "",
},
},
};
}
export function toPayload(source: EditableSettings): UpdateSettingsBody {
return {
general: source.general,
notifications: source.notifications,
security: source.security,
integrations: {
cloudflare: {
connected: source.integrations.cloudflare.connected,
zoneId: source.integrations.cloudflare.zoneId,
apiToken: source.integrations.cloudflare.apiToken,
},
awsS3: {
connected: source.integrations.awsS3.connected,
accessKeyId: source.integrations.awsS3.accessKeyId,
secretAccessKey: source.integrations.awsS3.secretAccessKey,
region: source.integrations.awsS3.region,
bucket: source.integrations.awsS3.bucket,
},
github: {
connected: source.integrations.github.connected,
token: source.integrations.github.token,
},
gitlab: {
connected: source.integrations.gitlab.connected,
token: source.integrations.gitlab.token,
},
},
};
}
+363
View File
@@ -0,0 +1,363 @@
"use client";
import { useEffect, useState } from "react";
import GuardedPage from "@/components/GuardedPage";
import { auth, settingsApi, type SettingsRecord } from "@/lib/api";
import { getStoredTheme, storeUiPreferences } from "@/lib/preferences";
import GeneralSettingsPanel from "@/app/settings/components/GeneralSettingsPanel";
import SecuritySettingsPanel from "@/app/settings/components/SecuritySettingsPanel";
import {
Banner,
SettingsLoadingPanel,
} from "@/app/settings/components/SettingsPrimitives";
import SettingsTabs from "@/app/settings/components/SettingsTabs";
import { ACTIVE_TAB_LABELS } from "@/app/settings/components/settings-config";
import type {
DisableTwoFactorFormState,
EditableSettings,
PasswordFormState,
SettingsTab,
TwoFactorSetupState,
} from "@/app/settings/components/settings-types";
import {
emptySettings,
toEditableSettings,
toPayload,
} from "@/app/settings/components/settings-utils";
export default function SettingsPage() {
const [activeTab, setActiveTab] = useState<SettingsTab>("general");
const [settings, setSettings] = useState<EditableSettings>(emptySettings);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [resetting, setResetting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [passwordForm, setPasswordForm] = useState<PasswordFormState>({
currentPassword: "",
newPassword: "",
confirmPassword: "",
});
const [passwordSaving, setPasswordSaving] = useState(false);
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [twoFactorSetup, setTwoFactorSetup] =
useState<TwoFactorSetupState | null>(null);
const [twoFactorCode, setTwoFactorCode] = useState("");
const [disableTwoFactorForm, setDisableTwoFactorForm] =
useState<DisableTwoFactorFormState>({
currentPassword: "",
code: "",
});
const syncSettingsFromServer = (
source: SettingsRecord,
options?: { preserveStoredTheme?: boolean },
) => {
const theme = options?.preserveStoredTheme
? getStoredTheme()
: source.general.theme;
const nextSettings = toEditableSettings({
...source,
general: {
...source.general,
theme,
},
});
setSettings(nextSettings);
storeUiPreferences({
panelName: source.general.panelName,
panelUrl: source.general.panelUrl,
theme,
sessionTimeoutMinutes: source.general.sessionTimeoutMinutes,
});
};
useEffect(() => {
let mounted = true;
const loadSettings = async () => {
setLoading(true);
setError(null);
try {
const response = await settingsApi.get();
if (!mounted) return;
syncSettingsFromServer(response.data, { preserveStoredTheme: true });
} catch (err) {
if (!mounted) return;
setError(
err instanceof Error ? err.message : "Failed to load settings",
);
} finally {
if (mounted) setLoading(false);
}
};
void loadSettings();
return () => {
mounted = false;
};
}, []);
useEffect(() => {
if (!success) return;
const timer = window.setTimeout(() => setSuccess(null), 3000);
return () => window.clearTimeout(timer);
}, [success]);
const updateIpWhitelist = (value: string) => {
setSettings((current) => ({
...current,
security: {
...current.security,
ipWhitelist: value
.split("\n")
.map((entry) => entry.trim())
.filter(Boolean),
},
}));
};
const updateGeneral = <K extends keyof EditableSettings["general"]>(
key: K,
value: EditableSettings["general"][K],
) => {
setSettings((current) => ({
...current,
general: {
...current.general,
[key]: value,
},
}));
};
const saveSettings = async () => {
setSaving(true);
setError(null);
setSuccess(null);
try {
const response = await settingsApi.update(toPayload(settings));
syncSettingsFromServer(response.data);
setSuccess(
response.message || `${ACTIVE_TAB_LABELS[activeTab]} settings saved`,
);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to save settings");
} finally {
setSaving(false);
}
};
const resetSettings = async () => {
setResetting(true);
setError(null);
setSuccess(null);
try {
const response = await settingsApi.reset();
syncSettingsFromServer(response.data);
setTwoFactorSetup(null);
setTwoFactorCode("");
setSuccess(response.message || "Settings reset to defaults");
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to reset settings");
} finally {
setResetting(false);
}
};
const changePassword = async () => {
setError(null);
setSuccess(null);
if (!passwordForm.currentPassword || !passwordForm.newPassword) {
setError("Current password and new password are required");
return;
}
if (passwordForm.newPassword.length < 8) {
setError("New password must be at least 8 characters");
return;
}
if (passwordForm.newPassword !== passwordForm.confirmPassword) {
setError("Password confirmation does not match");
return;
}
setPasswordSaving(true);
try {
const response = await auth.changePassword(
passwordForm.currentPassword,
passwordForm.newPassword,
);
setPasswordForm({
currentPassword: "",
newPassword: "",
confirmPassword: "",
});
setSuccess(response.message || "Password updated successfully");
} catch (err) {
setError(
err instanceof Error ? err.message : "Failed to update password",
);
} finally {
setPasswordSaving(false);
}
};
const runAction = async (key: string, action: () => Promise<void>) => {
setActionLoading(key);
setError(null);
setSuccess(null);
try {
await action();
} catch (err) {
setError(err instanceof Error ? err.message : "Action failed");
} finally {
setActionLoading(null);
}
};
const refreshSettings = async () => {
const response = await settingsApi.get();
syncSettingsFromServer(response.data, { preserveStoredTheme: true });
};
const startTwoFactorSetup = async () => {
await runAction("2fa-setup", async () => {
const response = await auth.setupTwoFactor();
setTwoFactorSetup(response.data);
setTwoFactorCode("");
const refreshed = await settingsApi.get();
syncSettingsFromServer(refreshed.data, { preserveStoredTheme: true });
setSuccess(
response.message || "Scan QR code lalu verifikasi dengan kode 6 digit",
);
});
};
const enableTwoFactor = async () => {
if (twoFactorCode.length !== 6) {
setError("Masukkan 6 digit authentication code");
return;
}
await runAction("2fa-enable", async () => {
const response = await auth.enableTwoFactor(twoFactorCode);
setTwoFactorSetup(null);
setTwoFactorCode("");
await refreshSettings();
setSuccess(response.message || "Two-factor authentication enabled");
});
};
const disableTwoFactor = async () => {
if (
!disableTwoFactorForm.currentPassword ||
disableTwoFactorForm.code.length !== 6
) {
setError(
"Masukkan current password dan 6 digit code untuk menonaktifkan 2FA",
);
return;
}
await runAction("2fa-disable", async () => {
const response = await auth.disableTwoFactor(
disableTwoFactorForm.currentPassword,
disableTwoFactorForm.code,
);
setDisableTwoFactorForm({ currentPassword: "", code: "" });
setTwoFactorSetup(null);
await refreshSettings();
setSuccess(response.message || "Two-factor authentication disabled");
});
};
const cancelTwoFactorSetup = () => {
setTwoFactorSetup(null);
setTwoFactorCode("");
};
return (
<GuardedPage
route="/settings"
title="Settings"
subtitle={`Configure your ${process.env.NEXT_PUBLIC_PANEL_NAME ?? "DOKTAINER"} preferences`}
redirectSubtitle="Redirecting to a page allowed for your role"
>
<div
className="animate-slide-in"
style={{
display: "flex",
gap: 20,
alignItems: "flex-start",
flexWrap: "wrap",
}}
>
<SettingsTabs activeTab={activeTab} onChange={setActiveTab} />
<div
style={{
flex: 1,
minWidth: 0,
display: "flex",
flexDirection: "column",
gap: 16,
}}
>
{error ? <Banner message={error} tone="error" /> : null}
{success ? <Banner message={success} tone="success" /> : null}
{loading ? (
<SettingsLoadingPanel />
) : (
<>
{activeTab === "general" ? (
<GeneralSettingsPanel
settings={settings}
updateGeneral={updateGeneral}
saving={saving}
resetting={resetting}
onReset={() => void resetSettings()}
onSave={() => void saveSettings()}
/>
) : null}
{activeTab === "security" ? (
<SecuritySettingsPanel
settings={settings}
setSettings={setSettings}
passwordForm={passwordForm}
setPasswordForm={setPasswordForm}
passwordSaving={passwordSaving}
actionLoading={actionLoading}
twoFactorSetup={twoFactorSetup}
twoFactorCode={twoFactorCode}
setTwoFactorCode={setTwoFactorCode}
disableTwoFactorForm={disableTwoFactorForm}
setDisableTwoFactorForm={setDisableTwoFactorForm}
changePassword={changePassword}
startTwoFactorSetup={startTwoFactorSetup}
enableTwoFactor={enableTwoFactor}
disableTwoFactor={disableTwoFactor}
updateIpWhitelist={updateIpWhitelist}
cancelTwoFactorSetup={cancelTwoFactorSetup}
saving={saving}
resetting={resetting}
onReset={() => void resetSettings()}
onSave={() => void saveSettings()}
/>
) : null}
</>
)}
</div>
</div>
</GuardedPage>
);
}