feat: Implement settings password protection with a dedicated gate, management UI, and API integration.

This commit is contained in:
kuekhaoyang
2026-02-16 22:54:16 +08:00
parent a8c4586859
commit 98e314e31a
9 changed files with 432 additions and 6 deletions
+182
View File
@@ -0,0 +1,182 @@
'use client';
import { useState, useEffect } from 'react';
import { settingsStore } from '@/lib/store/settings-store';
import { Lock } from 'lucide-react';
const SESSION_KEY = 'kvideo-settings-unlocked';
export function SettingsPasswordGate({ children }: { children: React.ReactNode }) {
const [isLocked, setIsLocked] = useState(true);
const [password, setPassword] = useState('');
const [error, setError] = useState(false);
const [isClient, setIsClient] = useState(false);
const [hasEnvSettingsPassword, setHasEnvSettingsPassword] = useState(false);
const [isValidating, setIsValidating] = useState(false);
useEffect(() => {
let mounted = true;
const init = async () => {
const settings = settingsStore.getSettings();
const sessionUnlocked = sessionStorage.getItem(SESSION_KEY) === 'true';
const isProtected = (settings.settingsPasswordEnabled && settings.settingsPasswords.length > 0);
const localLocked = isProtected && !sessionUnlocked;
if (mounted) {
setIsLocked(localLocked);
setIsClient(true);
}
// Fetch remote config for env settings password
try {
const res = await fetch('/api/config');
if (!res.ok) throw new Error('Failed to fetch config');
const data = await res.json();
if (mounted) {
setHasEnvSettingsPassword(data.hasEnvSettingsPassword);
const isProtectedNow = (settings.settingsPasswordEnabled && settings.settingsPasswords.length > 0) || data.hasEnvSettingsPassword;
setIsLocked(isProtectedNow && !sessionUnlocked);
}
} catch (e) {
console.error('SettingsPasswordGate init failed:', e);
}
};
init();
return () => { mounted = false; };
}, []);
// Subscribe to settings changes (auto-unlock if all passwords removed)
useEffect(() => {
const handleSettingsUpdate = () => {
const settings = settingsStore.getSettings();
const sessionUnlocked = sessionStorage.getItem(SESSION_KEY) === 'true';
const isProtected = (settings.settingsPasswordEnabled && settings.settingsPasswords.length > 0) || hasEnvSettingsPassword;
if (!isProtected) {
setIsLocked(false);
} else if (!sessionUnlocked) {
setIsLocked(true);
}
};
const unsubscribe = settingsStore.subscribe(handleSettingsUpdate);
return () => unsubscribe();
}, [hasEnvSettingsPassword]);
const handleUnlock = async (e: React.FormEvent) => {
e.preventDefault();
setIsValidating(true);
const settings = settingsStore.getSettings();
const setUnlocked = () => {
sessionStorage.setItem(SESSION_KEY, 'true');
setIsLocked(false);
setError(false);
setIsValidating(false);
};
// Check local settings passwords first
if (settings.settingsPasswords.includes(password)) {
setUnlocked();
return;
}
// Then check env password via API
if (hasEnvSettingsPassword) {
try {
const res = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password, type: 'settings' }),
});
const data = await res.json();
if (data.valid) {
setUnlocked();
return;
}
} catch {
// API error
}
}
// Password didn't match
setError(true);
setIsValidating(false);
const form = document.getElementById('settings-password-form');
form?.classList.add('animate-shake');
setTimeout(() => form?.classList.remove('animate-shake'), 500);
};
if (!isClient) return null;
if (!isLocked) {
return <>{children}</>;
}
return (
<div className="min-h-screen flex items-center justify-center bg-[var(--bg-color)] bg-[image:var(--bg-image)] text-[var(--text-color)]">
<div className="w-full max-w-md p-4">
<form
id="settings-password-form"
onSubmit={handleUnlock}
className="bg-[var(--glass-bg)] backdrop-blur-[25px] saturate-[180%] border border-[var(--glass-border)] rounded-[var(--radius-2xl)] p-8 shadow-[var(--shadow-md)] flex flex-col items-center gap-6 transition-all duration-[0.4s] cubic-bezier(0.2,0.8,0.2,1)"
>
<div className="w-16 h-16 rounded-[var(--radius-full)] bg-[var(--accent-color)]/10 flex items-center justify-center text-[var(--accent-color)] mb-2 shadow-[var(--shadow-sm)] border border-[var(--glass-border)]">
<Lock size={32} />
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold"></h2>
<p className="text-[var(--text-color-secondary)]"></p>
</div>
<div className="w-full space-y-4">
<div className="space-y-2">
<input
type="password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
setError(false);
}}
placeholder="输入密码..."
className={`w-full px-4 py-3 rounded-[var(--radius-2xl)] bg-[var(--glass-bg)] border ${error ? 'border-red-500' : 'border-[var(--glass-border)]'
} focus:outline-none focus:border-[var(--accent-color)] focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--accent-color)_30%,transparent)] transition-all duration-[0.4s] cubic-bezier(0.2,0.8,0.2,1) text-[var(--text-color)] placeholder-[var(--text-color-secondary)]`}
autoFocus
/>
{error && (
<p className="text-sm text-red-500 text-center animate-pulse">
</p>
)}
</div>
<button
type="submit"
className="w-full py-3 px-4 bg-[var(--accent-color)] text-white font-bold rounded-[var(--radius-2xl)] hover:translate-y-[-2px] hover:brightness-110 shadow-[var(--shadow-sm)] hover:shadow-[0_4px_8px_var(--shadow-color)] active:translate-y-0 active:scale-[0.98] transition-all duration-200"
>
</button>
</div>
</form>
</div>
<style jsx global>{`
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
.animate-shake {
animation: shake 0.3s cubic-bezier(.36,.07,.19,.97) both;
}
`}</style>
</div>
);
}
@@ -0,0 +1,156 @@
'use client';
import { useState } from 'react';
import { SettingsSection } from './SettingsSection';
import { Trash2, Plus, Eye, EyeOff, Shield, ShieldCheck } from 'lucide-react';
import { Switch } from '@/components/ui/Switch';
interface SettingsPasswordSettingsProps {
enabled: boolean;
passwords: string[];
envSettingsPasswordSet: boolean;
onToggle: (enabled: boolean) => void;
onAdd: (password: string) => void;
onRemove: (password: string) => void;
}
export function SettingsPasswordSettings({
enabled,
passwords,
envSettingsPasswordSet,
onToggle,
onAdd,
onRemove,
}: SettingsPasswordSettingsProps) {
const [newPassword, setNewPassword] = useState('');
const [error, setError] = useState('');
const [showPassword, setShowPassword] = useState(false);
const handleAdd = (e: React.FormEvent) => {
e.preventDefault();
if (!newPassword) return;
if (passwords.includes(newPassword)) {
setError('密码已存在');
return;
}
onAdd(newPassword);
setNewPassword('');
setError('');
};
const isActive = enabled || envSettingsPasswordSet;
return (
<SettingsSection title="设置页密码保护" description="为设置页面单独设置密码保护,防止他人修改应用配置。">
<div className="space-y-6">
{/* Toggle - only shown if no env password */}
{!envSettingsPasswordSet && (
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-[var(--text-color)]">
</label>
<Switch
checked={enabled}
onChange={onToggle}
ariaLabel="启用设置页密码开关"
/>
</div>
)}
{/* Env Password Notice */}
{envSettingsPasswordSet && (
<div className="flex items-center gap-3 p-4 bg-[color-mix(in_srgb,var(--accent-color)_10%,transparent)] border border-[var(--accent-color)]/30 rounded-[var(--radius-2xl)]">
<ShieldCheck className="text-[var(--accent-color)] shrink-0" size={24} />
<div>
<p className="text-sm font-medium text-[var(--text-color)]">
</p>
<p className="text-xs text-[var(--text-color-secondary)]">
<code className="px-1 py-0.5 bg-[var(--glass-bg)] rounded">SETTINGS_PASSWORD</code>
</p>
</div>
</div>
)}
{isActive && (
<div className="space-y-4 pt-4 border-t border-[var(--glass-border)] animate-in fade-in slide-in-from-top-2">
{/* Local Passwords Section */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Shield size={16} className="text-[var(--text-color-secondary)]" />
<h4 className="text-sm font-medium text-[var(--text-color)]"></h4>
</div>
<p className="text-xs text-[var(--text-color-secondary)]">
/
</p>
{passwords.length === 0 && !envSettingsPasswordSet && (
<p className="text-sm text-[var(--text-color-secondary)] italic">
访
</p>
)}
{passwords.length === 0 && envSettingsPasswordSet && (
<p className="text-sm text-[var(--text-color-secondary)] italic">
</p>
)}
<div className="flex flex-wrap gap-2">
{passwords.map((pwd, index) => (
<div
key={index}
className="flex items-center gap-2 px-3 py-1.5 bg-[var(--glass-bg)] border border-[var(--glass-border)] rounded-[var(--radius-full)] text-sm transition-all duration-300 hover:scale-105"
>
<span className="font-mono">{showPassword ? pwd : '••••••'}</span>
<button
onClick={() => onRemove(pwd)}
className="text-[var(--text-color-secondary)] hover:text-red-500 transition-colors cursor-pointer"
title="删除密码"
>
<Trash2 size={14} />
</button>
</div>
))}
</div>
</div>
<form onSubmit={handleAdd} className="flex gap-2 items-start">
<div className="flex-1 space-y-1">
<div className="relative">
<input
type={showPassword ? "text" : "password"}
value={newPassword}
onChange={(e) => {
setNewPassword(e.target.value);
setError('');
}}
placeholder="添加新的设置密码..."
className="w-full px-4 py-2 pr-10 rounded-[var(--radius-2xl)] bg-[var(--glass-bg)] border border-[var(--glass-border)] focus:outline-none focus:border-[var(--accent-color)] focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--accent-color)_30%,transparent)] transition-all duration-[0.4s] cubic-bezier(0.2,0.8,0.2,1) text-sm"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-[var(--text-color-secondary)] hover:text-[var(--text-color)] transition-colors cursor-pointer"
>
{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
{error && <p className="text-xs text-red-500 pl-2">{error}</p>}
</div>
<button
type="submit"
disabled={!newPassword}
className="p-2 bg-[var(--accent-color)] text-white rounded-[var(--radius-2xl)] hover:translate-y-[-2px] hover:brightness-110 shadow-[var(--shadow-sm)] hover:shadow-[0_4px_8px_var(--shadow-color)] disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:shadow-none transition-all duration-200 cursor-pointer"
>
<Plus size={20} />
</button>
</form>
</div>
)}
</div>
</SettingsSection>
);
}