Fix jwt-token
This commit is contained in:
@@ -11,6 +11,7 @@ import Devices from './pages/Devices';
|
||||
import Detections from './pages/Detections';
|
||||
import Alerts from './pages/Alerts';
|
||||
import Debug from './pages/Debug';
|
||||
import Settings from './pages/Settings';
|
||||
import Login from './pages/Login';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
|
||||
@@ -70,6 +71,7 @@ function App() {
|
||||
<Route path="devices" element={<Devices />} />
|
||||
<Route path="detections" element={<Detections />} />
|
||||
<Route path="alerts" element={<Alerts />} />
|
||||
<Route path="settings" element={<Settings />} />
|
||||
<Route path="debug" element={<Debug />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
XMarkIcon,
|
||||
SignalIcon,
|
||||
WifiIcon,
|
||||
BugAntIcon
|
||||
BugAntIcon,
|
||||
CogIcon
|
||||
} from '@heroicons/react/24/outline';
|
||||
import classNames from 'classnames';
|
||||
|
||||
@@ -27,6 +28,7 @@ const baseNavigation = [
|
||||
];
|
||||
|
||||
const adminNavigation = [
|
||||
{ name: 'Settings', href: '/settings', icon: CogIcon },
|
||||
{ name: 'Debug', href: '/debug', icon: BugAntIcon },
|
||||
];
|
||||
|
||||
|
||||
865
client/src/pages/Settings.jsx
Normal file
865
client/src/pages/Settings.jsx
Normal file
@@ -0,0 +1,865 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import api from '../services/api';
|
||||
import toast from 'react-hot-toast';
|
||||
import {
|
||||
CogIcon,
|
||||
ShieldCheckIcon,
|
||||
PaintBrushIcon,
|
||||
UserGroupIcon,
|
||||
GlobeAltIcon,
|
||||
KeyIcon,
|
||||
EyeIcon,
|
||||
EyeSlashIcon
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
const Settings = () => {
|
||||
const { user } = useAuth();
|
||||
const [activeTab, setActiveTab] = useState('general');
|
||||
const [tenantConfig, setTenantConfig] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Check if user has admin role
|
||||
const isAdmin = user?.role === 'admin';
|
||||
|
||||
useEffect(() => {
|
||||
fetchTenantConfig();
|
||||
}, []);
|
||||
|
||||
const fetchTenantConfig = async () => {
|
||||
try {
|
||||
// Get current tenant configuration
|
||||
const response = await api.get('/tenant/info');
|
||||
setTenantConfig(response.data.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch tenant config:', error);
|
||||
toast.error('Failed to load tenant settings');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<ShieldCheckIcon className="mx-auto h-12 w-12 text-gray-400" />
|
||||
<h3 className="mt-2 text-sm font-medium text-gray-900">Access Denied</h3>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
You need admin privileges to access tenant settings.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ id: 'general', name: 'General', icon: CogIcon },
|
||||
{ id: 'branding', name: 'Branding', icon: PaintBrushIcon },
|
||||
{ id: 'security', name: 'Security', icon: ShieldCheckIcon },
|
||||
{ id: 'authentication', name: 'Authentication', icon: KeyIcon },
|
||||
{ id: 'users', name: 'Users', icon: UserGroupIcon },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<div className="border-b border-gray-200">
|
||||
<div className="sm:flex sm:items-baseline">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">
|
||||
Tenant Settings
|
||||
</h3>
|
||||
<div className="mt-4 sm:mt-0 sm:ml-10">
|
||||
<nav className="-mb-px flex space-x-8">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon;
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`${
|
||||
activeTab === tab.id
|
||||
? 'border-primary-500 text-primary-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
} whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center`}
|
||||
>
|
||||
<Icon className="h-5 w-5 mr-2" />
|
||||
{tab.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
{activeTab === 'general' && <GeneralSettings tenantConfig={tenantConfig} />}
|
||||
{activeTab === 'branding' && <BrandingSettings tenantConfig={tenantConfig} onRefresh={fetchTenantConfig} />}
|
||||
{activeTab === 'security' && <SecuritySettings tenantConfig={tenantConfig} onRefresh={fetchTenantConfig} />}
|
||||
{activeTab === 'authentication' && <AuthenticationSettings tenantConfig={tenantConfig} />}
|
||||
{activeTab === 'users' && <UsersSettings tenantConfig={tenantConfig} onRefresh={fetchTenantConfig} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// General Settings Component
|
||||
const GeneralSettings = ({ tenantConfig }) => (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">General Information</h3>
|
||||
<div className="mt-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Tenant Name</label>
|
||||
<p className="mt-1 text-sm text-gray-900">{tenantConfig?.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Tenant ID</label>
|
||||
<p className="mt-1 text-sm text-gray-500 font-mono">{tenantConfig?.slug}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Authentication Provider</label>
|
||||
<p className="mt-1 text-sm text-gray-900 uppercase">{tenantConfig?.auth_provider}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Branding Settings Component
|
||||
const BrandingSettings = ({ tenantConfig, onRefresh }) => {
|
||||
const [branding, setBranding] = useState({
|
||||
logo_url: '',
|
||||
primary_color: '#3B82F6',
|
||||
secondary_color: '#1F2937',
|
||||
company_name: ''
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (tenantConfig?.branding) {
|
||||
setBranding(tenantConfig.branding);
|
||||
}
|
||||
}, [tenantConfig]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.put('/tenant/branding', branding);
|
||||
toast.success('Branding updated successfully');
|
||||
if (onRefresh) onRefresh();
|
||||
} catch (error) {
|
||||
toast.error('Failed to update branding');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">Branding & Appearance</h3>
|
||||
<div className="mt-5 space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Company Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={branding.company_name}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, company_name: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Logo URL</label>
|
||||
<input
|
||||
type="url"
|
||||
value={branding.logo_url}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, logo_url: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
placeholder="https://example.com/logo.png"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Primary Color</label>
|
||||
<div className="mt-1 flex">
|
||||
<input
|
||||
type="color"
|
||||
value={branding.primary_color}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, primary_color: e.target.value }))}
|
||||
className="h-10 w-20 border border-gray-300 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={branding.primary_color}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, primary_color: e.target.value }))}
|
||||
className="ml-2 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Secondary Color</label>
|
||||
<div className="mt-1 flex">
|
||||
<input
|
||||
type="color"
|
||||
value={branding.secondary_color}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, secondary_color: e.target.value }))}
|
||||
className="h-10 w-20 border border-gray-300 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={branding.secondary_color}
|
||||
onChange={(e) => setBranding(prev => ({ ...prev, secondary_color: e.target.value }))}
|
||||
className="ml-2 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="bg-primary-600 text-white px-4 py-2 rounded-md hover:bg-primary-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save Branding'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Placeholder components for other tabs
|
||||
const SecuritySettings = ({ tenantConfig, onRefresh }) => {
|
||||
const [securitySettings, setSecuritySettings] = useState({
|
||||
ip_restriction_enabled: false,
|
||||
ip_whitelist: [],
|
||||
ip_restriction_message: 'Access denied. Your IP address is not authorized to access this tenant.'
|
||||
});
|
||||
const [newIP, setNewIP] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (tenantConfig) {
|
||||
setSecuritySettings({
|
||||
ip_restriction_enabled: tenantConfig.ip_restriction_enabled || false,
|
||||
ip_whitelist: tenantConfig.ip_whitelist || [],
|
||||
ip_restriction_message: tenantConfig.ip_restriction_message || 'Access denied. Your IP address is not authorized to access this tenant.'
|
||||
});
|
||||
}
|
||||
}, [tenantConfig]);
|
||||
|
||||
const addIPToWhitelist = () => {
|
||||
if (!newIP.trim()) {
|
||||
toast.error('Please enter an IP address or CIDR block');
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic validation for IP format
|
||||
const ipPattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/(?:[0-9]|[1-2][0-9]|3[0-2]))?$|^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\*$/;
|
||||
|
||||
if (!ipPattern.test(newIP.trim())) {
|
||||
toast.error('Please enter a valid IP address, CIDR block (e.g., 192.168.1.0/24), or wildcard (e.g., 192.168.1.*)');
|
||||
return;
|
||||
}
|
||||
|
||||
const ip = newIP.trim();
|
||||
if (securitySettings.ip_whitelist.includes(ip)) {
|
||||
toast.error('This IP is already in the whitelist');
|
||||
return;
|
||||
}
|
||||
|
||||
setSecuritySettings(prev => ({
|
||||
...prev,
|
||||
ip_whitelist: [...prev.ip_whitelist, ip]
|
||||
}));
|
||||
setNewIP('');
|
||||
toast.success('IP added to whitelist');
|
||||
};
|
||||
|
||||
const removeIPFromWhitelist = (ipToRemove) => {
|
||||
setSecuritySettings(prev => ({
|
||||
...prev,
|
||||
ip_whitelist: prev.ip_whitelist.filter(ip => ip !== ipToRemove)
|
||||
}));
|
||||
toast.success('IP removed from whitelist');
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.put('/tenant/security', securitySettings);
|
||||
toast.success('Security settings updated successfully');
|
||||
if (onRefresh) onRefresh();
|
||||
} catch (error) {
|
||||
console.error('Failed to update security settings:', error);
|
||||
toast.error('Failed to update security settings');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">Security Settings</h3>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="bg-primary-600 text-white px-4 py-2 rounded-md hover:bg-primary-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* IP Restriction Toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="text-md font-medium text-gray-900">IP Access Control</h4>
|
||||
<p className="text-sm text-gray-500">
|
||||
Restrict access to this tenant to specific IP addresses
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ip_restriction_enabled"
|
||||
checked={securitySettings.ip_restriction_enabled}
|
||||
onChange={(e) => setSecuritySettings(prev => ({
|
||||
...prev,
|
||||
ip_restriction_enabled: e.target.checked
|
||||
}))}
|
||||
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
|
||||
/>
|
||||
<label htmlFor="ip_restriction_enabled" className="ml-2 text-sm font-medium text-gray-700">
|
||||
Enable IP Restrictions
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* IP Restriction Configuration */}
|
||||
{securitySettings.ip_restriction_enabled && (
|
||||
<div className="space-y-4 p-4 bg-gray-50 rounded-lg border">
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-md p-3">
|
||||
<div className="flex">
|
||||
<div className="ml-3">
|
||||
<h3 className="text-sm font-medium text-yellow-800">
|
||||
⚠️ Important Security Notes
|
||||
</h3>
|
||||
<div className="mt-1 text-sm text-yellow-700">
|
||||
<ul className="list-disc list-inside space-y-1">
|
||||
<li>Make sure to include your current IP to avoid being locked out</li>
|
||||
<li>IP restrictions apply to all tenant access including login and API calls</li>
|
||||
<li>Use CIDR notation for IP ranges (e.g., 192.168.1.0/24)</li>
|
||||
<li>Use wildcards for partial matching (e.g., 192.168.1.*)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add IP Input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Add IP Address or Range
|
||||
</label>
|
||||
<div className="flex space-x-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Enter IP address (e.g., 192.168.1.100, 10.0.0.0/24, or 192.168.1.*)"
|
||||
value={newIP}
|
||||
onChange={(e) => setNewIP(e.target.value)}
|
||||
onKeyPress={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addIPToWhitelist();
|
||||
}
|
||||
}}
|
||||
className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addIPToWhitelist}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
|
||||
>
|
||||
Add IP
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* IP Whitelist */}
|
||||
{securitySettings.ip_whitelist.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Allowed IP Addresses ({securitySettings.ip_whitelist.length})
|
||||
</label>
|
||||
<div className="space-y-2 max-h-40 overflow-y-auto">
|
||||
{securitySettings.ip_whitelist.map((ip, index) => (
|
||||
<div key={index} className="flex items-center justify-between bg-white px-3 py-2 rounded border">
|
||||
<span className="text-sm font-mono">{ip}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeIPFromWhitelist(ip)}
|
||||
className="text-red-600 hover:text-red-800 text-sm"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Custom restriction message */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Access Denied Message
|
||||
</label>
|
||||
<textarea
|
||||
value={securitySettings.ip_restriction_message}
|
||||
onChange={(e) => setSecuritySettings(prev => ({
|
||||
...prev,
|
||||
ip_restriction_message: e.target.value
|
||||
}))}
|
||||
rows={3}
|
||||
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||
placeholder="Message shown when access is denied due to IP restrictions"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
This message will be shown to users whose IP is not in the whitelist.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AuthenticationSettings = () => (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">Authentication Settings</h3>
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Authentication provider configuration will be available here.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const UsersSettings = ({ tenantConfig, onRefresh }) => {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showCreateUser, setShowCreateUser] = useState(false);
|
||||
|
||||
const authProvider = tenantConfig?.auth_provider;
|
||||
const canManageUsers = authProvider === 'local'; // Only local auth allows user management
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, []);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const response = await api.get('/tenant/users');
|
||||
setUsers(response.data.data || []);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch users:', error);
|
||||
toast.error('Failed to load users');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<div className="animate-pulse">
|
||||
<div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
|
||||
<div className="space-y-3">
|
||||
<div className="h-4 bg-gray-200 rounded"></div>
|
||||
<div className="h-4 bg-gray-200 rounded w-5/6"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg">
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div>
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900">User Management</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{authProvider === 'local'
|
||||
? 'Manage local users for this tenant'
|
||||
: `Users are managed through ${authProvider.toUpperCase()}. Showing read-only information.`
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
{canManageUsers && (
|
||||
<button
|
||||
onClick={() => setShowCreateUser(true)}
|
||||
className="bg-primary-600 text-white px-4 py-2 rounded-md hover:bg-primary-700"
|
||||
>
|
||||
Add User
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Authentication Provider Info */}
|
||||
<div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-md">
|
||||
<div className="flex items-center">
|
||||
<KeyIcon className="h-5 w-5 text-blue-400 mr-2" />
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-blue-800">
|
||||
Authentication Provider: {authProvider?.toUpperCase()}
|
||||
</h4>
|
||||
<p className="text-sm text-blue-700">
|
||||
{authProvider === 'local' && 'Local authentication - Users are managed directly in this system.'}
|
||||
{authProvider === 'saml' && 'SAML SSO - Users authenticate through your SAML identity provider.'}
|
||||
{authProvider === 'oauth' && 'OAuth - Users authenticate through your OAuth provider.'}
|
||||
{authProvider === 'ldap' && 'LDAP/Active Directory - Users authenticate through your directory service.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Users List */}
|
||||
{users.length === 0 ? (
|
||||
<div className="text-center py-8">
|
||||
<UserGroupIcon className="mx-auto h-12 w-12 text-gray-400" />
|
||||
<h3 className="mt-2 text-sm font-medium text-gray-900">No users found</h3>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
{canManageUsers
|
||||
? 'Get started by creating a new user.'
|
||||
: 'Users will appear here when they log in through your authentication provider.'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
User
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Role
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Last Login
|
||||
</th>
|
||||
{canManageUsers && (
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Actions
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900">{user.username}</div>
|
||||
<div className="text-sm text-gray-500">{user.email}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
|
||||
user.role === 'admin'
|
||||
? 'bg-purple-100 text-purple-800'
|
||||
: user.role === 'operator'
|
||||
? 'bg-blue-100 text-blue-800'
|
||||
: 'bg-gray-100 text-gray-800'
|
||||
}`}>
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
|
||||
user.is_active
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}>
|
||||
{user.is_active ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{user.last_login
|
||||
? new Date(user.last_login).toLocaleDateString()
|
||||
: 'Never'
|
||||
}
|
||||
</td>
|
||||
{canManageUsers && (
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
|
||||
<button
|
||||
onClick={() => handleEditUser(user)}
|
||||
className="text-primary-600 hover:text-primary-900 mr-4"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleToggleUserStatus(user)}
|
||||
className={user.is_active
|
||||
? 'text-red-600 hover:text-red-900'
|
||||
: 'text-green-600 hover:text-green-900'
|
||||
}
|
||||
>
|
||||
{user.is_active ? 'Deactivate' : 'Activate'}
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Non-Local Auth Guidance */}
|
||||
{!canManageUsers && (
|
||||
<div className="mt-6 p-4 bg-gray-50 border border-gray-200 rounded-md">
|
||||
<h4 className="text-sm font-medium text-gray-900 mb-2">
|
||||
User Management for {authProvider?.toUpperCase()}
|
||||
</h4>
|
||||
<div className="text-sm text-gray-700 space-y-2">
|
||||
{authProvider === 'saml' && (
|
||||
<div>
|
||||
<p>• Users are managed in your SAML identity provider</p>
|
||||
<p>• Role assignments can be configured in the Authentication tab</p>
|
||||
<p>• User information is synced automatically during login</p>
|
||||
</div>
|
||||
)}
|
||||
{authProvider === 'oauth' && (
|
||||
<div>
|
||||
<p>• Users authenticate through your OAuth provider</p>
|
||||
<p>• Role mappings can be configured based on OAuth claims</p>
|
||||
<p>• User information is retrieved from the OAuth provider</p>
|
||||
</div>
|
||||
)}
|
||||
{authProvider === 'ldap' && (
|
||||
<div>
|
||||
<p>• Users are managed in your LDAP/Active Directory</p>
|
||||
<p>• Group-to-role mappings can be configured in Authentication settings</p>
|
||||
<p>• User information is synced from the directory during login</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Create User Modal for Local Auth */}
|
||||
{showCreateUser && canManageUsers && (
|
||||
<CreateUserModal
|
||||
isOpen={showCreateUser}
|
||||
onClose={() => setShowCreateUser(false)}
|
||||
onUserCreated={() => {
|
||||
fetchUsers();
|
||||
setShowCreateUser(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
// Helper functions for local user management
|
||||
const handleEditUser = (user) => {
|
||||
// TODO: Implement edit user modal
|
||||
toast.info('Edit user functionality coming soon');
|
||||
};
|
||||
|
||||
const handleToggleUserStatus = async (user) => {
|
||||
try {
|
||||
await api.put(`/tenant/users/${user.id}/status`, {
|
||||
is_active: !user.is_active
|
||||
});
|
||||
toast.success(`User ${user.is_active ? 'deactivated' : 'activated'} successfully`);
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
toast.error('Failed to update user status');
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Create User Modal Component (for local auth only)
|
||||
const CreateUserModal = ({ isOpen, onClose, onUserCreated }) => {
|
||||
const [formData, setFormData] = useState({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
role: 'viewer',
|
||||
is_active: true
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
await api.post('/tenant/users', formData);
|
||||
toast.success('User created successfully');
|
||||
onUserCreated();
|
||||
setFormData({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
role: 'viewer',
|
||||
is_active: true
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error('Failed to create user');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 overflow-y-auto">
|
||||
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
|
||||
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={onClose}></div>
|
||||
|
||||
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
|
||||
<div className="sm:flex sm:items-start">
|
||||
<div className="w-full">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900 mb-4">
|
||||
Create New User
|
||||
</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={formData.username}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, username: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
required
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Password</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
required
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, password: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeSlashIcon className="h-5 w-5 text-gray-400" />
|
||||
) : (
|
||||
<EyeIcon className="h-5 w-5 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Role</label>
|
||||
<select
|
||||
value={formData.role}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, role: e.target.value }))}
|
||||
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500"
|
||||
>
|
||||
<option value="viewer">Viewer</option>
|
||||
<option value="operator">Operator</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="is_active"
|
||||
checked={formData.is_active}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, is_active: e.target.checked }))}
|
||||
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
|
||||
/>
|
||||
<label htmlFor="is_active" className="ml-2 text-sm font-medium text-gray-700">
|
||||
Active User
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Creating...' : 'Create User'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Settings;
|
||||
231
server/middleware/rbac.js
Normal file
231
server/middleware/rbac.js
Normal file
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Role-Based Access Control (RBAC) System
|
||||
* Defines granular permissions for different roles
|
||||
*/
|
||||
|
||||
// Define specific permissions
|
||||
const PERMISSIONS = {
|
||||
// General tenant management
|
||||
'tenant.view': 'View tenant information',
|
||||
'tenant.edit': 'Edit basic tenant settings',
|
||||
|
||||
// Branding permissions
|
||||
'branding.view': 'View branding settings',
|
||||
'branding.edit': 'Edit branding and appearance',
|
||||
|
||||
// Security permissions
|
||||
'security.view': 'View security settings',
|
||||
'security.edit': 'Edit security settings and IP restrictions',
|
||||
|
||||
// User management permissions
|
||||
'users.view': 'View user list',
|
||||
'users.create': 'Create new users',
|
||||
'users.edit': 'Edit user details',
|
||||
'users.delete': 'Delete or deactivate users',
|
||||
'users.manage_roles': 'Change user roles',
|
||||
|
||||
// Authentication permissions
|
||||
'auth.view': 'View authentication settings',
|
||||
'auth.edit': 'Edit authentication provider settings',
|
||||
|
||||
// Operational permissions
|
||||
'dashboard.view': 'View dashboard',
|
||||
'devices.view': 'View devices',
|
||||
'devices.manage': 'Add, edit, delete devices',
|
||||
'detections.view': 'View detections',
|
||||
'alerts.view': 'View alerts',
|
||||
'alerts.manage': 'Manage alert configurations',
|
||||
'debug.access': 'Access debug information'
|
||||
};
|
||||
|
||||
// Role definitions with their permissions
|
||||
const ROLES = {
|
||||
// Full tenant administrator
|
||||
'admin': [
|
||||
'tenant.view', 'tenant.edit',
|
||||
'branding.view', 'branding.edit',
|
||||
'security.view', 'security.edit',
|
||||
'users.view', 'users.create', 'users.edit', 'users.delete', 'users.manage_roles',
|
||||
'auth.view', 'auth.edit',
|
||||
'dashboard.view',
|
||||
'devices.view', 'devices.manage',
|
||||
'detections.view',
|
||||
'alerts.view', 'alerts.manage',
|
||||
'debug.access'
|
||||
],
|
||||
|
||||
// User management specialist
|
||||
'user_admin': [
|
||||
'tenant.view',
|
||||
'users.view', 'users.create', 'users.edit', 'users.delete', 'users.manage_roles',
|
||||
'dashboard.view',
|
||||
'devices.view',
|
||||
'detections.view',
|
||||
'alerts.view'
|
||||
],
|
||||
|
||||
// Security specialist
|
||||
'security_admin': [
|
||||
'tenant.view',
|
||||
'security.view', 'security.edit',
|
||||
'auth.view', 'auth.edit',
|
||||
'users.view',
|
||||
'dashboard.view',
|
||||
'devices.view',
|
||||
'detections.view',
|
||||
'alerts.view'
|
||||
],
|
||||
|
||||
// Branding/marketing specialist
|
||||
'branding_admin': [
|
||||
'tenant.view',
|
||||
'branding.view', 'branding.edit',
|
||||
'dashboard.view',
|
||||
'devices.view',
|
||||
'detections.view',
|
||||
'alerts.view'
|
||||
],
|
||||
|
||||
// Operations manager
|
||||
'operator': [
|
||||
'tenant.view',
|
||||
'dashboard.view',
|
||||
'devices.view', 'devices.manage',
|
||||
'detections.view',
|
||||
'alerts.view', 'alerts.manage'
|
||||
],
|
||||
|
||||
// Read-only user
|
||||
'viewer': [
|
||||
'dashboard.view',
|
||||
'devices.view',
|
||||
'detections.view',
|
||||
'alerts.view'
|
||||
]
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a user has a specific permission
|
||||
* @param {string} userRole - The user's role
|
||||
* @param {string} permission - The permission to check
|
||||
* @returns {boolean} - True if user has permission
|
||||
*/
|
||||
const hasPermission = (userRole, permission) => {
|
||||
if (!userRole || !ROLES[userRole]) {
|
||||
return false;
|
||||
}
|
||||
return ROLES[userRole].includes(permission);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a user has any of the specified permissions
|
||||
* @param {string} userRole - The user's role
|
||||
* @param {Array<string>} permissions - Array of permissions to check
|
||||
* @returns {boolean} - True if user has at least one permission
|
||||
*/
|
||||
const hasAnyPermission = (userRole, permissions) => {
|
||||
return permissions.some(permission => hasPermission(userRole, permission));
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a user has all of the specified permissions
|
||||
* @param {string} userRole - The user's role
|
||||
* @param {Array<string>} permissions - Array of permissions to check
|
||||
* @returns {boolean} - True if user has all permissions
|
||||
*/
|
||||
const hasAllPermissions = (userRole, permissions) => {
|
||||
return permissions.every(permission => hasPermission(userRole, permission));
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all permissions for a role
|
||||
* @param {string} userRole - The user's role
|
||||
* @returns {Array<string>} - Array of permissions
|
||||
*/
|
||||
const getPermissions = (userRole) => {
|
||||
return ROLES[userRole] || [];
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all available roles
|
||||
* @returns {Array<string>} - Array of role names
|
||||
*/
|
||||
const getRoles = () => {
|
||||
return Object.keys(ROLES);
|
||||
};
|
||||
|
||||
/**
|
||||
* Express middleware to check permissions
|
||||
* @param {Array<string>} requiredPermissions - Required permissions
|
||||
* @returns {Function} - Express middleware function
|
||||
*/
|
||||
const requirePermissions = (requiredPermissions) => {
|
||||
return (req, res, next) => {
|
||||
if (!req.user || !req.user.role) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Authentication required'
|
||||
});
|
||||
}
|
||||
|
||||
const userRole = req.user.role;
|
||||
const hasRequiredPermissions = requiredPermissions.every(permission =>
|
||||
hasPermission(userRole, permission)
|
||||
);
|
||||
|
||||
if (!hasRequiredPermissions) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'Insufficient permissions',
|
||||
required_permissions: requiredPermissions,
|
||||
user_role: userRole
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Express middleware to check if user has any of the specified permissions
|
||||
* @param {Array<string>} permissions - Array of permissions
|
||||
* @returns {Function} - Express middleware function
|
||||
*/
|
||||
const requireAnyPermission = (permissions) => {
|
||||
return (req, res, next) => {
|
||||
if (!req.user || !req.user.role) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Authentication required'
|
||||
});
|
||||
}
|
||||
|
||||
const userRole = req.user.role;
|
||||
const hasRequiredPermission = permissions.some(permission =>
|
||||
hasPermission(userRole, permission)
|
||||
);
|
||||
|
||||
if (!hasRequiredPermission) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'Insufficient permissions',
|
||||
required_permissions: permissions,
|
||||
user_role: userRole
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
PERMISSIONS,
|
||||
ROLES,
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasAllPermissions,
|
||||
getPermissions,
|
||||
getRoles,
|
||||
requirePermissions,
|
||||
requireAnyPermission
|
||||
};
|
||||
@@ -4,6 +4,7 @@ const router = express.Router();
|
||||
// Import route modules
|
||||
const managementRoutes = require('./management');
|
||||
const authRoutes = require('./auth');
|
||||
const tenantRoutes = require('./tenant');
|
||||
const deviceRoutes = require('./device');
|
||||
const userRoutes = require('./user');
|
||||
const alertRoutes = require('./alert');
|
||||
@@ -21,6 +22,9 @@ router.use('/management', managementRoutes);
|
||||
// Authentication routes (multi-tenant)
|
||||
router.use('/auth', authRoutes);
|
||||
|
||||
// Tenant self-management routes
|
||||
router.use('/tenant', tenantRoutes);
|
||||
|
||||
// API versioning
|
||||
router.use('/v1/devices', deviceRoutes);
|
||||
router.use('/v1/users', userRoutes);
|
||||
|
||||
453
server/routes/tenant.js
Normal file
453
server/routes/tenant.js
Normal file
@@ -0,0 +1,453 @@
|
||||
/**
|
||||
* Tenant Self-Management Routes
|
||||
* Allows tenant admins to manage their own tenant settings
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { Tenant, User } = require('../models');
|
||||
const { authenticateToken } = require('../middleware/auth');
|
||||
const { requirePermissions, requireAnyPermission, hasPermission } = require('../middleware/rbac');
|
||||
const MultiTenantAuth = require('../middleware/multi-tenant-auth');
|
||||
|
||||
// Initialize multi-tenant auth
|
||||
const multiAuth = new MultiTenantAuth();
|
||||
|
||||
/**
|
||||
* GET /tenant/info
|
||||
* Get current tenant information
|
||||
*/
|
||||
router.get('/info', authenticateToken, requirePermissions(['tenant.view']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Return tenant info (excluding sensitive data)
|
||||
const tenantInfo = {
|
||||
id: tenant.id,
|
||||
name: tenant.name,
|
||||
slug: tenant.slug,
|
||||
domain: tenant.domain,
|
||||
subscription_type: tenant.subscription_type,
|
||||
is_active: tenant.is_active,
|
||||
auth_provider: tenant.auth_provider,
|
||||
branding: tenant.branding,
|
||||
features: tenant.features,
|
||||
admin_email: tenant.admin_email,
|
||||
admin_phone: tenant.admin_phone,
|
||||
billing_email: tenant.billing_email,
|
||||
created_at: tenant.created_at,
|
||||
// IP restriction info (for security admins only)
|
||||
ip_restriction_enabled: hasPermission(req.user.role, 'security.view') ? tenant.ip_restriction_enabled : undefined,
|
||||
ip_whitelist: hasPermission(req.user.role, 'security.view') ? tenant.ip_whitelist : undefined,
|
||||
ip_restriction_message: hasPermission(req.user.role, 'security.view') ? tenant.ip_restriction_message : undefined
|
||||
};
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: tenantInfo
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching tenant info:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to fetch tenant information'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /tenant/branding
|
||||
* Update tenant branding (branding admin or higher)
|
||||
*/
|
||||
router.put('/branding', authenticateToken, requirePermissions(['branding.edit']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
const { logo_url, primary_color, secondary_color, company_name } = req.body;
|
||||
|
||||
// Validate colors
|
||||
const colorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
|
||||
if (primary_color && !colorRegex.test(primary_color)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid primary color format'
|
||||
});
|
||||
}
|
||||
if (secondary_color && !colorRegex.test(secondary_color)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid secondary color format'
|
||||
});
|
||||
}
|
||||
|
||||
// Update branding
|
||||
const updatedBranding = {
|
||||
...tenant.branding,
|
||||
logo_url: logo_url || tenant.branding?.logo_url || '',
|
||||
primary_color: primary_color || tenant.branding?.primary_color || '#3B82F6',
|
||||
secondary_color: secondary_color || tenant.branding?.secondary_color || '#1F2937',
|
||||
company_name: company_name || tenant.branding?.company_name || ''
|
||||
};
|
||||
|
||||
await tenant.update({ branding: updatedBranding });
|
||||
|
||||
console.log(`✅ Tenant "${tenantId}" branding updated by user "${req.user.username}"`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Branding updated successfully',
|
||||
data: { branding: updatedBranding }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error updating tenant branding:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to update branding'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /tenant/security
|
||||
* Update tenant security settings (security admin or higher)
|
||||
*/
|
||||
router.put('/security', authenticateToken, requirePermissions(['security.edit']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
const { ip_restriction_enabled, ip_whitelist, ip_restriction_message } = req.body;
|
||||
|
||||
// Validate IP whitelist if provided
|
||||
if (ip_whitelist && Array.isArray(ip_whitelist)) {
|
||||
for (const ip of ip_whitelist) {
|
||||
// Basic IP validation (could be enhanced)
|
||||
if (typeof ip !== 'string' || ip.trim().length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid IP address in whitelist'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update security settings
|
||||
const updates = {};
|
||||
if (typeof ip_restriction_enabled === 'boolean') {
|
||||
updates.ip_restriction_enabled = ip_restriction_enabled;
|
||||
}
|
||||
if (ip_whitelist) {
|
||||
updates.ip_whitelist = ip_whitelist;
|
||||
}
|
||||
if (ip_restriction_message) {
|
||||
updates.ip_restriction_message = ip_restriction_message;
|
||||
}
|
||||
|
||||
await tenant.update(updates);
|
||||
|
||||
console.log(`✅ Tenant "${tenantId}" security settings updated by user "${req.user.username}"`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Security settings updated successfully',
|
||||
data: {
|
||||
ip_restriction_enabled: tenant.ip_restriction_enabled,
|
||||
ip_whitelist: tenant.ip_whitelist,
|
||||
ip_restriction_message: tenant.ip_restriction_message
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error updating tenant security:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to update security settings'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /tenant/users
|
||||
* Get users in current tenant (user admin or higher)
|
||||
*/
|
||||
router.get('/users', authenticateToken, requirePermissions(['users.view']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Get users in this tenant
|
||||
const users = await User.findAll({
|
||||
where: { tenant_id: tenant.id },
|
||||
attributes: ['id', 'username', 'email', 'role', 'is_active', 'last_login', 'created_at'],
|
||||
order: [['created_at', 'DESC']]
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: users
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching tenant users:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to fetch users'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /tenant/users
|
||||
* Create a new user in current tenant (user admin or higher, local auth only)
|
||||
*/
|
||||
router.post('/users', authenticateToken, requirePermissions(['users.create']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if tenant uses local authentication
|
||||
if (tenant.auth_provider !== 'local') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: `User creation is only available for local authentication. This tenant uses ${tenant.auth_provider}.`
|
||||
});
|
||||
}
|
||||
|
||||
const { username, email, password, role = 'viewer', is_active = true } = req.body;
|
||||
|
||||
// Validate required fields
|
||||
if (!username || !email || !password) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Username, email, and password are required'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['admin', 'operator', 'viewer'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid role. Must be admin, operator, or viewer'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if username or email already exists in this tenant
|
||||
const existingUser = await User.findOne({
|
||||
where: {
|
||||
tenant_id: tenant.id,
|
||||
[require('sequelize').Op.or]: [
|
||||
{ username },
|
||||
{ email }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Username or email already exists in this tenant'
|
||||
});
|
||||
}
|
||||
|
||||
// Create user
|
||||
const user = await User.create({
|
||||
username,
|
||||
email,
|
||||
password_hash: password, // Will be hashed by the model
|
||||
role,
|
||||
is_active,
|
||||
tenant_id: tenant.id,
|
||||
created_by: req.user.id
|
||||
});
|
||||
|
||||
console.log(`✅ User "${username}" created in tenant "${tenantId}" by admin "${req.user.username}"`);
|
||||
|
||||
// Return user data (without password)
|
||||
const userData = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
is_active: user.is_active,
|
||||
created_at: user.created_at
|
||||
};
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'User created successfully',
|
||||
data: userData
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating tenant user:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to create user'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /tenant/users/:userId/status
|
||||
* Update user status (activate/deactivate) (user admin or higher, local auth only)
|
||||
*/
|
||||
router.put('/users/:userId/status', authenticateToken, requirePermissions(['users.edit']), async (req, res) => {
|
||||
try {
|
||||
// Determine tenant from request
|
||||
const tenantId = await multiAuth.determineTenant(req);
|
||||
if (!tenantId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Unable to determine tenant'
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||
if (!tenant) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tenant not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if tenant uses local authentication
|
||||
if (tenant.auth_provider !== 'local') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: `User management is only available for local authentication. This tenant uses ${tenant.auth_provider}.`
|
||||
});
|
||||
}
|
||||
|
||||
const { userId } = req.params;
|
||||
const { is_active } = req.body;
|
||||
|
||||
if (typeof is_active !== 'boolean') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'is_active must be a boolean value'
|
||||
});
|
||||
}
|
||||
|
||||
// Find user in this tenant
|
||||
const user = await User.findOne({
|
||||
where: {
|
||||
id: userId,
|
||||
tenant_id: tenant.id
|
||||
}
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'User not found in this tenant'
|
||||
});
|
||||
}
|
||||
|
||||
// Prevent self-deactivation
|
||||
if (user.id === req.user.id && !is_active) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'You cannot deactivate your own account'
|
||||
});
|
||||
}
|
||||
|
||||
// Update user status
|
||||
await user.update({ is_active });
|
||||
|
||||
console.log(`✅ User "${user.username}" ${is_active ? 'activated' : 'deactivated'} in tenant "${tenantId}" by admin "${req.user.username}"`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `User ${is_active ? 'activated' : 'deactivated'} successfully`,
|
||||
data: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
is_active: user.is_active
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error updating user status:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to update user status'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
131
server/test-rbac.js
Normal file
131
server/test-rbac.js
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Test script to verify RBAC system functionality
|
||||
*/
|
||||
|
||||
const { hasPermission, ROLES, PERMISSIONS } = require('./middleware/rbac');
|
||||
|
||||
// Mock users with different roles
|
||||
const users = {
|
||||
admin: {
|
||||
id: 1,
|
||||
username: 'super_admin',
|
||||
role: 'admin'
|
||||
},
|
||||
user_admin: {
|
||||
id: 2,
|
||||
username: 'user_manager',
|
||||
role: 'user_admin'
|
||||
},
|
||||
security_admin: {
|
||||
id: 3,
|
||||
username: 'security_manager',
|
||||
role: 'security_admin'
|
||||
},
|
||||
branding_admin: {
|
||||
id: 4,
|
||||
username: 'branding_manager',
|
||||
role: 'branding_admin'
|
||||
},
|
||||
operator: {
|
||||
id: 5,
|
||||
username: 'basic_operator',
|
||||
role: 'operator'
|
||||
},
|
||||
viewer: {
|
||||
id: 6,
|
||||
username: 'read_only',
|
||||
role: 'viewer'
|
||||
}
|
||||
};
|
||||
|
||||
// Test scenarios
|
||||
const testScenarios = [
|
||||
{
|
||||
name: 'Admin - Full Access',
|
||||
user: users.admin,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, true, true, true, true, true, true]
|
||||
},
|
||||
{
|
||||
name: 'User Admin - User Management Only',
|
||||
user: users.user_admin,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, false, false, false, true, true, true]
|
||||
},
|
||||
{
|
||||
name: 'Security Admin - Security Only',
|
||||
user: users.security_admin,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, false, false, true, false, false, false]
|
||||
},
|
||||
{
|
||||
name: 'Branding Admin - Branding Only',
|
||||
user: users.branding_admin,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, false, true, false, false, false, false]
|
||||
},
|
||||
{
|
||||
name: 'Operator - Limited Access',
|
||||
user: users.operator,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, false, false, false, false, false, false]
|
||||
},
|
||||
{
|
||||
name: 'Viewer - Read Only',
|
||||
user: users.viewer,
|
||||
permissions: ['tenant.view', 'tenant.edit', 'branding.edit', 'security.edit', 'users.create', 'users.edit', 'users.delete'],
|
||||
expectedResults: [true, false, false, false, false, false, false]
|
||||
}
|
||||
];
|
||||
|
||||
console.log('🧪 Testing RBAC System\n');
|
||||
|
||||
// Display available roles and permissions
|
||||
console.log('📋 Available Roles:');
|
||||
Object.keys(ROLES).forEach(role => {
|
||||
console.log(` ${role}: ${ROLES[role].join(', ')}`);
|
||||
});
|
||||
|
||||
console.log('\n📋 Available Permissions:');
|
||||
Object.keys(PERMISSIONS).forEach(category => {
|
||||
console.log(` ${category}:`);
|
||||
PERMISSIONS[category].forEach(permission => {
|
||||
console.log(` - ${permission}`);
|
||||
});
|
||||
});
|
||||
|
||||
console.log('\n🔍 Running Permission Tests:\n');
|
||||
|
||||
// Run tests
|
||||
let totalTests = 0;
|
||||
let passedTests = 0;
|
||||
|
||||
testScenarios.forEach(scenario => {
|
||||
console.log(`\n👤 ${scenario.name} (${scenario.user.username})`);
|
||||
console.log('─'.repeat(50));
|
||||
|
||||
scenario.permissions.forEach((permission, index) => {
|
||||
totalTests++;
|
||||
const result = hasPermission(scenario.user, permission);
|
||||
const expected = scenario.expectedResults[index];
|
||||
const passed = result === expected;
|
||||
|
||||
if (passed) passedTests++;
|
||||
|
||||
const status = passed ? '✅' : '❌';
|
||||
const expectedText = expected ? 'ALLOW' : 'DENY';
|
||||
const actualText = result ? 'ALLOW' : 'DENY';
|
||||
|
||||
console.log(` ${status} ${permission}: Expected ${expectedText}, Got ${actualText}`);
|
||||
});
|
||||
});
|
||||
|
||||
console.log('\n📊 Test Results:');
|
||||
console.log(` Passed: ${passedTests}/${totalTests}`);
|
||||
console.log(` Success Rate: ${Math.round((passedTests/totalTests) * 100)}%`);
|
||||
|
||||
if (passedTests === totalTests) {
|
||||
console.log('\n🎉 All tests passed! RBAC system is working correctly.');
|
||||
} else {
|
||||
console.log('\n⚠️ Some tests failed. Please check the RBAC configuration.');
|
||||
}
|
||||
Reference in New Issue
Block a user