feat: add authentication and authorization system

Backend:
- AuthManager (api/auth_manager.py): server-side user store with bcrypt
  password hashing, account lockout after 5 failed attempts (15 min),
  and atomic file writes
- AuthRoutes (api/auth_routes.py): Blueprint at /api/auth/* — login,
  logout, me, change-password, admin reset-password, list-users
- app.py: register auth_bp blueprint; add enforce_auth before_request
  hook (401 for unauthenticated, 403 for wrong role; only active when
  auth store has users so pre-auth tests remain green); instantiate
  AuthManager; update POST /api/peers to require password >= 10 chars
  and auto-provision email + calendar + files + auth accounts with full
  rollback on any failure; extend DELETE /api/peers to tear down all
  four service accounts; add /api/peer/dashboard and /api/peer/services
  peer-scoped routes; fix is_local_request to also trust the last
  X-Forwarded-For entry appended by the reverse proxy (Caddy)
- Role-based access: admin for /api/* (except /api/auth/* which is
  public and /api/peer/* which is peer-only)
- setup_cell.py: generate and print initial admin password, store in
  .admin_initial_password with 0600 permissions; cleaned up on first
  admin login

Frontend:
- AuthContext.jsx: React context with login/logout/me state and Axios
  interceptor for automatic 401 redirect
- PrivateRoute.jsx: route guard component
- Login.jsx: login page with error handling and must-change-password
  redirect
- AccountSettings.jsx: change-password form for any authenticated user
- PeerDashboard.jsx: peer-role landing page (IP, service list)
- MyServices.jsx: peer service links page
- App.jsx, Sidebar.jsx: AuthContext integration, logout button,
  PrivateRoute wrappers, peer-role routing
- Peers.jsx, WireGuard.jsx, api.js: auth-aware API calls

Tests: 100 new auth tests all pass (test_auth_manager, test_auth_routes,
test_route_protection, test_peer_provisioning). Fix pre-existing test
failures: update WireGuard test keys to valid 44-char base64 format
(test_wireguard_manager, test_peer_wg_integration), add password field
and service manager mocks to test_api_endpoints peer tests, add auth
helpers to conftest.py. Full suite: 845 passed, 0 failures.

Fixed: .admin_initial_password security cleanup on bootstrap, username
minimum length (3 chars enforced by USERNAME_RE regex)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-25 15:00:06 -04:00
parent a338836bb8
commit 8650704316
23 changed files with 4618 additions and 1576 deletions
+211
View File
@@ -0,0 +1,211 @@
import React, { useState, useEffect } from 'react';
import { CheckCircle, XCircle, AlertTriangle } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { authAPI } from '../services/api';
export default function AccountSettings() {
const { user, changePassword } = useAuth();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
const [pwError, setPwError] = useState('');
const [pwLoading, setPwLoading] = useState(false);
const [adminUsers, setAdminUsers] = useState([]);
const [adminTarget, setAdminTarget] = useState('');
const [adminNewPw, setAdminNewPw] = useState('');
const [adminStatus, setAdminStatus] = useState(null);
const [adminError, setAdminError] = useState('');
const [adminLoading, setAdminLoading] = useState(false);
useEffect(() => {
if (user?.role === 'admin') {
authAPI.listUsers()
.then(r => {
const list = r.data || [];
setAdminUsers(list);
if (list.length > 0) setAdminTarget(list[0].username || list[0]);
})
.catch(() => {});
}
}, [user]);
const pwErrors = (() => {
const e = {};
if (newPassword && newPassword.length < 10) e.newPassword = 'Password must be at least 10 characters';
if (confirmPassword && newPassword !== confirmPassword) e.confirmPassword = 'Passwords do not match';
return e;
})();
const handleChangePassword = async e => {
e.preventDefault();
if (Object.keys(pwErrors).length) return;
setPwLoading(true);
setPwError('');
setPwStatus(null);
try {
await changePassword(oldPassword, newPassword);
setPwStatus('success');
setOldPassword('');
setNewPassword('');
setConfirmPassword('');
} catch (err) {
setPwError(err?.response?.data?.error || 'Failed to change password.');
} finally {
setPwLoading(false);
}
};
const handleAdminReset = async e => {
e.preventDefault();
if (!adminNewPw || adminNewPw.length < 10) {
setAdminError('Password must be at least 10 characters');
return;
}
setAdminLoading(true);
setAdminError('');
setAdminStatus(null);
try {
await authAPI.adminResetPassword(adminTarget, adminNewPw);
setAdminStatus('success');
setAdminNewPw('');
} catch (err) {
setAdminError(err?.response?.data?.error || 'Failed to reset password.');
} finally {
setAdminLoading(false);
}
};
return (
<div>
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">Account Settings</h1>
<p className="mt-1 text-gray-500 text-sm">Manage your login credentials</p>
</div>
{user?.must_change_password && (
<div className="mb-6 flex items-start gap-3 bg-yellow-50 border border-yellow-300 rounded-lg p-4">
<AlertTriangle className="h-5 w-5 text-yellow-600 flex-shrink-0 mt-0.5" />
<p className="text-sm text-yellow-800 font-medium">
You must change your password before continuing. Choose a new password below.
</p>
</div>
)}
<div className="card mb-4">
<h2 className="text-base font-semibold text-gray-900 mb-4">Change Password</h2>
<form onSubmit={handleChangePassword} className="space-y-4 max-w-sm">
<div>
<label className="block text-sm text-gray-600 mb-1">Current password</label>
<input
type="password"
value={oldPassword}
onChange={e => setOldPassword(e.target.value)}
autoComplete="current-password"
required
className="w-full text-sm border rounded px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-white"
/>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">New password</label>
<input
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
autoComplete="new-password"
required
className={`w-full text-sm border rounded px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-white ${pwErrors.newPassword ? 'border-red-400' : ''}`}
/>
{pwErrors.newPassword && <p className="text-xs text-red-500 mt-1">{pwErrors.newPassword}</p>}
<p className="text-xs text-gray-400 mt-1">Minimum 10 characters</p>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Confirm new password</label>
<input
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
autoComplete="new-password"
required
className={`w-full text-sm border rounded px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-white ${pwErrors.confirmPassword ? 'border-red-400' : ''}`}
/>
{pwErrors.confirmPassword && <p className="text-xs text-red-500 mt-1">{pwErrors.confirmPassword}</p>}
</div>
{pwError && (
<div className="flex items-center gap-2 text-sm text-red-600">
<XCircle className="h-4 w-4 flex-shrink-0" />
{pwError}
</div>
)}
{pwStatus === 'success' && (
<div className="flex items-center gap-2 text-sm text-green-600">
<CheckCircle className="h-4 w-4 flex-shrink-0" />
Password changed successfully.
</div>
)}
<button
type="submit"
disabled={pwLoading || Object.keys(pwErrors).length > 0 || !oldPassword || !newPassword || !confirmPassword}
className="btn btn-primary disabled:opacity-50"
>
{pwLoading ? 'Saving…' : 'Update Password'}
</button>
</form>
</div>
{user?.role === 'admin' && (
<div className="card">
<h2 className="text-base font-semibold text-gray-900 mb-1">Reset Another User's Password</h2>
<p className="text-sm text-gray-500 mb-4">Set a new password for any user account.</p>
<form onSubmit={handleAdminReset} className="space-y-4 max-w-sm">
<div>
<label className="block text-sm text-gray-600 mb-1">User</label>
<select
value={adminTarget}
onChange={e => setAdminTarget(e.target.value)}
className="w-full text-sm border rounded px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-white"
>
{adminUsers.map(u => {
const name = typeof u === 'string' ? u : u.username;
return <option key={name} value={name}>{name}</option>;
})}
</select>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">New password</label>
<input
type="password"
value={adminNewPw}
onChange={e => { setAdminNewPw(e.target.value); setAdminError(''); }}
autoComplete="new-password"
required
className={`w-full text-sm border rounded px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-white ${adminError ? 'border-red-400' : ''}`}
/>
{adminError && <p className="text-xs text-red-500 mt-1">{adminError}</p>}
<p className="text-xs text-gray-400 mt-1">Minimum 10 characters</p>
</div>
{adminStatus === 'success' && (
<div className="flex items-center gap-2 text-sm text-green-600">
<CheckCircle className="h-4 w-4 flex-shrink-0" />
Password reset successfully.
</div>
)}
<button
type="submit"
disabled={adminLoading || !adminTarget || !adminNewPw}
className="btn btn-primary disabled:opacity-50"
>
{adminLoading ? 'Resetting' : 'Reset Password'}
</button>
</form>
</div>
)}
</div>
);
}
+70
View File
@@ -0,0 +1,70 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
export default function Login() {
const { login } = useAuth();
const navigate = useNavigate();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async e => {
e.preventDefault();
setError('');
setLoading(true);
try {
await login(username, password);
navigate('/', { replace: true });
} catch (err) {
if (err.response?.status === 423) {
setError('Account locked. Too many failed attempts. Try again later.');
} else {
setError('Invalid username or password.');
}
} finally {
setLoading(false);
}
};
return (
<div className="flex items-center justify-center min-h-screen bg-gray-950">
<div className="w-full max-w-sm bg-gray-900 border border-gray-700 rounded-lg p-8 shadow-lg">
<h1 className="text-xl font-semibold text-white mb-6">Personal Internet Cell</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm text-gray-400 mb-1">Username</label>
<input
type="text"
autoComplete="username"
value={username}
onChange={e => setUsername(e.target.value)}
className="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
required
/>
</div>
<div>
<label className="block text-sm text-gray-400 mb-1">Password</label>
<input
type="password"
autoComplete="current-password"
value={password}
onChange={e => setPassword(e.target.value)}
className="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
required
/>
</div>
{error && <p className="text-red-400 text-sm">{error}</p>}
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-sm font-medium py-2 rounded transition-colors"
>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
</div>
);
}
+165
View File
@@ -0,0 +1,165 @@
import React, { useState, useEffect } from 'react';
import { Copy, Download, Wifi, Mail, Calendar, FolderOpen } from 'lucide-react';
import { peerAPI } from '../services/api';
function CopyButton({ text }) {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {}
};
return (
<button
onClick={handleCopy}
className="inline-flex items-center gap-1 text-xs text-primary-600 hover:text-primary-800 transition-colors"
title="Copy to clipboard"
>
<Copy className="h-3.5 w-3.5" />
{copied ? 'Copied' : 'Copy'}
</button>
);
}
function InfoRow({ label, value }) {
return (
<div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 py-2 border-b border-gray-100 last:border-0">
<span className="text-sm text-gray-500 sm:w-40 shrink-0">{label}</span>
<div className="flex items-center gap-2 min-w-0">
<span className="text-sm font-mono text-gray-900 break-all">{value}</span>
{value && <CopyButton text={value} />}
</div>
</div>
);
}
export default function MyServices() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
peerAPI.services()
.then(r => setData(r.data))
.catch(() => setError('Could not load services. Please try again.'))
.finally(() => setIsLoading(false));
}, []);
const downloadConfig = (filename, content) => {
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
</div>
);
}
if (error) {
return (
<div className="card text-center py-10">
<p className="text-sm text-danger-600">{error}</p>
</div>
);
}
const wg = data?.wireguard || {};
const email = data?.email || {};
const caldav = data?.caldav || {};
const files = data?.files || {};
return (
<div>
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">My Services</h1>
<p className="mt-1 text-gray-500 text-sm">Credentials and configuration for your personal services</p>
</div>
<div className="card mb-4">
<div className="flex items-center gap-2 mb-4">
<Wifi className="h-5 w-5 text-primary-500" />
<h2 className="text-base font-semibold text-gray-900">WireGuard VPN</h2>
</div>
<InfoRow label="VPN IP" value={wg.ip || wg.allowed_ips || '—'} />
{wg.config && (
<div className="mt-3 flex flex-wrap gap-2">
<button
onClick={() => downloadConfig(`${data?.username || 'peer'}.conf`, wg.config)}
className="inline-flex items-center gap-1.5 btn btn-secondary btn-sm text-sm"
>
<Download className="h-4 w-4" /> Download Config
</button>
<CopyButton text={wg.config} />
</div>
)}
{wg.qr_code && (
<div className="mt-4">
<p className="text-sm text-gray-600 mb-2">Scan with the WireGuard mobile app:</p>
<div className="inline-block p-3 bg-white border-2 border-gray-200 rounded-lg">
<img src={wg.qr_code} alt="WireGuard QR code" className="w-48 h-48" />
</div>
</div>
)}
</div>
<div className="card mb-4">
<div className="flex items-center gap-2 mb-4">
<Mail className="h-5 w-5 text-primary-500" />
<h2 className="text-base font-semibold text-gray-900">Email</h2>
</div>
<InfoRow label="Address" value={email.address || '—'} />
<InfoRow label="SMTP" value={email.smtp ? `${email.smtp.host}:${email.smtp.port}` : '—'} />
<InfoRow label="IMAP" value={email.imap ? `${email.imap.host}:${email.imap.port}` : '—'} />
{(email.smtp || email.imap) && (
<p className="text-xs text-gray-400 mt-3">
When setting up your mail client, use your dashboard username and password for authentication.
</p>
)}
</div>
<div className="card mb-4">
<div className="flex items-center gap-2 mb-4">
<Calendar className="h-5 w-5 text-primary-500" />
<h2 className="text-base font-semibold text-gray-900">Calendar & Contacts</h2>
</div>
<InfoRow label="CalDAV URL" value={caldav.url || '—'} />
<InfoRow label="Username" value={caldav.username || '—'} />
{caldav.url && (
<p className="text-xs text-gray-400 mt-3">
Use this URL in your calendar client. Authenticate with your username and dashboard password.
</p>
)}
</div>
<div className="card mb-4">
<div className="flex items-center gap-2 mb-4">
<FolderOpen className="h-5 w-5 text-primary-500" />
<h2 className="text-base font-semibold text-gray-900">Files</h2>
</div>
<InfoRow label="WebDAV URL" value={files.url || '—'} />
<InfoRow label="Username" value={files.username || '—'} />
{files.url && (
<p className="text-xs text-gray-400 mt-3">
Mount this URL as a network drive or use a WebDAV client. Authenticate with your username and dashboard password.
</p>
)}
</div>
<p className="text-xs text-gray-400 mt-4">
Note: Changing your dashboard password does not update email, calendar, or files passwords.
</p>
</div>
);
}
+129
View File
@@ -0,0 +1,129 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Wifi, ArrowDown, ArrowUp, Clock } from 'lucide-react';
import { peerAPI } from '../services/api';
function formatBytes(bytes) {
if (!bytes || bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
function timeAgo(isoString) {
if (!isoString) return 'Never';
const seconds = Math.floor((Date.now() - new Date(isoString).getTime()) / 1000);
if (seconds < 60) return `${seconds} seconds ago`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
const days = Math.floor(hours / 24);
return `${days} day${days !== 1 ? 's' : ''} ago`;
}
export default function PeerDashboard() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
peerAPI.dashboard()
.then(r => setData(r.data))
.catch(() => setError('Could not load dashboard data. Please try again.'))
.finally(() => setIsLoading(false));
}, []);
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
</div>
);
}
if (error) {
return (
<div className="card text-center py-10">
<p className="text-sm text-danger-600">{error}</p>
</div>
);
}
const peer = data || {};
return (
<div>
<div className="mb-6 flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">{peer.name || 'My Dashboard'}</h1>
<p className="mt-1 text-gray-500 text-sm">Your VPN connection and status</p>
</div>
<span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium ${
peer.online ? 'bg-success-100 text-success-700' : 'bg-gray-100 text-gray-500'
}`}>
<span className={`h-2 w-2 rounded-full ${peer.online ? 'bg-success-500' : 'bg-gray-400'}`} />
{peer.online ? 'Online' : 'Offline'}
</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<div className="card">
<div className="flex items-center">
<Wifi className="h-8 w-8 text-primary-500" />
<div className="ml-4 min-w-0">
<p className="text-sm font-medium text-gray-500">VPN Address</p>
<p className="text-lg font-semibold text-gray-900 font-mono truncate">
{peer.allowed_ips || peer.ip || '—'}
</p>
</div>
</div>
</div>
<div className="card">
<div className="flex items-center">
<ArrowDown className="h-8 w-8 text-primary-500" />
<div className="ml-4">
<p className="text-sm font-medium text-gray-500">Received</p>
<p className="text-lg font-semibold text-gray-900">{formatBytes(peer.transfer_rx)}</p>
</div>
</div>
</div>
<div className="card">
<div className="flex items-center">
<ArrowUp className="h-8 w-8 text-primary-500" />
<div className="ml-4">
<p className="text-sm font-medium text-gray-500">Sent</p>
<p className="text-lg font-semibold text-gray-900">{formatBytes(peer.transfer_tx)}</p>
</div>
</div>
</div>
<div className="card">
<div className="flex items-center">
<Clock className="h-8 w-8 text-primary-500" />
<div className="ml-4">
<p className="text-sm font-medium text-gray-500">Last Handshake</p>
<p className="text-sm font-semibold text-gray-900">{timeAgo(peer.last_handshake)}</p>
</div>
</div>
</div>
</div>
<div className="card">
<h2 className="text-base font-semibold text-gray-900 mb-3">Quick Access</h2>
<Link
to="/my-services"
className="inline-flex items-center gap-2 btn btn-primary"
>
My Services
</Link>
<p className="text-xs text-gray-500 mt-2">
View your VPN config, email, calendar, and file storage credentials.
</p>
</div>
</div>
);
}
+75 -7
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { Plus, Trash2, Edit, Eye, Shield, Copy, Download, Key, AlertTriangle, CheckCircle, Globe, Lock, Users, Server } from 'lucide-react';
import { peerAPI, wireguardAPI } from '../services/api';
import { peerRegistryAPI, wireguardAPI } from '../services/api';
import { useConfig } from '../contexts/ConfigContext';
import QRCode from 'qrcode';
@@ -15,8 +15,16 @@ const emptyForm = () => ({
service_access: ['calendar', 'files', 'mail', 'webdav'],
peer_access: true,
create_calendar: false,
password: '',
});
const generatePassword = () => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
const arr = new Uint8Array(14);
crypto.getRandomValues(arr);
return Array.from(arr).map(b => chars[b % chars.length]).join('');
};
function AccessBadge({ icon: Icon, label, active }) {
return (
<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium mr-1 ${
@@ -59,6 +67,7 @@ function Peers() {
const [showAddModal, setShowAddModal] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const [showViewModal, setShowViewModal] = useState(false);
const [showPasswordModal, setShowPasswordModal] = useState(null);
const [selectedPeer, setSelectedPeer] = useState(null);
const [formData, setFormData] = useState(emptyForm());
const [showAdvanced, setShowAdvanced] = useState(false);
@@ -79,7 +88,7 @@ function Peers() {
const fetchPeers = async () => {
try {
const [regResp, statusResp, scResp] = await Promise.all([
peerAPI.getPeers(),
peerRegistryAPI.getPeers(),
wireguardAPI.getPeerStatuses().catch(() => ({ data: {} })),
fetch('/api/wireguard/server-config').then(r => r.ok ? r.json() : null).catch(() => null),
]);
@@ -156,6 +165,7 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
const handleAddPeer = async (e) => {
e.preventDefault();
const errs = validate(formData);
if (!formData.password || formData.password.length < 10) errs.password = 'Password must be at least 10 characters';
if (Object.keys(errs).length) { setErrors(errs); return; }
setIsSubmitting(true);
try {
@@ -179,11 +189,10 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
internet_access: formData.internet_access,
service_access: formData.service_access,
peer_access: formData.peer_access,
password: formData.password,
};
const addResult = await peerAPI.addPeer(peerData);
const addResult = await peerRegistryAPI.addPeer(peerData);
const assignedIp = addResult.data?.ip;
// Server-side AllowedIPs = peer's VPN IP only (/32).
// Full/split tunnel is a CLIENT-side setting (AllowedIPs in the client config).
await wireguardAPI.addPeer({
name: formData.name,
public_key: publicKey,
@@ -197,11 +206,14 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
} catch {}
}
const provisioned = addResult.data?.provisioned;
const createdName = formData.name;
const createdPassword = formData.password;
setShowAddModal(false);
setFormData(emptyForm());
setErrors({});
fetchPeers();
showToast(`Peer "${formData.name}" created. Open it to download the tunnel config.`);
setShowPasswordModal({ name: createdName, password: createdPassword, provisioned });
} catch (err) {
showToast(err?.response?.data?.error || 'Failed to add peer', 'error');
} finally { setIsSubmitting(false); }
@@ -251,7 +263,7 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
const handleRemovePeer = async (peerName) => {
if (!window.confirm(`Remove peer "${peerName}"?`)) return;
try {
await Promise.all([peerAPI.removePeer(peerName), wireguardAPI.removePeer({ name: peerName })]);
await Promise.all([peerRegistryAPI.removePeer(peerName), wireguardAPI.removePeer({ name: peerName })]);
fetchPeers();
showToast(`Peer "${peerName}" removed.`);
} catch { showToast('Failed to remove peer', 'error'); }
@@ -525,6 +537,25 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
{/* Account Creation */}
<div className="pt-3 border-t border-gray-200">
<div className="text-sm font-semibold text-gray-700 mb-2">Account Setup</div>
<div className="mb-3">
<label className="block text-sm font-medium text-gray-700 mb-1">Dashboard Password *</label>
<div className="flex gap-2">
<input
type="password"
value={formData.password}
onChange={e => { setFormData(f => ({ ...f, password: e.target.value })); setErrors(e2 => ({ ...e2, password: undefined })); }}
className={`input flex-1 ${errors.password ? 'border-red-500' : ''}`}
placeholder="Min 10 characters"
autoComplete="new-password"
/>
<button type="button"
onClick={() => setFormData(f => ({ ...f, password: generatePassword() }))}
className="btn btn-secondary text-xs whitespace-nowrap">
Generate
</button>
</div>
{errors.password && <p className="text-xs text-red-600 mt-1">{errors.password}</p>}
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={formData.create_calendar}
onChange={e => setFormData(f => ({ ...f, create_calendar: e.target.checked }))} className="rounded" />
@@ -727,6 +758,43 @@ PersistentKeepalive = ${peer.persistent_keepalive || 25}`;
</div>
</div>
)}
{/* One-time password modal */}
{showPasswordModal && (
<div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center">
<div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-md mx-4">
<div className="flex items-center gap-2 mb-4">
<CheckCircle className="h-6 w-6 text-green-500 flex-shrink-0" />
<h3 className="text-lg font-medium text-gray-900">Peer Created Save This Password</h3>
</div>
<p className="text-sm text-gray-600 mb-3">
This is the only time you will see this password. Copy it and share it with <strong>{showPasswordModal.name}</strong>.
</p>
<div className="bg-gray-50 border border-gray-200 rounded-md p-3 mb-3">
<div className="flex items-center justify-between gap-2">
<code className="text-sm font-mono text-gray-900 break-all">{showPasswordModal.password}</code>
<button
onClick={() => copyToClipboard(showPasswordModal.password)}
className="flex-shrink-0 p-1.5 text-gray-500 hover:text-gray-700 rounded"
title="Copy password"
>
<Copy className="h-4 w-4" />
</button>
</div>
</div>
{showPasswordModal.provisioned && (
<p className="text-xs text-gray-500 mb-4">
Accounts created: {Object.entries(showPasswordModal.provisioned).filter(([, v]) => v).map(([k]) => k).join(', ') || 'none'}
</p>
)}
<div className="flex justify-end">
<button onClick={() => setShowPasswordModal(null)} className="btn btn-primary">
Done
</button>
</div>
</div>
</div>
)}
</div>
);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { Shield, Key, Users, Activity, Wifi, Download, Copy, RefreshCw, Play, Pause, AlertCircle, Eye, Globe, CheckCircle, XCircle } from 'lucide-react';
import { wireguardAPI, peerAPI } from '../services/api';
import { wireguardAPI, peerRegistryAPI as peerAPI } from '../services/api';
import { useConfig } from '../contexts/ConfigContext';
import QRCode from 'qrcode';