feat: 3-tier role system across all platform apps

Portal:
- Replace is_admin boolean with role column (admin/advanced/standard)
- Settings UI: 3-tier portal role select + per-app role dropdowns
- /portal-return endpoint: re-establishes session from JWT for sub-app back-links
- /api/internal/nv-users: internal endpoint for NetworkView user sync
- portal/migrate_roles.py: one-time DB migration script
- Role badges (admin/advanced/standard) in topbar and settings table

DigiServer:
- Add editor and viewer roles (portal advanced->editor, standard->viewer)
- PlaylistPermission model: grant viewer users edit access to specific playlists
- app/utils/access.py: shared editor_required, admin_required, can_edit_playlist helpers
- Content routes: editor_required on create/delete, per-playlist permission check on mutations
- Admin: playlist_permissions route + template to manage viewer playlist grants
- Base template: hide Admin nav for viewers, Portal button (⬡) returns to portal
- content_list_new: hide create/delete for viewers; Manage vs View button per permission
- manage_playlist_content: view-only mode when user lacks edit permission

NetworkView:
- backend/src/middleware/rbac.js: requireRole + requireWriteAccess helpers
- site_permissions table: one site per advanced user
- All mutating routes guarded (admin=all, advanced=assigned site, viewer=read-only)
- Portal SSO auto-upsert: user row synced from X-Auth-Role on every request
- GET /api/users: merges portal users list with local NV data (all 4 portal users visible)
- GET/PUT /api/users/:id/site-permission: assign site to advanced user
- Settings Users tab: role badges, site dropdown for advanced, (portal only) indicator
- Sidebar: ⬡ Portal button between Settings and Logout
- Frontend build: VITE_API_BASE=/networkview/api now set in start-dev.sh

IT Assets / Server Monitor:
- portal_sso.py updated: map advanced->editor/viewer, standard->readonly
- AdminUser model: add editor role + is_editor property
This commit is contained in:
ske087
2026-07-07 00:08:46 +03:00
parent 5762dd420d
commit 1f6217d347
41 changed files with 1028 additions and 153 deletions
+4
View File
@@ -84,6 +84,10 @@ export const rotateApiKey = (id: string) =>
request<{ api_key: string }>(`/users/${id}/api-key`, { method: 'POST' });
export const revokeApiKey = (id: string) =>
request(`/users/${id}/api-key`, { method: 'DELETE' });
export const setSitePermission = (userId: string, siteId: string | null) =>
request<{ ok: boolean; site_id: string | null }>(`/users/${userId}/site-permission`, {
method: 'PUT', body: JSON.stringify({ site_id: siteId }),
});
// --- Audit ---
export const getAuditLog = (params: {
+33 -17
View File
@@ -19,6 +19,7 @@ export default function Sidebar() {
const [loading, setLoading] = useState(true);
const [addSiteName, setAddSiteName] = useState('');
const [showAddSite, setShowAddSite] = useState(false);
const [addSiteErr, setAddSiteErr] = useState<string | null>(null);
const navigate = useNavigate();
const location = useLocation();
@@ -74,11 +75,16 @@ export default function Sidebar() {
const handleAddSite = async (e: React.FormEvent) => {
e.preventDefault();
if (!addSiteName.trim()) return;
const site = await api.createSite({ name: addSiteName.trim() });
setAddSiteName('');
setShowAddSite(false);
await loadTree();
navigate(`/sites/${site.id}`);
setAddSiteErr(null);
try {
const site = await api.createSite({ name: addSiteName.trim() });
setAddSiteName('');
setShowAddSite(false);
await loadTree();
navigate(`/sites/${site.id}`);
} catch (ex: unknown) {
setAddSiteErr(ex instanceof Error ? ex.message : String(ex));
}
};
useEffect(() => {
@@ -147,18 +153,21 @@ export default function Sidebar() {
</div>
{showAddSite && (
<form onSubmit={handleAddSite} className="inline-add-form">
<input
autoFocus
type="text"
placeholder="Site name..."
value={addSiteName}
onChange={e => setAddSiteName(e.target.value)}
className="inline-input"
/>
<button type="submit" className="inline-btn">Add</button>
<button type="button" className="inline-btn secondary" onClick={() => setShowAddSite(false)}></button>
</form>
<>
<form onSubmit={handleAddSite} className="inline-add-form">
<input
autoFocus
type="text"
placeholder="Site name..."
value={addSiteName}
onChange={e => setAddSiteName(e.target.value)}
className="inline-input"
/>
<button type="submit" className="inline-btn">Add</button>
<button type="button" className="inline-btn secondary" onClick={() => { setShowAddSite(false); setAddSiteErr(null); }}></button>
</form>
{addSiteErr && <div className="inline-error">{addSiteErr}</div>}
</>
)}
{loading && <div className="sidebar-loading">Loading...</div>}
@@ -229,6 +238,13 @@ export default function Sidebar() {
<Link to="/settings" className={`sidebar-footer-link ${isActive('/settings') ? 'active' : ''}`}>
Settings
</Link>
<a
href="/portal-return"
className="sidebar-footer-link"
title="Back to Enterprise Portal"
>
Portal
</a>
<button
className="sidebar-footer-link sidebar-logout-btn"
onClick={() => { window.location.href = (import.meta.env.VITE_PORTAL_LOGOUT_URL as string | undefined) ?? '/logout'; }}
+3
View File
@@ -172,6 +172,7 @@ a:hover { text-decoration: underline; }
}
.inline-input {
flex: 1;
min-width: 0;
background: var(--surface2);
border: 1px solid var(--accent);
border-radius: var(--radius);
@@ -181,6 +182,7 @@ a:hover { text-decoration: underline; }
outline: none;
}
.inline-btn {
flex-shrink: 0;
background: var(--accent-dim);
border: none;
border-radius: var(--radius);
@@ -190,6 +192,7 @@ a:hover { text-decoration: underline; }
padding: 4px 8px;
}
.inline-btn.secondary { background: var(--surface3); }
.inline-error { padding: 2px 8px 4px; color: var(--danger); font-size: 11px; }
/* Tree nodes */
.tree-node { display: flex; flex-direction: column; }
+56 -13
View File
@@ -14,9 +14,10 @@ const ACTION_COLORS: Record<string, string> = {
};
const ROLE_COLORS: Record<string, string> = {
admin: '#f87171',
editor: '#f59e0b',
viewer: '#8b949e',
admin: '#f87171',
advanced: '#f59e0b',
editor: '#f59e0b',
viewer: '#8b949e',
};
function formatTs(ts: string) {
@@ -40,6 +41,7 @@ function StatsPanel({ stats }: { stats: DbStats }) {
// ── Sub-section: Users ────────────────────────────────────────────────────────
function UsersPanel() {
const [users, setUsers] = useState<User[]>([]);
const [sites, setSites] = useState<{ id: string; name: string }[]>([]);
const [loading, setLoading] = useState(true);
const [showAdd, setShowAdd] = useState(false);
const [form, setForm] = useState({ username: '', email: '', role: 'viewer' });
@@ -48,7 +50,9 @@ function UsersPanel() {
const load = useCallback(async () => {
setLoading(true);
setUsers(await api.getUsers());
const [us, ss] = await Promise.all([api.getUsers(), api.getSites()]);
setUsers(us);
setSites(ss);
setLoading(false);
}, []);
@@ -90,6 +94,21 @@ function UsersPanel() {
await load();
};
const handleSitePermission = async (u: User, siteId: string | null) => {
try {
await api.setSitePermission(u.id, siteId);
await load();
} catch (ex: unknown) {
alert(ex instanceof Error ? ex.message : String(ex));
}
};
const ROLE_LABEL: Record<string, string> = {
admin: '★ admin',
advanced: '✏ advanced',
viewer: '👁 viewer',
};
return (
<div className="settings-section">
<div className="settings-section-header">
@@ -97,8 +116,8 @@ function UsersPanel() {
<button className="btn-primary btn-sm" onClick={() => setShowAdd(v => !v)}>+ Add User</button>
</div>
<p className="settings-desc">
User accounts for this NetworkView instance. Authentication is delegated to your central app
set <code>X-User-Id</code> + <code>X-Username</code> headers on API requests, or use per-user API keys.
Users are automatically synced from the Enterprise Portal on each login.
Roles: <strong>admin</strong> full access · <strong>advanced</strong> CRUD on one assigned site · <strong>viewer</strong> read-only.
</p>
{showAdd && (
@@ -115,9 +134,9 @@ function UsersPanel() {
className="modal-select"
value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))}
>
<option value="viewer">Viewer</option>
<option value="editor">Editor</option>
<option value="admin">Admin</option>
<option value="viewer">👁 Viewer read-only</option>
<option value="advanced"> Advanced one site</option>
<option value="admin"> Admin full access</option>
</select>
{err && <div className="settings-error">{err}</div>}
<div className="form-actions">
@@ -142,19 +161,43 @@ function UsersPanel() {
<table className="settings-user-table">
<thead>
<tr>
<th>Username</th><th>Email</th><th>Role</th><th>Status</th><th>API Key</th><th>Actions</th>
<th>Username</th><th>Email</th><th>Role</th><th>Assigned Site</th><th>Status</th><th>API Key</th><th>Actions</th>
</tr>
</thead>
<tbody>
{users.map(u => (
<tr key={u.id} style={{ opacity: u.is_active ? 1 : 0.5 }}>
<td><strong>{u.username}</strong></td>
<td><strong>{u.username}</strong>{u.not_yet_synced && (
<span title="User exists in portal but hasn't logged into NetworkView yet"
style={{ marginLeft: 6, fontSize: 10, color: 'var(--text3)', verticalAlign: 'middle' }}>
(portal only)
</span>
)}</td>
<td style={{ color: 'var(--text3)', fontSize: 12 }}>{u.email ?? '—'}</td>
<td>
<span className="status-badge" style={{ color: ROLE_COLORS[u.role] ?? '#8b949e', borderColor: ROLE_COLORS[u.role] ?? '#8b949e' }}>
{u.role}
{ROLE_LABEL[u.role] ?? u.role}
</span>
</td>
<td style={{ minWidth: 160 }}>
{u.role === 'advanced' ? (
<select
className="modal-select"
style={{ fontSize: 12, padding: '2px 6px' }}
value={u.site_permission?.site_id ?? ''}
onChange={e => handleSitePermission(u, e.target.value || null)}
>
<option value=""> no site assigned </option>
{sites.map(s => (
<option key={s.id} value={s.id}>{s.name}</option>
))}
</select>
) : (
<span style={{ color: 'var(--text3)', fontSize: 12 }}>
{u.role === 'admin' ? 'all sites' : '—'}
</span>
)}
</td>
<td>
<span className={`status-badge status-${u.is_active ? 'active' : 'decommissioned'}`}>
{u.is_active ? 'active' : 'inactive'}
@@ -177,7 +220,7 @@ function UsersPanel() {
</tr>
))}
{users.length === 0 && (
<tr><td colSpan={6} style={{ textAlign: 'center', color: 'var(--text3)', padding: 20 }}>No users yet</td></tr>
<tr><td colSpan={7} style={{ textAlign: 'center', color: 'var(--text3)', padding: 20 }}>No users yet</td></tr>
)}
</tbody>
</table>
+5 -3
View File
@@ -143,11 +143,13 @@ export interface User {
id: string;
username: string;
email?: string;
role: 'admin' | 'editor' | 'viewer';
role: 'admin' | 'advanced' | 'viewer';
is_active: boolean;
has_api_key: boolean;
created_at: string;
updated_at: string;
site_permission: { site_id: string; site_name: string } | null;
not_yet_synced?: boolean;
created_at: string | null;
updated_at: string | null;
}
export interface AuditEntry {