proper src structure, dockerfile, entrypoint

This commit is contained in:
jarek committed 2025-12-29 08:40:11 +01:00
1 parent e5828c7d31
commit 73c9f580a1
556 files changed
+1390

No files matched your search

+326
View File
@@ -0,0 +1,326 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import {
Shield,
User,
Settings,
Crown,
KeyRound,
Network,
LogIn,
RefreshCw,
Save
} from 'lucide-svelte';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import { canAccess, authStore } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
// Sub-tab components
import UsersSubTab from './users/UsersSubTab.svelte';
import LdapSubTab from './ldap/LdapSubTab.svelte';
import SsoSubTab from './oidc/SsoSubTab.svelte';
import RolesSubTab from './roles/RolesSubTab.svelte';
// Props
interface Props {
onTabChange?: (tab: string) => void;
}
let { onTabChange = (_tab: string) => {} }: Props = $props();
// Role type for passing to sub-tabs
interface Role {
id: number;
name: string;
description?: string;
isSystem: boolean;
permissions: any;
createdAt: string;
}
// Authentication state
let authSubTab = $state<'general' | 'local' | 'ldap' | 'sso' | 'roles'>('general');
let authEnabled = $state(false);
let authLoading = $state(true);
let sessionTimeout = $state(86400);
let authSaving = $state(false);
// Roles state (shared with sub-tabs that need it)
let roles = $state<Role[]>([]);
// === Authentication Functions ===
async function fetchAuthSettings() {
authLoading = true;
try {
const response = await fetch('/api/auth/settings');
if (response.ok) {
const data = await response.json();
authEnabled = data.authEnabled;
sessionTimeout = data.sessionTimeout || 86400;
}
} catch (error) {
console.error('Failed to fetch auth settings:', error);
} finally {
authLoading = false;
}
}
async function fetchRoles() {
try {
const response = await fetch('/api/roles');
if (response.ok) {
roles = await response.json();
}
} catch (error) {
console.error('Failed to fetch roles:', error);
}
}
async function handleAuthEnabledToggle(checked: boolean) {
authSaving = true;
try {
const response = await fetch('/api/auth/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ authEnabled: checked })
});
if (response.ok) {
// authEnabled already updated via binding
toast.success(checked ? 'Authentication enabled' : 'Authentication disabled');
// Update global auth store so other components react immediately
await authStore.check();
} else {
const data = await response.json();
toast.error(data.error || 'Failed to update auth settings');
// Revert toggle on error - checked is new value, so previous was !checked
authEnabled = !checked;
}
} catch (error) {
console.error('Failed to update auth settings:', error);
toast.error('Failed to update auth settings');
// Revert toggle on error
authEnabled = !checked;
} finally {
authSaving = false;
}
}
async function saveAuthSettings() {
authSaving = true;
try {
const response = await fetch('/api/auth/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionTimeout: sessionTimeout })
});
if (response.ok) {
toast.success('Settings saved');
} else {
console.error('Failed to save auth settings');
toast.error('Failed to save settings');
}
} catch (error) {
console.error('Failed to save auth settings:', error);
toast.error('Failed to save settings');
} finally {
authSaving = false;
}
}
// Initialize on mount
onMount(() => {
fetchAuthSettings();
});
// Fetch roles reactively when enterprise license is detected or when switching to users tab
$effect(() => {
if ($licenseStore.isEnterprise) {
fetchRoles();
}
});
// Refetch roles when switching to users tab (in case roles were added/modified)
$effect(() => {
if (authSubTab === 'local' && $licenseStore.isEnterprise) {
fetchRoles();
}
});
</script>
<div class="flex flex-col flex-1 min-h-0">
<!-- Auth Enable/Disable Toggle at Top -->
<div class="flex items-start gap-3 p-3 mb-3 border rounded-md bg-muted/30 flex-shrink-0">
<Shield class="w-5 h-5 text-muted-foreground mt-0.5" />
<div class="flex-1">
<div class="flex items-center gap-3">
<p class="text-sm font-medium">Authentication</p>
<TogglePill
bind:checked={authEnabled}
onchange={(checked) => handleAuthEnabledToggle(checked)}
disabled={authLoading || authSaving || !$canAccess('settings', 'edit')}
/>
</div>
<p class="text-xs text-muted-foreground mt-1">
{authEnabled
? 'Users must log in to access the application'
: 'Authentication is disabled - open access'}
</p>
<p class="text-xs text-muted-foreground mt-1 flex items-center gap-1">
<Crown class="w-3 h-3 text-amber-500" />
{#if $licenseStore.isEnterprise}
{authEnabled
? 'Audit logging is active - all actions are recorded'
: 'Enable authentication to activate audit logging'}
{:else}
Enable authentication to activate audit logging
{/if}
</p>
</div>
</div>
<!-- Auth Subtabs Navigation -->
<div class="inline-flex gap-1 p-1 bg-muted/50 rounded-lg mb-3 flex-shrink-0">
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all {authSubTab ===
'general'
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => (authSubTab = 'general')}
>
<Settings class="w-4 h-4" />
General
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all {authSubTab ===
'local'
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => (authSubTab = 'local')}
>
<User class="w-4 h-4" />
Users
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all {authSubTab ===
'sso'
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => (authSubTab = 'sso')}
>
<LogIn class="w-4 h-4" />
SSO / OIDC
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all {authSubTab ===
'ldap'
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => (authSubTab = 'ldap')}
>
<Network class="w-4 h-4" />
LDAP / AD
<Crown class="w-3 h-3 text-amber-500" />
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all {authSubTab ===
'roles'
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'}"
onclick={() => (authSubTab = 'roles')}
>
<Shield class="w-4 h-4" />
Roles
<Crown class="w-3 h-3 text-amber-500" />
</button>
</div>
<!-- Sub-tab Content -->
<div class="flex flex-col flex-1 min-h-0 overflow-hidden">
<!-- General Settings Subtab -->
{#if authSubTab === 'general'}
<div class="flex-1 min-h-0 overflow-y-auto space-y-4">
{#if authEnabled}
<Card.Root>
<Card.Header>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<KeyRound class="w-4 h-4" />
Session settings
</Card.Title>
</Card.Header>
<Card.Content class="space-y-4">
<div class="space-y-1.5">
<Label class="text-sm">Session timeout</Label>
<p class="text-xs text-muted-foreground mb-2">
How long until inactive sessions expire
</p>
<div class="flex items-center gap-2">
<Input
type="number"
value={sessionTimeout}
min={3600}
max={604800}
onchange={(e) => (sessionTimeout = parseInt(e.currentTarget.value))}
class="w-32"
disabled={!$canAccess('settings', 'edit')}
/>
<span class="text-sm text-muted-foreground">seconds</span>
<span class="text-xs text-muted-foreground">
({Math.floor(sessionTimeout / 3600)} hours)
</span>
</div>
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={saveAuthSettings} disabled={authSaving}>
{#if authSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Save class="w-4 h-4 mr-1" />
{/if}
Save settings
</Button>
{/if}
</Card.Content>
</Card.Root>
{:else}
<div class="text-center py-12 text-muted-foreground">
<Shield class="w-12 h-12 mx-auto mb-3 opacity-30" />
<p class="text-sm">Enable authentication to configure session settings</p>
</div>
{/if}
</div>
{/if}
<!-- Local Users Subtab -->
{#if authSubTab === 'local'}
<div class="flex flex-col flex-1 min-h-0">
<UsersSubTab {roles} />
</div>
{/if}
<!-- LDAP / AD Subtab -->
{#if authSubTab === 'ldap'}
<div class="flex-1 min-h-0 overflow-y-auto">
<LdapSubTab {onTabChange} />
</div>
{/if}
<!-- SSO / OIDC Subtab -->
{#if authSubTab === 'sso'}
<div class="flex-1 min-h-0 overflow-y-auto">
<SsoSubTab {roles} />
</div>
{/if}
<!-- Roles Subtab -->
{#if authSubTab === 'roles'}
<div class="flex-1 min-h-0 overflow-y-auto">
<RolesSubTab {onTabChange} />
</div>
{/if}
</div>
</div>
@@ -0,0 +1,508 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/dialog';
import * as Tabs from '$lib/components/ui/tabs';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as Select from '$lib/components/ui/select';
import { Network, Pencil, Plus, Check, RefreshCw, TriangleAlert, Trash2, Star } from 'lucide-svelte';
import * as Alert from '$lib/components/ui/alert';
import { focusFirstInput } from '$lib/utils';
export interface LdapRoleMapping {
groupDn: string;
roleId: number;
}
export interface LdapConfig {
id: number;
name: string;
enabled: boolean;
serverUrl: string;
bindDn?: string;
bindPassword?: string;
baseDn: string;
userFilter: string;
usernameAttribute: string;
emailAttribute: string;
displayNameAttribute: string;
groupBaseDn?: string;
groupFilter?: string;
adminGroup?: string;
roleMappings?: LdapRoleMapping[];
tlsEnabled: boolean;
tlsCa?: string;
}
interface Role {
id: number;
name: string;
isSystem: boolean;
}
interface Props {
open: boolean;
ldap?: LdapConfig | null;
roles?: Role[];
isEnterprise?: boolean;
onClose: () => void;
onSaved: () => void;
}
let { open = $bindable(), ldap = null, roles = [], isEnterprise = false, onClose, onSaved }: Props = $props();
const isEditing = $derived(ldap !== null);
// Form state
let formName = $state('');
let formEnabled = $state(false);
let formServerUrl = $state('');
let formBindDn = $state('');
let formBindPassword = $state('');
let formBaseDn = $state('');
let formUserFilter = $state('(uid={{username}})');
let formUsernameAttr = $state('uid');
let formEmailAttr = $state('mail');
let formDisplayNameAttr = $state('cn');
let formGroupBaseDn = $state('');
let formGroupFilter = $state('');
let formAdminGroup = $state('');
let formRoleMappings = $state<LdapRoleMapping[]>([]);
let formTlsEnabled = $state(false);
let formTlsCa = $state('');
let formError = $state('');
let formErrors = $state<{ name?: string; serverUrl?: string; baseDn?: string }>({});
let formSaving = $state(false);
let formModalTab = $state<'connection' | 'groups'>('connection');
// Role mapping helpers
function addRoleMapping() {
formRoleMappings = [...formRoleMappings, { groupDn: '', roleId: 0 }];
}
function removeRoleMapping(index: number) {
formRoleMappings = formRoleMappings.filter((_, i) => i !== index);
}
function updateRoleMappingRole(index: number, roleId: number) {
formRoleMappings = formRoleMappings.map((mapping, i) =>
i === index ? { ...mapping, roleId } : mapping
);
}
function updateRoleMappingGroupDn(index: number, groupDn: string) {
formRoleMappings = formRoleMappings.map((mapping, i) =>
i === index ? { ...mapping, groupDn } : mapping
);
}
function resetForm() {
formName = '';
formEnabled = false;
formServerUrl = '';
formBindDn = '';
formBindPassword = '';
formBaseDn = '';
formUserFilter = '(uid={{username}})';
formUsernameAttr = 'uid';
formEmailAttr = 'mail';
formDisplayNameAttr = 'cn';
formGroupBaseDn = '';
formGroupFilter = '';
formAdminGroup = '';
formRoleMappings = [];
formTlsEnabled = false;
formTlsCa = '';
formError = '';
formErrors = {};
formSaving = false;
formModalTab = 'connection';
}
// Initialize form when ldap changes or modal opens
$effect(() => {
if (open) {
if (ldap) {
formName = ldap.name;
formEnabled = ldap.enabled;
formServerUrl = ldap.serverUrl;
formBindDn = ldap.bindDn || '';
formBindPassword = ldap.bindPassword || '';
formBaseDn = ldap.baseDn;
formUserFilter = ldap.userFilter || '(uid={{username}})';
formUsernameAttr = ldap.usernameAttribute || 'uid';
formEmailAttr = ldap.emailAttribute || 'mail';
formDisplayNameAttr = ldap.displayNameAttribute || 'cn';
formGroupBaseDn = ldap.groupBaseDn || '';
formGroupFilter = ldap.groupFilter || '';
formAdminGroup = ldap.adminGroup || '';
formRoleMappings = ldap.roleMappings || [];
formTlsEnabled = ldap.tlsEnabled || false;
formTlsCa = ldap.tlsCa || '';
formError = '';
formErrors = {};
formSaving = false;
formModalTab = 'connection';
} else {
resetForm();
}
}
});
async function save() {
formErrors = {};
let hasErrors = false;
if (!formName.trim()) {
formErrors.name = 'Name is required';
hasErrors = true;
}
if (!formServerUrl.trim()) {
formErrors.serverUrl = 'Server URL is required';
hasErrors = true;
}
if (!formBaseDn.trim()) {
formErrors.baseDn = 'Base DN is required';
hasErrors = true;
}
if (hasErrors) return;
formSaving = true;
formError = '';
try {
const url = isEditing ? `/api/auth/ldap/${ldap!.id}` : '/api/auth/ldap';
const method = isEditing ? 'PUT' : 'POST';
// Filter valid role mappings (both groupDn and roleId must be set)
const validRoleMappings = formRoleMappings.filter(m => m.groupDn.trim() && m.roleId);
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: formName.trim(),
enabled: formEnabled,
serverUrl: formServerUrl.trim(),
bindDn: formBindDn.trim() || undefined,
bindPassword: formBindPassword || undefined,
baseDn: formBaseDn.trim(),
userFilter: formUserFilter.trim() || '(uid={{username}})',
usernameAttribute: formUsernameAttr.trim() || 'uid',
emailAttribute: formEmailAttr.trim() || 'mail',
displayNameAttribute: formDisplayNameAttr.trim() || 'cn',
groupBaseDn: formGroupBaseDn.trim() || undefined,
groupFilter: formGroupFilter.trim() || undefined,
adminGroup: formAdminGroup.trim() || undefined,
roleMappings: validRoleMappings.length > 0 ? validRoleMappings : undefined,
tlsEnabled: formTlsEnabled,
tlsCa: formTlsCa.trim() || undefined
})
});
if (response.ok) {
open = false;
onSaved();
} else {
const data = await response.json();
formError = data.error || `Failed to ${isEditing ? 'update' : 'create'} LDAP configuration`;
}
} catch {
formError = `Failed to ${isEditing ? 'update' : 'create'} LDAP configuration`;
} finally {
formSaving = false;
}
}
function handleClose() {
open = false;
onClose();
}
</script>
<Dialog.Root bind:open onOpenChange={(o) => { if (o) { formError = ''; formErrors = {}; formModalTab = 'connection'; focusFirstInput(); } }}>
<Dialog.Content class="max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">
<Dialog.Header class="flex-shrink-0">
<Dialog.Title class="flex items-center gap-2">
{#if isEditing}
<Pencil class="w-5 h-5" />
Edit LDAP configuration
{:else}
<Network class="w-5 h-5" />
Add LDAP configuration
{/if}
</Dialog.Title>
</Dialog.Header>
<div class="flex-1 overflow-y-auto py-2">
{#if formError}
<Alert.Root variant="destructive" class="mb-4">
<TriangleAlert class="h-4 w-4" />
<Alert.Description>{formError}</Alert.Description>
</Alert.Root>
{/if}
<Tabs.Root bind:value={formModalTab}>
<Tabs.List class="grid w-full grid-cols-2 mb-4">
<Tabs.Trigger value="connection">Connection</Tabs.Trigger>
<Tabs.Trigger value="groups">Group settings</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="connection" class="space-y-4">
<!-- Basic Settings -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Basic settings</h4>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Name <span class="text-destructive">*</span></Label>
<Input
bind:value={formName}
placeholder="Corporate LDAP"
class={formErrors.name ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.name = undefined}
/>
{#if formErrors.name}
<p class="text-xs text-destructive">{formErrors.name}</p>
{/if}
</div>
<div class="space-y-2">
<Label>Server URL <span class="text-destructive">*</span></Label>
<Input
bind:value={formServerUrl}
placeholder="ldap://ldap.example.com:389"
class={formErrors.serverUrl ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.serverUrl = undefined}
/>
{#if formErrors.serverUrl}
<p class="text-xs text-destructive">{formErrors.serverUrl}</p>
{/if}
</div>
</div>
<div class="flex items-center gap-2">
<Checkbox
checked={formEnabled}
onCheckedChange={(checked) => formEnabled = checked === true}
/>
<Label class="text-sm font-normal cursor-pointer" onclick={() => formEnabled = !formEnabled}>
Enable this LDAP configuration
</Label>
</div>
</div>
<!-- Bind Credentials -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Bind credentials (optional)</h4>
<p class="text-xs text-muted-foreground">Service account used to search for users. Leave empty for anonymous bind.</p>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Bind DN</Label>
<Input
bind:value={formBindDn}
placeholder="cn=admin,dc=example,dc=com"
/>
</div>
<div class="space-y-2">
<Label>Bind password</Label>
<Input
type="password"
bind:value={formBindPassword}
placeholder={isEditing ? 'Leave blank to keep existing' : 'Enter password'}
/>
</div>
</div>
</div>
<!-- Search Settings -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">User search settings</h4>
<div class="space-y-2">
<Label>Base DN <span class="text-destructive">*</span></Label>
<Input
bind:value={formBaseDn}
placeholder="dc=example,dc=com"
class={formErrors.baseDn ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.baseDn = undefined}
/>
{#if formErrors.baseDn}
<p class="text-xs text-destructive">{formErrors.baseDn}</p>
{:else}
<p class="text-xs text-muted-foreground">The base DN to search for users.</p>
{/if}
</div>
<div class="space-y-2">
<Label>User filter</Label>
<Input
bind:value={formUserFilter}
placeholder={`(uid={{username}})`}
/>
<p class="text-xs text-muted-foreground">
LDAP filter to find users. Use <code class="text-xs bg-muted px-1 rounded">{`{{username}}`}</code> as placeholder.<br />
<span class="text-muted-foreground/70">OpenLDAP: <code class="text-xs bg-muted px-1 rounded">(uid={`{{username}}`})</code> &bull; AD: <code class="text-xs bg-muted px-1 rounded">(sAMAccountName={`{{username}}`})</code></span>
</p>
</div>
</div>
<!-- Attribute Mapping -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Attribute mapping</h4>
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2">
<Label>Username attribute</Label>
<Input
bind:value={formUsernameAttr}
placeholder="uid"
/>
</div>
<div class="space-y-2">
<Label>Email attribute</Label>
<Input
bind:value={formEmailAttr}
placeholder="mail"
/>
</div>
<div class="space-y-2">
<Label>Display name attribute</Label>
<Input
bind:value={formDisplayNameAttr}
placeholder="cn"
/>
</div>
</div>
</div>
<!-- TLS Settings -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">TLS settings</h4>
<div class="flex items-center gap-2">
<Checkbox
checked={formTlsEnabled}
onCheckedChange={(checked) => formTlsEnabled = checked === true}
/>
<Label class="text-sm font-normal cursor-pointer" onclick={() => formTlsEnabled = !formTlsEnabled}>
Enable TLS (LDAPS or StartTLS)
</Label>
</div>
{#if formTlsEnabled}
<div class="space-y-2">
<Label>CA certificate (optional)</Label>
<textarea
bind:value={formTlsCa}
class="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 font-mono"
placeholder="-----BEGIN CERTIFICATE-----&#10;...&#10;-----END CERTIFICATE-----"
></textarea>
</div>
{/if}
</div>
</Tabs.Content>
<Tabs.Content value="groups" class="space-y-4">
<!-- Group Settings -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Group settings</h4>
<p class="text-xs text-muted-foreground">Configure group-based access control. These settings are optional.</p>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Group base DN</Label>
<Input
bind:value={formGroupBaseDn}
placeholder="ou=groups,dc=example,dc=com"
/>
<p class="text-xs text-muted-foreground">The base DN to search for groups.</p>
</div>
<div class="space-y-2">
<Label>Admin group</Label>
<Input
bind:value={formAdminGroup}
placeholder="cn=admins,ou=groups,dc=example,dc=com"
/>
<p class="text-xs text-muted-foreground">Members of this group will be admins.</p>
</div>
</div>
<div class="space-y-2">
<Label>Member filter</Label>
<Input
bind:value={formGroupFilter}
placeholder={'(&(objectClass=groupOfNames)(member={{user_dn}}))'}
/>
<p class="text-xs text-muted-foreground">
Filter to find groups the user belongs to. Use <code class="text-xs bg-muted px-1 rounded">{'{{user_dn}}'}</code> as placeholder.
</p>
</div>
</div>
<!-- Role Mappings (Enterprise) -->
{#if isEnterprise}
<div class="space-y-4">
<div class="flex items-center gap-2">
<h4 class="text-sm font-medium text-muted-foreground">Group to role mappings</h4>
<Star class="w-3.5 h-3.5 text-amber-500" />
</div>
<p class="text-xs text-muted-foreground">Map LDAP groups to Dockhand roles. Users in these groups will be assigned the corresponding role.</p>
{#if formRoleMappings.length > 0}
<div class="space-y-2">
{#each formRoleMappings as mapping, index}
<div class="flex items-center gap-2">
<Input
value={mapping.groupDn}
placeholder="cn=developers,ou=groups,dc=example,dc=com"
class="flex-1"
oninput={(e) => updateRoleMappingGroupDn(index, e.currentTarget.value)}
/>
<Select.Root
type="single"
value={mapping.roleId ? String(mapping.roleId) : undefined}
onValueChange={(value) => updateRoleMappingRole(index, parseInt(value))}
>
<Select.Trigger class="w-40">
{#if mapping.roleId}
{@const role = roles.find(r => r.id === mapping.roleId)}
{role?.name || 'Select role'}
{:else}
Select role
{/if}
</Select.Trigger>
<Select.Content>
{#each roles.filter(r => !r.isSystem || r.name !== 'Admin') as role}
<Select.Item value={String(role.id)}>{role.name}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
<Button
variant="ghost"
size="icon"
class="h-9 w-9 text-muted-foreground hover:text-destructive"
onclick={() => removeRoleMapping(index)}
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
{/each}
</div>
{/if}
<Button variant="outline" size="sm" onclick={addRoleMapping}>
<Plus class="w-4 h-4 mr-1" />
Add mapping
</Button>
</div>
{/if}
</Tabs.Content>
</Tabs.Root>
</div>
<Dialog.Footer class="flex-shrink-0 border-t pt-4">
<Button variant="outline" onclick={handleClose}>Cancel</Button>
<Button onclick={save} disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
{:else}
<Plus class="w-4 h-4 mr-1" />
{/if}
{isEditing ? 'Save' : 'Add configuration'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
@@ -0,0 +1,320 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Badge } from '$lib/components/ui/badge';
import {
Network,
Plus,
Pencil,
Trash2,
RefreshCw,
Crown,
Key
} from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import LdapModal from './LdapModal.svelte';
import { EmptyState } from '$lib/components/ui/empty-state';
interface LdapRoleMapping {
groupDn: string;
roleId: number;
}
interface LdapConfig {
id: number;
name: string;
enabled: boolean;
serverUrl: string;
bindDn?: string;
bindPassword?: string;
baseDn: string;
userFilter: string;
usernameAttribute: string;
emailAttribute: string;
displayNameAttribute: string;
groupBaseDn?: string;
groupFilter?: string;
adminGroup?: string;
roleMappings?: LdapRoleMapping[];
tlsEnabled: boolean;
tlsCa?: string;
}
interface Role {
id: number;
name: string;
isSystem: boolean;
}
interface Props {
onTabChange?: (tab: string) => void;
}
let { onTabChange = () => {} }: Props = $props();
// LDAP state
let ldapConfigs = $state<LdapConfig[]>([]);
let ldapLoading = $state(true);
let showLdapModal = $state(false);
let editingLdap = $state<LdapConfig | null>(null);
let confirmDeleteLdapId = $state<number | null>(null);
let ldapTesting = $state<number | null>(null);
let ldapTestResult = $state<{ success: boolean; error?: string; userCount?: number } | null>(null);
let roles = $state<Role[]>([]);
async function fetchLdapConfigs() {
ldapLoading = true;
try {
const response = await fetch('/api/auth/ldap');
if (response.ok) {
ldapConfigs = await response.json();
}
} catch (error) {
console.error('Failed to fetch LDAP configs:', error);
toast.error('Failed to fetch LDAP configurations');
} finally {
ldapLoading = false;
}
}
async function fetchRoles() {
try {
const response = await fetch('/api/roles');
if (response.ok) {
roles = await response.json();
}
} catch (error) {
console.error('Failed to fetch roles:', error);
}
}
function openLdapModal(config: LdapConfig | null) {
editingLdap = config;
showLdapModal = true;
}
function handleLdapModalClose() {
showLdapModal = false;
editingLdap = null;
}
async function handleLdapModalSaved() {
showLdapModal = false;
editingLdap = null;
await fetchLdapConfigs();
}
async function deleteLdapConfig(configId: number) {
try {
const response = await fetch(`/api/auth/ldap/${configId}`, { method: 'DELETE' });
if (response.ok) {
await fetchLdapConfigs();
toast.success('LDAP configuration deleted');
} else {
toast.error('Failed to delete LDAP configuration');
}
} catch (error) {
console.error('Failed to delete LDAP config:', error);
toast.error('Failed to delete LDAP configuration');
} finally {
confirmDeleteLdapId = null;
}
}
async function testLdapConnection(configId: number) {
ldapTesting = configId;
ldapTestResult = null;
try {
const response = await fetch(`/api/auth/ldap/${configId}/test`, { method: 'POST' });
const data = await response.json();
ldapTestResult = data;
if (data.success) {
toast.success(`LDAP connection successful - found ${data.userCount} users`);
} else {
toast.error(`LDAP connection failed: ${data.error}`);
}
} catch (error) {
ldapTestResult = { success: false, error: 'Failed to test connection' };
toast.error('Failed to test LDAP connection');
} finally {
ldapTesting = null;
}
}
async function toggleLdapEnabled(config: LdapConfig) {
try {
const response = await fetch(`/api/auth/ldap/${config.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...config, enabled: !config.enabled })
});
if (response.ok) {
await fetchLdapConfigs();
toast.success(`LDAP ${config.enabled ? 'disabled' : 'enabled'}`);
} else {
toast.error('Failed to toggle LDAP configuration');
}
} catch (error) {
console.error('Failed to toggle LDAP config:', error);
toast.error('Failed to toggle LDAP configuration');
}
}
// Fetch data when license is confirmed as enterprise
let hasFetched = $state(false);
$effect(() => {
if ($licenseStore.isEnterprise && !$licenseStore.loading && !hasFetched) {
hasFetched = true;
fetchLdapConfigs();
fetchRoles();
}
});
</script>
{#if $licenseStore.loading}
<Card.Root>
<Card.Content class="py-12">
<div class="flex justify-center">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
</Card.Content>
</Card.Root>
{:else if !$licenseStore.isEnterprise}
<Card.Root>
<Card.Content class="py-12">
<div class="text-center">
<h3 class="text-lg font-medium mb-2 flex items-center justify-center gap-2">
<Crown class="w-5 h-5 text-amber-500" />
Enterprise feature
</h3>
<p class="text-sm text-muted-foreground mb-4 max-w-md mx-auto">
LDAP / Active Directory integration is available with an enterprise license. Connect to your organization's directory services for centralized authentication.
</p>
<Button onclick={() => onTabChange('license')}>
<Key class="w-4 h-4 mr-2" />
Activate license
</Button>
</div>
</Card.Content>
</Card.Root>
{:else}
<div class="space-y-4">
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<Network class="w-4 h-4" />
LDAP configurations
</Card.Title>
<p class="text-xs text-muted-foreground mt-1">Connect to LDAP or Active Directory servers for centralized user authentication.</p>
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openLdapModal(null)}>
<Plus class="w-4 h-4 mr-1" />
Add LDAP
</Button>
{/if}
</div>
</Card.Header>
<Card.Content>
{#if ldapLoading}
<div class="flex justify-center py-8">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
{:else if ldapConfigs.length === 0}
<EmptyState
icon={Network}
title="No LDAP providers configured"
description="Click 'Add LDAP' to configure a new LDAP server"
class="py-8"
/>
{:else}
<div class="space-y-3">
{#each ldapConfigs as config}
<div class="flex items-center justify-between p-3 border rounded-lg">
<div class="flex items-center gap-3">
<Network class="w-5 h-5 text-muted-foreground" />
<div>
<div class="flex items-center gap-2">
<span class="font-medium">{config.name}</span>
{#if config.enabled}
<Badge variant="default" class="text-xs">Enabled</Badge>
{:else}
<Badge variant="secondary" class="text-xs">Disabled</Badge>
{/if}
</div>
<p class="text-xs text-muted-foreground">{config.serverUrl}</p>
</div>
</div>
<div class="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onclick={() => testLdapConnection(config.id)}
disabled={ldapTesting === config.id}
>
{#if ldapTesting === config.id}
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
Test
{/if}
</Button>
{#if $canAccess('settings', 'edit')}
<Button
variant="outline"
size="sm"
onclick={() => toggleLdapEnabled(config)}
>
{config.enabled ? 'Disable' : 'Enable'}
</Button>
<Button
variant="outline"
size="sm"
onclick={() => openLdapModal(config)}
>
<Pencil class="w-4 h-4" />
</Button>
<ConfirmPopover
open={confirmDeleteLdapId === config.id}
action="Delete"
itemType="LDAP config"
itemName={config.name}
onConfirm={() => deleteLdapConfig(config.id)}
onOpenChange={(open) => confirmDeleteLdapId = open ? config.id : null}
>
{#snippet children({ open })}
<Trash2 class="w-4 h-4 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
{/snippet}
</ConfirmPopover>
{/if}
</div>
</div>
{/each}
</div>
{#if ldapTestResult}
<div class="mt-4 p-3 rounded-lg {ldapTestResult.success ? 'bg-green-500/10 text-green-600' : 'bg-destructive/10 text-destructive'}">
{#if ldapTestResult.success}
<p class="text-sm">Connection successful! Found {ldapTestResult.userCount} users.</p>
{:else}
<p class="text-sm">Connection failed: {ldapTestResult.error}</p>
{/if}
</div>
{/if}
{/if}
</Card.Content>
</Card.Root>
</div>
{/if}
<LdapModal
bind:open={showLdapModal}
ldap={editingLdap}
{roles}
isEnterprise={$licenseStore.isEnterprise}
onClose={handleLdapModalClose}
onSaved={handleLdapModalSaved}
/>
@@ -0,0 +1,511 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/dialog';
import * as Tabs from '$lib/components/ui/tabs';
import * as Select from '$lib/components/ui/select';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import { LogIn, Pencil, Plus, Check, RefreshCw, Crown, Key, Shield, Trash2, TriangleAlert } from 'lucide-svelte';
import * as Alert from '$lib/components/ui/alert';
import { focusFirstInput } from '$lib/utils';
export interface OidcConfig {
id: number;
name: string;
enabled: boolean;
issuerUrl: string;
clientId: string;
clientSecret: string;
redirectUri: string;
scopes: string;
usernameClaim: string;
emailClaim: string;
displayNameClaim: string;
adminClaim?: string;
adminValue?: string;
roleMappingsClaim?: string;
roleMappings?: { claimValue: string; roleId: number }[];
}
export interface Role {
id: number;
name: string;
description?: string;
is_system: boolean;
permissions: any;
created_at: string;
}
interface Props {
open: boolean;
oidc?: OidcConfig | null;
roles: Role[];
isEnterprise: boolean;
onClose: () => void;
onSaved: () => void;
onNavigateToLicense?: () => void;
}
let { open = $bindable(), oidc = null, roles, isEnterprise, onClose, onSaved, onNavigateToLicense }: Props = $props();
const isEditing = $derived(oidc !== null);
// Form state
let formName = $state('');
let formEnabled = $state(false);
let formIssuerUrl = $state('');
let formClientId = $state('');
let formClientSecret = $state('');
let formRedirectUri = $state('');
let formScopes = $state('openid profile email');
let formUsernameClaim = $state('preferred_username');
let formEmailClaim = $state('email');
let formDisplayNameClaim = $state('name');
let formAdminClaim = $state('');
let formAdminValue = $state('');
let formRoleMappingsClaim = $state('groups');
let formRoleMappings = $state<{ claim_value: string; role_id: number }[]>([]);
let formActiveTab = $state('general');
let formError = $state('');
let formErrors = $state<{ name?: string; issuerUrl?: string; clientId?: string; clientSecret?: string; redirectUri?: string }>({});
let formSaving = $state(false);
function resetForm() {
formName = '';
formEnabled = false;
formIssuerUrl = '';
formClientId = '';
formClientSecret = '';
formRedirectUri = typeof window !== 'undefined' ? `${window.location.origin}/api/auth/oidc/callback` : '';
formScopes = 'openid profile email';
formUsernameClaim = 'preferred_username';
formEmailClaim = 'email';
formDisplayNameClaim = 'name';
formAdminClaim = '';
formAdminValue = '';
formRoleMappingsClaim = 'groups';
formRoleMappings = [];
formActiveTab = 'general';
formError = '';
formErrors = {};
formSaving = false;
}
// Initialize form when oidc changes or modal opens
$effect(() => {
if (open) {
if (oidc) {
formName = oidc.name;
formEnabled = oidc.enabled;
formIssuerUrl = oidc.issuerUrl;
formClientId = oidc.clientId;
formClientSecret = oidc.clientSecret;
formRedirectUri = oidc.redirectUri;
formScopes = oidc.scopes || 'openid profile email';
formUsernameClaim = oidc.usernameClaim || 'preferred_username';
formEmailClaim = oidc.emailClaim || 'email';
formDisplayNameClaim = oidc.displayNameClaim || 'name';
formAdminClaim = oidc.adminClaim || '';
formAdminValue = oidc.adminValue || '';
formRoleMappingsClaim = oidc.roleMappingsClaim || 'groups';
formRoleMappings = oidc.roleMappings ? oidc.roleMappings.map(m => ({ claim_value: m.claimValue, role_id: m.roleId })) : [];
formActiveTab = 'general';
formError = '';
formErrors = {};
formSaving = false;
} else {
resetForm();
}
}
});
async function save() {
formErrors = {};
let hasErrors = false;
if (!formName.trim()) {
formErrors.name = 'Name is required';
hasErrors = true;
}
if (!formIssuerUrl.trim()) {
formErrors.issuerUrl = 'Issuer URL is required';
hasErrors = true;
}
if (!formClientId.trim()) {
formErrors.clientId = 'Client ID is required';
hasErrors = true;
}
if (!isEditing && !formClientSecret.trim()) {
formErrors.clientSecret = 'Client secret is required';
hasErrors = true;
}
if (!formRedirectUri.trim()) {
formErrors.redirectUri = 'Redirect URI is required';
hasErrors = true;
}
if (hasErrors) return;
formSaving = true;
formError = '';
try {
const url = isEditing ? `/api/auth/oidc/${oidc!.id}` : '/api/auth/oidc';
const method = isEditing ? 'PUT' : 'POST';
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: formName.trim(),
enabled: formEnabled,
issuerUrl: formIssuerUrl.trim(),
clientId: formClientId.trim(),
clientSecret: formClientSecret.trim(),
redirectUri: formRedirectUri.trim(),
scopes: formScopes.trim() || 'openid profile email',
usernameClaim: formUsernameClaim.trim() || 'preferred_username',
emailClaim: formEmailClaim.trim() || 'email',
displayNameClaim: formDisplayNameClaim.trim() || 'name',
adminClaim: formAdminClaim.trim() || undefined,
adminValue: formAdminValue.trim() || undefined,
roleMappings: formRoleMappings.length > 0 ? formRoleMappings.map(m => ({ claimValue: m.claim_value, roleId: m.role_id })) : undefined
})
});
if (response.ok) {
open = false;
onSaved();
} else {
const data = await response.json();
formError = data.error || `Failed to ${isEditing ? 'update' : 'create'} OIDC configuration`;
}
} catch {
formError = `Failed to ${isEditing ? 'update' : 'create'} OIDC configuration`;
} finally {
formSaving = false;
}
}
function handleClose() {
open = false;
onClose();
}
function addRoleMapping() {
formRoleMappings = [...formRoleMappings, { claim_value: '', role_id: 0 }];
}
function removeRoleMapping(index: number) {
formRoleMappings = formRoleMappings.filter((_, i) => i !== index);
}
function updateRoleMappingRole(index: number, roleId: number) {
formRoleMappings[index].role_id = roleId;
formRoleMappings = [...formRoleMappings];
}
</script>
<Dialog.Root bind:open onOpenChange={(o) => { if (o) { formError = ''; formErrors = {}; focusFirstInput(); } }}>
<Dialog.Content class="max-w-2xl h-[80vh] flex flex-col overflow-hidden">
<Dialog.Header class="flex-shrink-0">
<Dialog.Title class="flex items-center gap-2">
{#if isEditing}
<Pencil class="w-5 h-5" />
Edit OIDC provider
{:else}
<LogIn class="w-5 h-5" />
Add OIDC provider
{/if}
</Dialog.Title>
</Dialog.Header>
<Tabs.Root bind:value={formActiveTab} class="flex-1 flex flex-col overflow-hidden">
<Tabs.List class="flex-shrink-0 grid w-full grid-cols-2">
<Tabs.Trigger value="general">General</Tabs.Trigger>
<Tabs.Trigger value="role-mapping" class="flex items-center gap-1.5">
<Crown class="w-3.5 h-3.5 text-amber-500" />
Role mapping
</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="general" class="flex-1 overflow-y-auto space-y-4 py-2 mt-0">
{#if formError}
<Alert.Root variant="destructive">
<TriangleAlert class="h-4 w-4" />
<Alert.Description>{formError}</Alert.Description>
</Alert.Root>
{/if}
<!-- Basic Settings -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Basic settings</h4>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Name <span class="text-destructive">*</span></Label>
<Input
bind:value={formName}
placeholder="Okta, Auth0, Azure AD..."
class={formErrors.name ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.name = undefined}
/>
{#if formErrors.name}
<p class="text-xs text-destructive">{formErrors.name}</p>
{/if}
</div>
<div class="space-y-2">
<Label>Issuer URL <span class="text-destructive">*</span></Label>
<Input
bind:value={formIssuerUrl}
placeholder="https://example.okta.com"
class={formErrors.issuerUrl ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.issuerUrl = undefined}
/>
{#if formErrors.issuerUrl}
<p class="text-xs text-destructive">{formErrors.issuerUrl}</p>
{/if}
</div>
</div>
<div class="flex items-center gap-2">
<Checkbox
checked={formEnabled}
onCheckedChange={(checked) => formEnabled = checked === true}
/>
<Label class="text-sm font-normal cursor-pointer" onclick={() => formEnabled = !formEnabled}>
Enable this OIDC provider
</Label>
</div>
</div>
<!-- Client Credentials -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Client credentials</h4>
<p class="text-xs text-muted-foreground">Get these from your identity provider's application settings.</p>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Client ID <span class="text-destructive">*</span></Label>
<Input
bind:value={formClientId}
placeholder="your-client-id"
class={formErrors.clientId ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.clientId = undefined}
/>
{#if formErrors.clientId}
<p class="text-xs text-destructive">{formErrors.clientId}</p>
{/if}
</div>
<div class="space-y-2">
<Label>Client secret {#if !isEditing}<span class="text-destructive">*</span>{/if}</Label>
<Input
type="password"
bind:value={formClientSecret}
placeholder={isEditing ? 'Leave blank to keep existing' : 'your-client-secret'}
class={formErrors.clientSecret ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.clientSecret = undefined}
/>
{#if formErrors.clientSecret}
<p class="text-xs text-destructive">{formErrors.clientSecret}</p>
{/if}
</div>
</div>
</div>
<!-- Redirect & Scopes -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Redirect settings</h4>
<div class="space-y-2">
<Label>Redirect URI <span class="text-destructive">*</span></Label>
<Input
bind:value={formRedirectUri}
placeholder="https://dockhand.example.com/api/auth/oidc/callback"
class={formErrors.redirectUri ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.redirectUri = undefined}
/>
{#if formErrors.redirectUri}
<p class="text-xs text-destructive">{formErrors.redirectUri}</p>
{:else}
<p class="text-xs text-muted-foreground">Add this URI to your identity provider's allowed callback URLs.</p>
{/if}
</div>
<div class="space-y-2">
<Label>Scopes</Label>
<Input
bind:value={formScopes}
placeholder="openid profile email"
/>
</div>
</div>
<!-- Claim Mapping -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Claim mapping</h4>
<p class="text-xs text-muted-foreground">Map OIDC claims to user attributes.</p>
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2">
<Label>Username claim</Label>
<Input
bind:value={formUsernameClaim}
placeholder="preferred_username"
/>
</div>
<div class="space-y-2">
<Label>Email claim</Label>
<Input
bind:value={formEmailClaim}
placeholder="email"
/>
</div>
<div class="space-y-2">
<Label>Display name claim</Label>
<Input
bind:value={formDisplayNameClaim}
placeholder="name"
/>
</div>
</div>
</div>
</Tabs.Content>
<Tabs.Content value="role-mapping" class="flex-1 overflow-y-auto space-y-4 py-2 mt-0">
{#if !isEnterprise}
<!-- Enterprise Feature Notice (no license) -->
<div class="flex-1 flex items-center justify-center py-8">
<div class="text-center">
<h3 class="text-lg font-medium mb-2 flex items-center justify-center gap-2">
<Crown class="w-5 h-5 text-amber-500" />
Enterprise feature
</h3>
<p class="text-sm text-muted-foreground mb-4 max-w-md mx-auto">
Role mapping allows you to automatically assign Dockhand roles based on your identity provider's groups or claims. This feature requires an enterprise license.
</p>
{#if onNavigateToLicense}
<Button onclick={() => { open = false; onNavigateToLicense?.(); }}>
<Key class="w-4 h-4 mr-2" />
Activate license
</Button>
{/if}
</div>
</div>
{:else}
<!-- Admin Mapping (Simple) -->
<div class="space-y-4">
<h4 class="text-sm font-medium text-muted-foreground">Groups/roles claim</h4>
<p class="text-xs text-muted-foreground">Grant admin access based on claim values from your identity provider.</p>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Claim name</Label>
<Input
bind:value={formAdminClaim}
placeholder="groups, roles, etc."
/>
<p class="text-xs text-muted-foreground">Name of the claim containing roles/groups</p>
</div>
<div class="space-y-2">
<Label>Admin value(s)</Label>
<Input
bind:value={formAdminValue}
placeholder="admin, Administrators"
/>
<p class="text-xs text-muted-foreground">Comma-separated values that grant Admin role</p>
</div>
</div>
</div>
<!-- Role Mappings Grid -->
<div class="space-y-4">
<div class="flex items-center justify-between">
<div>
<h4 class="text-sm font-medium text-muted-foreground">Claim to role mappings</h4>
<p class="text-xs text-muted-foreground mt-0.5">Map claim values from your identity provider to Dockhand roles.</p>
</div>
<Button
size="sm"
variant="outline"
onclick={addRoleMapping}
>
<Plus class="w-4 h-4 mr-1" />
Add mapping
</Button>
</div>
{#if formRoleMappings.length === 0}
<div class="text-center py-6 text-muted-foreground text-sm border border-dashed rounded-lg">
No role mappings configured. Click "Add mapping" to create one.
</div>
{:else}
<div class="space-y-2">
{#each formRoleMappings as mapping, index}
<div class="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
<div class="flex-1 grid grid-cols-2 gap-3">
<div class="space-y-1">
<Label class="text-xs">Claim value</Label>
<Input
bind:value={mapping.claim_value}
placeholder="e.g., developers, admins"
class="h-8"
/>
</div>
<div class="space-y-1">
<Label class="text-xs">Dockhand role</Label>
<Select.Root
type="single"
value={mapping.role_id ? String(mapping.role_id) : undefined}
onValueChange={(value) => {
if (value) {
updateRoleMappingRole(index, parseInt(value));
}
}}
>
<Select.Trigger class="h-8">
{#if mapping.role_id}
{roles.find(r => r.id === mapping.role_id)?.name || 'Select role...'}
{:else}
Select role...
{/if}
</Select.Trigger>
<Select.Content>
{#each roles as role}
<Select.Item value={String(role.id)}>
<div class="flex items-center gap-2">
<Shield class="w-3.5 h-3.5 text-muted-foreground" />
{role.name}
</div>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
</div>
<Button
size="sm"
variant="ghost"
class="text-destructive hover:text-destructive h-8 w-8 p-0"
onclick={() => removeRoleMapping(index)}
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
{/each}
</div>
{/if}
</div>
{/if}
</Tabs.Content>
</Tabs.Root>
<Dialog.Footer class="flex-shrink-0 border-t pt-4">
<Button variant="outline" onclick={handleClose}>Cancel</Button>
<Button onclick={save} disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
{:else}
<Plus class="w-4 h-4 mr-1" />
{/if}
{isEditing ? 'Save' : 'Add provider'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
@@ -0,0 +1,289 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Badge } from '$lib/components/ui/badge';
import {
LogIn,
Plus,
Pencil,
Trash2,
RefreshCw,
Check,
Pause,
Play,
Zap,
XCircle
} from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import OidcModal from './OidcModal.svelte';
import { EmptyState } from '$lib/components/ui/empty-state';
interface OidcConfig {
id: number;
name: string;
enabled: boolean;
issuerUrl: string;
clientId: string;
clientSecret: string;
redirectUri: string;
scopes: string;
usernameClaim: string;
emailClaim: string;
displayNameClaim: string;
adminClaim?: string;
adminValue?: string;
roleMappingsClaim?: string;
roleMappings?: { claimValue: string; roleId: number }[];
}
interface Role {
id: number;
name: string;
description?: string;
is_system: boolean;
permissions: any;
created_at: string;
}
interface Props {
roles: Role[];
}
let { roles }: Props = $props();
// OIDC/SSO state
let oidcConfigs = $state<OidcConfig[]>([]);
let oidcLoading = $state(true);
let showOidcModal = $state(false);
let editingOidc = $state<OidcConfig | null>(null);
let confirmDeleteOidcId = $state<number | null>(null);
let oidcTesting = $state<number | null>(null);
let oidcTestResult = $state<{ success: boolean; error?: string; issuer?: string; endpoints?: any } | null>(null);
async function fetchOidcConfigs() {
oidcLoading = true;
try {
const response = await fetch('/api/auth/oidc');
if (response.ok) {
oidcConfigs = await response.json();
}
} catch (error) {
console.error('Failed to fetch OIDC configs:', error);
toast.error('Failed to fetch OIDC configurations');
} finally {
oidcLoading = false;
}
}
function openOidcModal(config: OidcConfig | null) {
editingOidc = config;
showOidcModal = true;
}
function handleOidcModalClose() {
showOidcModal = false;
editingOidc = null;
}
async function handleOidcModalSaved() {
showOidcModal = false;
editingOidc = null;
await fetchOidcConfigs();
}
async function deleteOidcConfig(configId: number) {
try {
const response = await fetch(`/api/auth/oidc/${configId}`, { method: 'DELETE' });
if (response.ok) {
await fetchOidcConfigs();
toast.success('OIDC provider deleted');
} else {
toast.error('Failed to delete OIDC provider');
}
} catch (error) {
console.error('Failed to delete OIDC config:', error);
toast.error('Failed to delete OIDC provider');
} finally {
confirmDeleteOidcId = null;
}
}
async function testOidcConnection(configId: number) {
oidcTesting = configId;
oidcTestResult = null;
try {
const response = await fetch(`/api/auth/oidc/${configId}/test`, { method: 'POST' });
const data = await response.json();
oidcTestResult = data;
if (data.success) {
toast.success('OIDC connection successful');
} else {
toast.error(`OIDC connection failed: ${data.error}`);
}
} catch (error) {
oidcTestResult = { success: false, error: 'Failed to test connection' };
toast.error('Failed to test OIDC connection');
} finally {
oidcTesting = null;
}
}
async function toggleOidcEnabled(config: OidcConfig) {
try {
const response = await fetch(`/api/auth/oidc/${config.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...config, enabled: !config.enabled })
});
if (response.ok) {
await fetchOidcConfigs();
toast.success(`OIDC provider ${config.enabled ? 'disabled' : 'enabled'}`);
} else {
toast.error('Failed to toggle OIDC provider');
}
} catch (error) {
console.error('Failed to toggle OIDC config:', error);
toast.error('Failed to toggle OIDC provider');
}
}
onMount(() => {
fetchOidcConfigs();
});
</script>
<div class="space-y-4">
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<LogIn class="w-4 h-4" />
SSO providers
</Card.Title>
<p class="text-xs text-muted-foreground mt-1">Enable SSO using OpenID Connect providers like Okta, Auth0, Azure AD, or Google Workspace.</p>
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openOidcModal(null)}>
<Plus class="w-4 h-4 mr-1" />
Add provider
</Button>
{/if}
</div>
</Card.Header>
<Card.Content>
{#if oidcLoading}
<div class="flex items-center justify-center py-4">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
{:else if oidcConfigs.length === 0}
<EmptyState
icon={LogIn}
title="No SSO providers configured"
description="Add an OIDC provider to enable single sign-on"
class="py-8"
/>
{:else}
<div class="space-y-2">
{#each oidcConfigs as config}
<div class="flex items-center justify-between p-3 border rounded-md">
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<span class="font-medium text-sm">{config.name}</span>
{#if config.enabled}
<Badge variant="default" class="text-xs">Enabled</Badge>
{:else}
<Badge variant="outline" class="text-xs">Disabled</Badge>
{/if}
</div>
<span class="text-xs text-muted-foreground truncate block">{config.issuerUrl}</span>
</div>
<div class="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
title="Test connection"
onclick={() => testOidcConnection(config.id)}
disabled={oidcTesting === config.id}
>
{#if oidcTesting === config.id}
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Zap class="w-4 h-4" />
{/if}
</Button>
{#if $canAccess('settings', 'edit')}
<Button
variant="ghost"
size="sm"
title={config.enabled ? 'Disable provider' : 'Enable provider'}
onclick={() => toggleOidcEnabled(config)}
>
{#if config.enabled}
<Pause class="w-4 h-4" />
{:else}
<Play class="w-4 h-4" />
{/if}
</Button>
<Button
variant="ghost"
size="sm"
title="Edit provider"
onclick={() => openOidcModal(config)}
>
<Pencil class="w-4 h-4" />
</Button>
<ConfirmPopover
open={confirmDeleteOidcId === config.id}
action="Delete"
itemType="OIDC provider"
itemName={config.name}
title="Delete"
onConfirm={() => deleteOidcConfig(config.id)}
onOpenChange={(open) => confirmDeleteOidcId = open ? config.id : null}
>
{#snippet children({ open })}
<Trash2 class="w-4 h-4 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
{/snippet}
</ConfirmPopover>
{/if}
</div>
</div>
{/each}
</div>
{/if}
{#if oidcTestResult}
<div class="mt-4 p-3 border rounded-md {oidcTestResult.success ? 'border-green-500 bg-green-500/10' : 'border-destructive bg-destructive/10'}">
{#if oidcTestResult.success}
<div class="flex items-center gap-2 text-green-600">
<Check class="w-4 h-4" />
<p class="text-sm font-medium">Connection successful</p>
</div>
{#if oidcTestResult.issuer}
<p class="text-xs text-muted-foreground mt-1">Issuer: {oidcTestResult.issuer}</p>
{/if}
{:else}
<div class="flex items-center gap-2 text-destructive">
<XCircle class="w-4 h-4" />
<p class="text-sm">Connection failed: {oidcTestResult.error}</p>
</div>
{/if}
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
<OidcModal
bind:open={showOidcModal}
oidc={editingOidc}
{roles}
isEnterprise={$licenseStore.isEnterprise}
onClose={handleOidcModalClose}
onSaved={handleOidcModalSaved}
/>
@@ -0,0 +1,632 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/dialog';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import { Shield, Pencil, Plus, Check, RefreshCw, Box, Image, HardDrive, Cable, Layers, Globe, Download, Bell, Sliders, Settings, Users, Eye, SquarePlus, Play, Square, RotateCcw, Trash2, Terminal, ScrollText, Search, Upload, Plug, Unplug, Copy, GitBranch, KeyRound, Building2, Container, TriangleAlert, ClipboardList, Activity, Timer } from 'lucide-svelte';
import { getIconComponent } from '$lib/utils/icons';
import * as Alert from '$lib/components/ui/alert';
import { focusFirstInput } from '$lib/utils';
export interface Role {
id: number;
name: string;
description?: string;
is_system: boolean;
permissions: any;
environmentIds?: number[] | null;
created_at: string;
}
interface Environment {
id: number;
name: string;
icon?: string;
}
interface Props {
open: boolean;
role?: Role | null;
copyFrom?: Role | null;
environments?: Environment[];
onClose: () => void;
onSaved: () => void;
}
let { open = $bindable(), role = null, copyFrom = null, environments = [], onClose, onSaved }: Props = $props();
const isEditing = $derived(role !== null);
const isCopying = $derived(copyFrom !== null);
// Form state
let formName = $state('');
let formDescription = $state('');
let formError = $state('');
let formErrors = $state<{ name?: string }>({});
let formSaving = $state(false);
let formAllEnvironments = $state(false); // true = applies to all envs, false = specific envs
let formEnvironmentIds = $state<number[]>([]); // selected env IDs when not all
let formPermissions = $state<{
containers: string[];
images: string[];
volumes: string[];
networks: string[];
stacks: string[];
environments: string[];
registries: string[];
notifications: string[];
configsets: string[];
settings: string[];
users: string[];
git: string[];
license: string[];
audit_logs: string[];
activity: string[];
schedules: string[];
}>({
containers: [],
images: [],
volumes: [],
networks: [],
stacks: [],
environments: [],
registries: [],
notifications: [],
configsets: [],
settings: [],
users: [],
git: [],
license: [],
audit_logs: [],
activity: [],
schedules: []
});
// Permission definitions - separated into system and environment categories
const systemPermissions = {
users: [
{ key: 'view', label: 'View users' },
{ key: 'create', label: 'Create users' },
{ key: 'edit', label: 'Edit users' },
{ key: 'delete', label: 'Delete users' }
],
settings: [
{ key: 'view', label: 'View settings' },
{ key: 'edit', label: 'Edit settings' }
],
environments: [
{ key: 'view', label: 'View environments' },
{ key: 'create', label: 'Create environments' },
{ key: 'edit', label: 'Edit environments' },
{ key: 'delete', label: 'Delete environments' }
],
registries: [
{ key: 'view', label: 'View registries' },
{ key: 'create', label: 'Create registries' },
{ key: 'edit', label: 'Edit registries' },
{ key: 'delete', label: 'Delete registries' }
],
notifications: [
{ key: 'view', label: 'View notifications' },
{ key: 'create', label: 'Create notifications' },
{ key: 'edit', label: 'Edit notifications' },
{ key: 'delete', label: 'Delete notifications' },
{ key: 'test', label: 'Test notifications' }
],
configsets: [
{ key: 'view', label: 'View config sets' },
{ key: 'create', label: 'Create config sets' },
{ key: 'edit', label: 'Edit config sets' },
{ key: 'delete', label: 'Delete config sets' }
],
git: [
{ key: 'view', label: 'View credentials & repos' },
{ key: 'create', label: 'Create credentials & repos' },
{ key: 'edit', label: 'Edit credentials & repos' },
{ key: 'delete', label: 'Delete credentials & repos' }
],
license: [
{ key: 'manage', label: 'Manage license' }
],
audit_logs: [
{ key: 'view', label: 'View audit logs' }
],
schedules: [
{ key: 'view', label: 'View schedules' }
]
};
const environmentPermissions = {
activity: [
{ key: 'view', label: 'View activity' }
],
containers: [
{ key: 'view', label: 'View containers' },
{ key: 'create', label: 'Create containers' },
{ key: 'start', label: 'Start containers' },
{ key: 'stop', label: 'Stop containers' },
{ key: 'restart', label: 'Restart containers' },
{ key: 'remove', label: 'Remove containers' },
{ key: 'exec', label: 'Execute terminal' },
{ key: 'logs', label: 'View logs' },
{ key: 'inspect', label: 'Inspect containers' }
],
images: [
{ key: 'view', label: 'View images' },
{ key: 'pull', label: 'Pull images' },
{ key: 'push', label: 'Push images' },
{ key: 'remove', label: 'Remove images' },
{ key: 'build', label: 'Build images' },
{ key: 'inspect', label: 'Inspect images' }
],
volumes: [
{ key: 'view', label: 'View volumes' },
{ key: 'create', label: 'Create volumes' },
{ key: 'remove', label: 'Remove volumes' },
{ key: 'inspect', label: 'Inspect volumes' }
],
networks: [
{ key: 'view', label: 'View networks' },
{ key: 'create', label: 'Create networks' },
{ key: 'remove', label: 'Remove networks' },
{ key: 'inspect', label: 'Inspect networks' },
{ key: 'connect', label: 'Connect containers' },
{ key: 'disconnect', label: 'Disconnect containers' }
],
stacks: [
{ key: 'view', label: 'View stacks' },
{ key: 'create', label: 'Create stacks' },
{ key: 'start', label: 'Start stacks' },
{ key: 'stop', label: 'Stop stacks' },
{ key: 'remove', label: 'Remove stacks' },
{ key: 'edit', label: 'Edit stacks' }
]
};
const categoryIcons: Record<string, typeof Box> = {
containers: Container,
images: Image,
volumes: HardDrive,
networks: Cable,
stacks: Layers,
environments: Globe,
registries: Download,
notifications: Bell,
configsets: Sliders,
settings: Settings,
users: Users,
git: GitBranch,
license: KeyRound,
audit_logs: ClipboardList,
activity: Activity,
schedules: Timer
};
const categoryColorsSolid: Record<string, string> = {
containers: 'bg-blue-100 dark:bg-blue-950 text-blue-700 dark:text-blue-400 border-blue-300 dark:border-blue-800',
images: 'bg-purple-100 dark:bg-purple-950 text-purple-700 dark:text-purple-400 border-purple-300 dark:border-purple-800',
volumes: 'bg-amber-100 dark:bg-amber-950 text-amber-700 dark:text-amber-400 border-amber-300 dark:border-amber-800',
networks: 'bg-green-100 dark:bg-green-950 text-green-700 dark:text-green-400 border-green-300 dark:border-green-800',
stacks: 'bg-cyan-100 dark:bg-cyan-950 text-cyan-700 dark:text-cyan-400 border-cyan-300 dark:border-cyan-800',
environments: 'bg-indigo-100 dark:bg-indigo-950 text-indigo-700 dark:text-indigo-400 border-indigo-300 dark:border-indigo-800',
registries: 'bg-pink-100 dark:bg-pink-950 text-pink-700 dark:text-pink-400 border-pink-300 dark:border-pink-800',
notifications: 'bg-orange-100 dark:bg-orange-950 text-orange-700 dark:text-orange-400 border-orange-300 dark:border-orange-800',
configsets: 'bg-teal-100 dark:bg-teal-950 text-teal-700 dark:text-teal-400 border-teal-300 dark:border-teal-800',
settings: 'bg-slate-100 dark:bg-slate-900 text-slate-700 dark:text-slate-400 border-slate-300 dark:border-slate-700',
users: 'bg-rose-100 dark:bg-rose-950 text-rose-700 dark:text-rose-400 border-rose-300 dark:border-rose-800',
git: 'bg-violet-100 dark:bg-violet-950 text-violet-700 dark:text-violet-400 border-violet-300 dark:border-violet-800',
license: 'bg-yellow-100 dark:bg-yellow-950 text-yellow-700 dark:text-yellow-400 border-yellow-300 dark:border-yellow-800',
audit_logs: 'bg-stone-100 dark:bg-stone-950 text-stone-700 dark:text-stone-400 border-stone-300 dark:border-stone-800',
activity: 'bg-emerald-100 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-400 border-emerald-300 dark:border-emerald-800',
schedules: 'bg-sky-100 dark:bg-sky-950 text-sky-700 dark:text-sky-400 border-sky-300 dark:border-sky-800'
};
const permissionIcons: Record<string, typeof Eye> = {
view: Eye,
create: SquarePlus,
start: Play,
stop: Square,
restart: RotateCcw,
remove: Trash2,
delete: Trash2,
exec: Terminal,
logs: ScrollText,
inspect: Search,
pull: Download,
push: Upload,
build: Box,
connect: Plug,
disconnect: Unplug,
edit: Pencil,
test: Play,
manage: Settings
};
function resetForm() {
formName = '';
formDescription = '';
formError = '';
formErrors = {};
formSaving = false;
formAllEnvironments = false;
formEnvironmentIds = [];
formPermissions = {
containers: [],
images: [],
volumes: [],
networks: [],
stacks: [],
environments: [],
registries: [],
notifications: [],
configsets: [],
settings: [],
users: [],
git: [],
license: [],
audit_logs: [],
activity: [],
schedules: []
};
}
// Initialize form when role changes or modal opens
$effect(() => {
if (open) {
if (role) {
// Editing existing role
formName = role.name;
formDescription = role.description || '';
// Environment scope: null = all environments
formAllEnvironments = role.environmentIds === null || role.environmentIds === undefined;
formEnvironmentIds = role.environmentIds ? [...role.environmentIds] : [];
formPermissions = {
containers: [...(role.permissions.containers || [])],
images: [...(role.permissions.images || [])],
volumes: [...(role.permissions.volumes || [])],
networks: [...(role.permissions.networks || [])],
stacks: [...(role.permissions.stacks || [])],
environments: [...(role.permissions.environments || [])],
registries: [...(role.permissions.registries || [])],
notifications: [...(role.permissions.notifications || [])],
configsets: [...(role.permissions.configsets || [])],
settings: [...(role.permissions.settings || [])],
users: [...(role.permissions.users || [])],
git: [...(role.permissions.git || [])],
license: [...(role.permissions.license || [])],
audit_logs: [...(role.permissions.audit_logs || [])],
activity: [...(role.permissions.activity || [])],
schedules: [...(role.permissions.schedules || [])]
};
formError = '';
formErrors = {};
formSaving = false;
} else if (copyFrom) {
// Copying from existing role - new role with pre-filled permissions
formName = `${copyFrom.name} (copy)`;
formDescription = copyFrom.description || '';
// Copy environment scope from source role
formAllEnvironments = copyFrom.environmentIds === null || copyFrom.environmentIds === undefined;
formEnvironmentIds = copyFrom.environmentIds ? [...copyFrom.environmentIds] : [];
formPermissions = {
containers: [...(copyFrom.permissions.containers || [])],
images: [...(copyFrom.permissions.images || [])],
volumes: [...(copyFrom.permissions.volumes || [])],
networks: [...(copyFrom.permissions.networks || [])],
stacks: [...(copyFrom.permissions.stacks || [])],
environments: [...(copyFrom.permissions.environments || [])],
registries: [...(copyFrom.permissions.registries || [])],
notifications: [...(copyFrom.permissions.notifications || [])],
configsets: [...(copyFrom.permissions.configsets || [])],
settings: [...(copyFrom.permissions.settings || [])],
users: [...(copyFrom.permissions.users || [])],
git: [...(copyFrom.permissions.git || [])],
license: [...(copyFrom.permissions.license || [])],
audit_logs: [...(copyFrom.permissions.audit_logs || [])],
activity: [...(copyFrom.permissions.activity || [])],
schedules: [...(copyFrom.permissions.schedules || [])]
};
formError = '';
formErrors = {};
formSaving = false;
} else {
resetForm();
}
}
});
function togglePermission(category: keyof typeof formPermissions, permission: string) {
const current = formPermissions[category];
if (current.includes(permission)) {
formPermissions[category] = current.filter(p => p !== permission);
} else {
formPermissions[category] = [...current, permission];
}
}
function toggleAllPermissions(category: keyof typeof formPermissions, enable: boolean, definitions: { key: string; label: string }[]) {
if (enable) {
formPermissions[category] = definitions.map(p => p.key);
} else {
formPermissions[category] = [];
}
}
function toggleEnvironment(envId: number) {
if (formEnvironmentIds.includes(envId)) {
formEnvironmentIds = formEnvironmentIds.filter(id => id !== envId);
} else {
formEnvironmentIds = [...formEnvironmentIds, envId];
}
}
async function save() {
formErrors = {};
if (!formName.trim()) {
formErrors.name = 'Role name is required';
return;
}
formSaving = true;
formError = '';
try {
const url = isEditing ? `/api/roles/${role!.id}` : '/api/roles';
const method = isEditing ? 'PUT' : 'POST';
// null = all environments, array = specific environments
const environmentIds = formAllEnvironments ? null : formEnvironmentIds;
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: formName.trim(),
description: formDescription.trim() || (isEditing ? null : undefined),
permissions: formPermissions,
environmentIds
})
});
if (response.ok) {
open = false;
onSaved();
} else {
const data = await response.json();
if (data.error?.includes('already exists')) {
formErrors.name = 'Role name already exists';
} else {
formError = data.error || `Failed to ${isEditing ? 'update' : 'create'} role`;
}
}
} catch {
formError = `Failed to ${isEditing ? 'update' : 'create'} role`;
} finally {
formSaving = false;
}
}
function handleClose() {
open = false;
onClose();
}
</script>
<Dialog.Root bind:open onOpenChange={(o) => { if (o) { formError = ''; formErrors = {}; focusFirstInput(); } }}>
<Dialog.Content class="max-w-6xl max-h-[85vh] flex flex-col overflow-hidden">
<Dialog.Header class="flex-shrink-0">
<Dialog.Title class="flex items-center gap-2">
{#if isEditing}
<Pencil class="w-5 h-5" />
Edit role
{:else if isCopying}
<Copy class="w-5 h-5" />
Copy role
{:else}
<Shield class="w-5 h-5" />
Create role
{/if}
</Dialog.Title>
<Dialog.Description>
{#if isEditing}
Update role permissions
{:else if isCopying}
Create a new role based on "{copyFrom?.name}"
{:else}
Define a new role with specific permissions
{/if}
</Dialog.Description>
</Dialog.Header>
{#if formError}
<Alert.Root variant="destructive" class="flex-shrink-0">
<TriangleAlert class="h-4 w-4" />
<Alert.Description>{formError}</Alert.Description>
</Alert.Root>
{/if}
<div class="flex-shrink-0 grid grid-cols-2 gap-4 py-4">
<div class="space-y-2">
<Label>Role name</Label>
<Input
bind:value={formName}
placeholder="Developer"
class={formErrors.name ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.name = undefined}
/>
{#if formErrors.name}
<p class="text-xs text-destructive">{formErrors.name}</p>
{/if}
</div>
<div class="space-y-2">
<Label>Description (optional)</Label>
<Input
bind:value={formDescription}
placeholder="Access to development resources"
/>
</div>
</div>
<!-- Vertically stacked permissions layout -->
<div class="flex-1 flex flex-col gap-4 min-h-0 overflow-y-auto pr-1">
<!-- System Permissions Section -->
<div class="flex-shrink-0 border rounded-lg">
<div class="px-4 py-3 border-b bg-muted/30">
<div class="flex items-center gap-2">
<Building2 class="w-4 h-4" />
<span class="font-medium text-sm">System permissions</span>
<span class="text-xs text-muted-foreground">(always global)</span>
</div>
</div>
<div class="p-3 grid grid-cols-2 lg:grid-cols-4 gap-3">
{#each Object.entries(systemPermissions) as [category, permissions]}
{@const IconComponent = categoryIcons[category]}
<div class="relative border rounded-md pt-5 pb-3 px-3">
<!-- Category pill on border -->
<div class="absolute -top-2.5 left-3 inline-flex items-center gap-1.5 px-2 py-0.5 rounded border {categoryColorsSolid[category] || 'bg-gray-100 dark:bg-gray-900 text-gray-700 dark:text-gray-400 border-gray-300 dark:border-gray-700'}">
<IconComponent class="w-3.5 h-3.5" />
<span class="text-xs font-medium capitalize">{category}</span>
</div>
<!-- Select all / Clear links -->
<div class="absolute -top-2 right-3 flex gap-2 bg-background px-1">
<button
type="button"
class="text-xs text-primary hover:underline"
onclick={() => toggleAllPermissions(category as keyof typeof formPermissions, true, permissions)}
>
All
</button>
<span class="text-muted-foreground">|</span>
<button
type="button"
class="text-xs text-muted-foreground hover:underline"
onclick={() => toggleAllPermissions(category as keyof typeof formPermissions, false, permissions)}
>
Clear
</button>
</div>
<div class="flex flex-col gap-1.5">
{#each permissions as permission}
{@const PermIcon = permissionIcons[permission.key]}
<label class="flex items-center gap-1.5 cursor-pointer">
<Checkbox
checked={formPermissions[category as keyof typeof formPermissions].includes(permission.key)}
onCheckedChange={() => togglePermission(category as keyof typeof formPermissions, permission.key)}
/>
{#if PermIcon}
<PermIcon class="w-3 h-3 text-muted-foreground" />
{/if}
<span class="text-xs truncate">{permission.label}</span>
</label>
{/each}
</div>
</div>
{/each}
</div>
</div>
<!-- Environment Permissions Section -->
<div class="flex-shrink-0 border rounded-lg">
<div class="px-4 py-3 border-b bg-muted/30">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<Globe class="w-4 h-4" />
<span class="font-medium text-sm">Environment permissions</span>
</div>
{#if environments.length > 0}
<div class="flex items-center gap-2">
<span class="text-xs text-muted-foreground">All environments (incl. new)</span>
<TogglePill bind:checked={formAllEnvironments} />
</div>
{/if}
</div>
<!-- Environment selector -->
{#if environments.length > 0}
{#if !formAllEnvironments}
<div class="mt-3 grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 gap-2">
{#each environments as env}
{@const EnvIcon = getIconComponent(env.icon || 'globe')}
<label class="flex items-center gap-2 p-2 border rounded-md cursor-pointer hover:bg-muted/50 transition-colors text-xs {formEnvironmentIds.includes(env.id) ? 'border-primary bg-primary/5' : ''}">
<Checkbox
checked={formEnvironmentIds.includes(env.id)}
onCheckedChange={() => toggleEnvironment(env.id)}
/>
<EnvIcon class="w-3.5 h-3.5 flex-shrink-0 text-muted-foreground" />
<span class="truncate">{env.name}</span>
</label>
{/each}
</div>
{#if formEnvironmentIds.length === 0}
<p class="text-xs text-amber-600 mt-2">Select at least one environment for these permissions to be effective.</p>
{/if}
{:else}
<p class="text-xs text-muted-foreground mt-1">Permissions apply to all environments, including future ones.</p>
{/if}
{:else}
<p class="text-xs text-muted-foreground mt-1">Permissions apply to all environments.</p>
{/if}
</div>
<div class="p-3 grid grid-cols-2 lg:grid-cols-5 gap-3">
{#each Object.entries(environmentPermissions) as [category, permissions]}
{@const IconComponent = categoryIcons[category]}
<div class="relative border rounded-md pt-5 pb-3 px-3">
<!-- Category pill on border -->
<div class="absolute -top-2.5 left-3 inline-flex items-center gap-1.5 px-2 py-0.5 rounded border {categoryColorsSolid[category] || 'bg-gray-100 dark:bg-gray-900 text-gray-700 dark:text-gray-400 border-gray-300 dark:border-gray-700'}">
<IconComponent class="w-3.5 h-3.5" />
<span class="text-xs font-medium capitalize">{category}</span>
</div>
<!-- Select all / Clear links -->
<div class="absolute -top-2 right-3 flex gap-2 bg-background px-1">
<button
type="button"
class="text-xs text-primary hover:underline"
onclick={() => toggleAllPermissions(category as keyof typeof formPermissions, true, permissions)}
>
All
</button>
<span class="text-muted-foreground">|</span>
<button
type="button"
class="text-xs text-muted-foreground hover:underline"
onclick={() => toggleAllPermissions(category as keyof typeof formPermissions, false, permissions)}
>
Clear
</button>
</div>
<div class="flex flex-col gap-1.5">
{#each permissions as permission}
{@const PermIcon = permissionIcons[permission.key]}
<label class="flex items-center gap-1.5 cursor-pointer">
<Checkbox
checked={formPermissions[category as keyof typeof formPermissions].includes(permission.key)}
onCheckedChange={() => togglePermission(category as keyof typeof formPermissions, permission.key)}
/>
{#if PermIcon}
<PermIcon class="w-3 h-3 text-muted-foreground" />
{/if}
<span class="text-xs truncate">{permission.label}</span>
</label>
{/each}
</div>
</div>
{/each}
</div>
</div>
</div>
<Dialog.Footer class="flex-shrink-0 pt-4">
<Button variant="outline" onclick={handleClose}>Cancel</Button>
<Button onclick={save} disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
{:else}
<Plus class="w-4 h-4 mr-1" />
{/if}
{isEditing ? 'Save' : 'Create role'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
@@ -0,0 +1,444 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Badge } from '$lib/components/ui/badge';
import {
Shield,
Plus,
Pencil,
Trash2,
RefreshCw,
Crown,
Key,
Box,
Image,
HardDrive,
Cable,
Layers,
Globe,
Download,
Bell,
Sliders,
Settings,
Users,
Eye,
SquarePlus,
Play,
Square,
RotateCcw,
Terminal,
ScrollText,
Search,
Upload,
Hammer,
Send,
Zap,
PlugZap,
Unplug,
Copy,
GitBranch,
KeyRound,
Container,
ClipboardList,
Timer
} from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import RoleModal from './RoleModal.svelte';
import { getIconComponent } from '$lib/utils/icons';
interface Role {
id: number;
name: string;
description?: string;
isSystem: boolean;
permissions: any;
environmentIds?: number[] | null;
createdAt: string;
}
interface Environment {
id: number;
name: string;
icon?: string;
}
interface Props {
onTabChange?: (tab: string) => void;
}
let { onTabChange = () => {} }: Props = $props();
// Roles state
let roles = $state<Role[]>([]);
let environments = $state<Environment[]>([]);
let rolesLoading = $state(true);
let showRoleModal = $state(false);
let editingRole = $state<Role | null>(null);
let copyingRole = $state<Role | null>(null);
let confirmDeleteRoleId = $state<number | null>(null);
// Permission definitions
const categoryIcons: Record<string, typeof Box> = {
containers: Box,
images: Image,
volumes: HardDrive,
networks: Cable,
stacks: Layers,
environments: Globe,
registries: Download,
notifications: Bell,
configsets: Sliders,
settings: Settings,
users: Users,
git: GitBranch,
license: KeyRound,
audit_logs: ClipboardList,
schedules: Timer
};
const categoryColors: Record<string, string> = {
containers: 'bg-blue-500/15 text-blue-700 dark:text-blue-400 border-blue-500/30',
images: 'bg-purple-500/15 text-purple-700 dark:text-purple-400 border-purple-500/30',
volumes: 'bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30',
networks: 'bg-green-500/15 text-green-700 dark:text-green-400 border-green-500/30',
stacks: 'bg-cyan-500/15 text-cyan-700 dark:text-cyan-400 border-cyan-500/30',
environments: 'bg-indigo-500/15 text-indigo-700 dark:text-indigo-400 border-indigo-500/30',
registries: 'bg-pink-500/15 text-pink-700 dark:text-pink-400 border-pink-500/30',
notifications: 'bg-orange-500/15 text-orange-700 dark:text-orange-400 border-orange-500/30',
configsets: 'bg-teal-500/15 text-teal-700 dark:text-teal-400 border-teal-500/30',
settings: 'bg-slate-500/15 text-slate-700 dark:text-slate-400 border-slate-500/30',
users: 'bg-rose-500/15 text-rose-700 dark:text-rose-400 border-rose-500/30',
git: 'bg-violet-500/15 text-violet-700 dark:text-violet-400 border-violet-500/30',
license: 'bg-yellow-500/15 text-yellow-700 dark:text-yellow-400 border-yellow-500/30',
audit_logs: 'bg-stone-500/15 text-stone-700 dark:text-stone-400 border-stone-500/30',
schedules: 'bg-sky-500/15 text-sky-700 dark:text-sky-400 border-sky-500/30'
};
const permissionIcons: Record<string, typeof Eye> = {
view: Eye,
create: SquarePlus,
start: Play,
stop: Square,
restart: RotateCcw,
remove: Trash2,
delete: Trash2,
exec: Terminal,
logs: ScrollText,
inspect: Search,
pull: Download,
push: Upload,
build: Hammer,
edit: Pencil,
manage: Settings,
send: Send,
test: Zap,
connect: PlugZap,
disconnect: Unplug,
activate: KeyRound
};
// Define which categories are system-wide vs environment-specific
const systemCategories = ['users', 'settings', 'environments', 'registries', 'notifications', 'configsets', 'git', 'license', 'audit_logs', 'schedules'];
const envCategories = ['containers', 'images', 'volumes', 'networks', 'stacks'];
function getRolePermissionPills(permissions: any): { system: Array<{ category: string; perms: string[] }>; env: Array<{ category: string; perms: string[] }> } {
if (!permissions || typeof permissions !== 'object') return { system: [], env: [] };
const all = Object.entries(permissions)
.filter(([_, perms]) => Array.isArray(perms) && perms.length > 0)
.map(([category, perms]) => ({ category, perms: perms as string[] }));
return {
system: all.filter(p => systemCategories.includes(p.category)),
env: all.filter(p => envCategories.includes(p.category))
};
}
async function fetchRoles() {
rolesLoading = true;
try {
const response = await fetch('/api/roles');
if (response.ok) {
roles = await response.json();
}
} catch (error) {
console.error('Failed to fetch roles:', error);
toast.error('Failed to fetch roles');
} finally {
rolesLoading = false;
}
}
async function fetchEnvironments() {
try {
const response = await fetch('/api/environments');
if (response.ok) {
environments = await response.json();
}
} catch (error) {
console.error('Failed to fetch environments:', error);
}
}
async function openRoleModal(role: Role | null) {
await fetchEnvironments(); // Re-fetch to get any newly added environments
editingRole = role;
copyingRole = null;
showRoleModal = true;
}
async function copyRole(role: Role) {
await fetchEnvironments(); // Re-fetch to get any newly added environments
editingRole = null;
copyingRole = role;
showRoleModal = true;
}
function handleRoleModalClose() {
showRoleModal = false;
editingRole = null;
copyingRole = null;
}
async function handleRoleModalSaved() {
showRoleModal = false;
editingRole = null;
copyingRole = null;
await fetchRoles();
}
async function deleteRole(roleId: number) {
try {
const response = await fetch(`/api/roles/${roleId}`, { method: 'DELETE' });
if (response.ok) {
await fetchRoles();
toast.success('Role deleted');
} else {
toast.error('Failed to delete role');
}
} catch (error) {
console.error('Failed to delete role:', error);
toast.error('Failed to delete role');
} finally {
confirmDeleteRoleId = null;
}
}
// Fetch data when license is confirmed as enterprise
let hasFetched = $state(false);
$effect(() => {
if ($licenseStore.isEnterprise && !$licenseStore.loading && !hasFetched) {
hasFetched = true;
fetchRoles();
fetchEnvironments();
}
});
</script>
{#if $licenseStore.loading}
<Card.Root>
<Card.Content class="py-12">
<div class="flex justify-center">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
</Card.Content>
</Card.Root>
{:else if !$licenseStore.isEnterprise}
<Card.Root>
<Card.Content class="py-12">
<div class="text-center">
<h3 class="text-lg font-medium mb-2 flex items-center justify-center gap-2">
<Crown class="w-5 h-5 text-amber-500" />
Enterprise feature
</h3>
<p class="text-sm text-muted-foreground mb-4 max-w-md mx-auto">
Role-based access control (RBAC) is available with an enterprise license. Define custom
roles with granular permissions and assign them to users.
</p>
<Button onclick={() => onTabChange('license')}>
<Key class="w-4 h-4 mr-2" />
Activate license
</Button>
</div>
</Card.Content>
</Card.Root>
{:else}
<div class="space-y-4">
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<Shield class="w-4 h-4" />
Roles
</Card.Title>
<p class="text-xs text-muted-foreground mt-1">
Define roles with granular permissions and assign them to users for access control.
</p>
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openRoleModal(null)}>
<Plus class="w-4 h-4 mr-1" />
Add role
</Button>
{/if}
</div>
</Card.Header>
<Card.Content>
{#if rolesLoading}
<div class="flex items-center justify-center py-4">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
{:else if roles.length === 0}
<div class="text-center py-8 text-sm text-muted-foreground">
<Shield class="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No roles configured</p>
<p class="text-xs">Create a role to define custom permissions</p>
</div>
{:else}
<div class="space-y-2 max-h-96 overflow-y-auto">
{#each roles as role}
{@const pills = getRolePermissionPills(role.permissions)}
<div class="flex items-center justify-between p-3 border rounded-md gap-4">
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-1">
<span class="font-medium text-sm">{role.name}</span>
{#if role.isSystem}
<Badge variant="outline" class="text-xs">System</Badge>
{/if}
</div>
{#if role.description}
<p class="text-xs text-muted-foreground mb-2">{role.description}</p>
{/if}
<!-- Permission Pills - System -->
{#if pills.system.length > 0}
<div class="flex flex-wrap items-center gap-1 mb-1">
<span class="text-2xs text-muted-foreground font-medium uppercase tracking-wide mr-1">System:</span>
{#each pills.system as { category, perms }}
{@const CategoryIcon = categoryIcons[category]}
<span
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border {categoryColors[
category
] || 'bg-gray-500/15 text-gray-700 dark:text-gray-400 border-gray-500/30'}"
>
{#if CategoryIcon}
<svelte:component this={CategoryIcon} class="w-3 h-3" />
{/if}
<span class="capitalize">{category}</span>
<span class="inline-flex items-center gap-0.5 opacity-70">
{#each perms as perm}
{@const PermIcon = permissionIcons[perm]}
{#if PermIcon}
<span title={perm}>
<svelte:component this={PermIcon} class="w-2.5 h-2.5" />
</span>
{/if}
{/each}
</span>
</span>
{/each}
</div>
{/if}
<!-- Permission Pills - Environment -->
{#if pills.env.length > 0}
<div class="flex flex-wrap items-center gap-1">
<span class="text-2xs text-muted-foreground font-medium uppercase tracking-wide mr-1">Env</span>
{#if role.environmentIds === null || role.environmentIds === undefined}
<Badge variant="secondary" class="text-2xs gap-0.5 px-1 py-0 h-4">
<Globe class="w-2.5 h-2.5" />
All
</Badge>
{:else if role.environmentIds.length > 0}
{@const envs = role.environmentIds
.map(id => environments.find(e => e.id === id))
.filter(Boolean)}
{#each envs as env}
{@const EnvIcon = getIconComponent(env.icon || 'globe')}
<span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border bg-indigo-500/15 text-indigo-700 dark:text-indigo-400 border-indigo-500/30">
<EnvIcon class="w-3 h-3" />
{env.name}
</span>
{/each}
{/if}
<span class="text-2xs text-muted-foreground mx-0.5">:</span>
{#each pills.env as { category, perms }}
{@const CategoryIcon = categoryIcons[category]}
<span
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border {categoryColors[
category
] || 'bg-gray-500/15 text-gray-700 dark:text-gray-400 border-gray-500/30'}"
>
{#if CategoryIcon}
<svelte:component this={CategoryIcon} class="w-3 h-3" />
{/if}
<span class="capitalize">{category}</span>
<span class="inline-flex items-center gap-0.5 opacity-70">
{#each perms as perm}
{@const PermIcon = permissionIcons[perm]}
{#if PermIcon}
<span title={perm}>
<svelte:component this={PermIcon} class="w-2.5 h-2.5" />
</span>
{/if}
{/each}
</span>
</span>
{/each}
</div>
{/if}
</div>
{#if $canAccess('settings', 'edit')}
<div class="flex items-center gap-1 flex-shrink-0">
{#if role.isSystem}
<!-- System roles: only Copy button -->
<Button variant="ghost" size="sm" onclick={() => copyRole(role)} title="Copy as new role">
<Copy class="w-4 h-4" />
</Button>
{:else}
<!-- Custom roles: Copy, Edit and Delete -->
<Button variant="ghost" size="sm" onclick={() => copyRole(role)} title="Copy as new role">
<Copy class="w-4 h-4" />
</Button>
<Button variant="ghost" size="sm" onclick={() => openRoleModal(role)} title="Edit role">
<Pencil class="w-4 h-4" />
</Button>
<ConfirmPopover
open={confirmDeleteRoleId === role.id}
action="Delete"
itemType="role"
itemName={role.name}
title="Delete"
onConfirm={() => deleteRole(role.id)}
onOpenChange={(open) => (confirmDeleteRoleId = open ? role.id : null)}
>
{#snippet children({ open })}
<Trash2
class="w-4 h-4 {open
? 'text-destructive'
: 'text-muted-foreground hover:text-destructive'}"
/>
{/snippet}
</ConfirmPopover>
{/if}
</div>
{/if}
</div>
{/each}
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
{/if}
<RoleModal
bind:open={showRoleModal}
role={editingRole}
copyFrom={copyingRole}
{environments}
onClose={handleRoleModalClose}
onSaved={handleRoleModalSaved}
/>
@@ -0,0 +1,598 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/dialog';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import { Badge } from '$lib/components/ui/badge';
import { User, UserPlus, Pencil, KeyRound, Crown, ShieldCheck, RefreshCw, Check, Globe, TriangleAlert, Shield, Eye, Wrench, Tag, Smartphone } from 'lucide-svelte';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import * as Alert from '$lib/components/ui/alert';
import { focusFirstInput } from '$lib/utils';
import PasswordStrengthIndicator from '$lib/components/PasswordStrengthIndicator.svelte';
export interface LocalUser {
id: number;
username: string;
email?: string;
displayName?: string;
mfaEnabled: boolean;
isAdmin: boolean;
isActive: boolean;
isSso: boolean;
lastLogin?: string;
createdAt: string;
}
export interface Role {
id: number;
name: string;
description?: string;
isSystem: boolean;
permissions: any;
environmentIds?: number[] | null; // null = all environments, array = specific envs
createdAt: string;
}
// Simple role assignment - just the role ID (env scope is on the role itself)
interface RoleAssignment {
roleId: number;
}
interface Props {
open: boolean;
user?: LocalUser | null;
roles: Role[];
isEnterprise?: boolean;
onClose: () => void;
onSaved: () => void;
}
let {
open = $bindable(),
user = null,
roles = [],
isEnterprise = false,
onClose,
onSaved
}: Props = $props();
const isEditing = $derived(user !== null);
// Form state
let formUsername = $state('');
let formEmail = $state('');
let formDisplayName = $state('');
let formPassword = $state('');
let formPasswordRepeat = $state('');
let formRoleAssignments = $state<RoleAssignment[]>([]);
let formError = $state('');
let formErrors = $state<{ username?: string; password?: string; passwordRepeat?: string }>({});
let formSaving = $state(false);
let mfaDisabling = $state(false);
function resetForm() {
formUsername = '';
formEmail = '';
formDisplayName = '';
formPassword = '';
formPasswordRepeat = '';
formRoleAssignments = [];
formError = '';
formErrors = {};
formSaving = false;
mfaDisabling = false;
}
async function handleMfaToggle() {
if (!user || !user.mfaEnabled) return;
mfaDisabling = true;
try {
const response = await fetch(`/api/users/${user.id}/mfa`, {
method: 'DELETE'
});
if (response.ok) {
toast.success('MFA disabled for user');
user.mfaEnabled = false;
} else {
const data = await response.json();
toast.error(data.error || 'Failed to disable MFA');
}
} catch {
toast.error('Failed to disable MFA');
} finally {
mfaDisabling = false;
}
}
// Initialize form when user changes or modal opens
$effect(() => {
if (open) {
if (user) {
formUsername = user.username;
formEmail = user.email || '';
formDisplayName = user.displayName || '';
formPassword = '';
formPasswordRepeat = '';
formRoleAssignments = [];
formError = '';
formErrors = {};
formSaving = false;
// Fetch user's current roles
fetchUserRoles(user.id);
} else {
resetForm();
}
}
});
async function fetchUserRoles(userId: number) {
try {
const response = await fetch(`/api/users/${userId}/roles`);
if (response.ok) {
const userRoles = await response.json();
// Get unique role IDs (user just has roles assigned, env scope is on role)
const uniqueRoleIds = [...new Set(userRoles.map((ur: any) => ur.roleId))];
formRoleAssignments = uniqueRoleIds.map(roleId => ({ roleId: roleId as number }));
}
} catch (error) {
console.error('Failed to fetch user roles:', error);
toast.error('Failed to fetch user roles');
}
}
async function syncUserRoles(userId: number) {
try {
// Get current assignments from server
const currentResponse = await fetch(`/api/users/${userId}/roles`);
if (!currentResponse.ok) return;
const currentRoles = await currentResponse.json();
const currentRoleIds = [...new Set(currentRoles.map((c: any) => c.roleId))];
const targetRoleIds = formRoleAssignments.map(a => a.roleId);
// Remove roles that are no longer assigned
for (const roleId of currentRoleIds) {
if (!targetRoleIds.includes(roleId as number)) {
await fetch(`/api/users/${userId}/roles`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ roleId })
});
}
}
// Add new role assignments
for (const roleId of targetRoleIds) {
if (!currentRoleIds.includes(roleId)) {
await fetch(`/api/users/${userId}/roles`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ roleId })
});
}
}
} catch (error) {
console.error('Failed to sync user roles:', error);
toast.error('Failed to sync user roles');
}
}
function toggleRole(roleId: number, checked: boolean, _isSystem: boolean) {
if (checked) {
formRoleAssignments = [...formRoleAssignments, { roleId }];
} else {
formRoleAssignments = formRoleAssignments.filter(a => a.roleId !== roleId);
}
}
async function createUser() {
formErrors = {};
let hasErrors = false;
if (!formUsername.trim()) {
formErrors.username = 'Username is required';
hasErrors = true;
}
if (!formPassword.trim()) {
formErrors.password = 'Password is required';
hasErrors = true;
}
if (formPassword !== formPasswordRepeat) {
formErrors.passwordRepeat = 'Passwords do not match';
hasErrors = true;
}
if (hasErrors) return;
formSaving = true;
formError = '';
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: formUsername.trim(),
email: formEmail.trim() || undefined,
displayName: formDisplayName.trim() || undefined,
password: formPassword
})
});
if (response.ok) {
const data = await response.json();
// Sync roles for the new user (Enterprise mode)
if (data.id && isEnterprise) {
await syncUserRoles(data.id);
}
open = false;
onSaved();
toast.success('User created');
} else {
const data = await response.json();
formError = data.error || 'Failed to create user';
toast.error(formError);
}
} catch {
formError = 'Failed to create user';
toast.error('Failed to create user');
} finally {
formSaving = false;
}
}
async function updateUser() {
formErrors = {};
let hasErrors = false;
if (!user || !formUsername.trim()) {
formErrors.username = 'Username is required';
hasErrors = true;
}
if (formPassword.trim() && formPassword !== formPasswordRepeat) {
formErrors.passwordRepeat = 'Passwords do not match';
hasErrors = true;
}
if (hasErrors) return;
formSaving = true;
formError = '';
try {
const body: any = {
username: formUsername.trim(),
email: formEmail.trim() || null,
displayName: formDisplayName.trim() || null
};
if (formPassword.trim()) {
body.password = formPassword;
}
const response = await fetch(`/api/users/${user!.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (response.ok) {
await syncUserRoles(user!.id);
open = false;
onSaved();
toast.success('User updated');
} else {
const data = await response.json();
formError = data.error || 'Failed to update user';
toast.error(formError);
}
} catch {
formError = 'Failed to update user';
toast.error('Failed to update user');
} finally {
formSaving = false;
}
}
function handleClose() {
open = false;
onClose();
}
// Get icon component for a role based on its name
function getRoleIcon(roleName: string): typeof Crown {
const name = roleName.toLowerCase();
if (name.includes('admin')) return Crown;
if (name.includes('operator')) return Wrench;
if (name.includes('viewer') || name.includes('view') || name.includes('read')) return Eye;
return Tag;
}
function handleSubmit(e: Event) {
e.preventDefault();
if (isEditing) {
updateUser();
} else {
createUser();
}
}
</script>
<Dialog.Root bind:open onOpenChange={(o) => { if (o) { formError = ''; formErrors = {}; focusFirstInput(); } }}>
<Dialog.Content class="max-w-2xl">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
{#if isEditing}
<Pencil class="w-5 h-5" />
Edit user
{:else}
<UserPlus class="w-5 h-5" />
Add user
{/if}
</Dialog.Title>
</Dialog.Header>
<form onsubmit={handleSubmit}>
<div class="space-y-5">
{#if formError}
<Alert.Root variant="destructive">
<TriangleAlert class="h-4 w-4" />
<Alert.Description>{formError}</Alert.Description>
</Alert.Root>
{/if}
{#if user?.isSso}
<div class="flex items-center gap-2 px-3 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
<ShieldCheck class="w-4 h-4 text-yellow-600 flex-shrink-0" />
<p class="text-sm text-yellow-700 dark:text-yellow-500">
SSO user - profile synced from identity provider
</p>
</div>
{/if}
<!-- User Details Section -->
<div class="space-y-4">
<h3 class="text-sm font-medium flex items-center gap-2 text-muted-foreground">
<User class="w-4 h-4" />
User details
</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label>Username {#if !isEditing}<span class="text-destructive">*</span>{/if}</Label>
<Input
bind:value={formUsername}
placeholder={isEditing ? 'admin' : 'johndoe'}
autocomplete="off"
disabled={user?.isSso}
class="{user?.isSso ? 'opacity-60' : ''} {formErrors.username ? 'border-destructive focus-visible:ring-destructive' : ''}"
oninput={() => formErrors.username = undefined}
/>
{#if formErrors.username}
<p class="text-xs text-destructive">{formErrors.username}</p>
{/if}
</div>
<div class="space-y-2">
<Label>Email</Label>
<Input
type="email"
bind:value={formEmail}
placeholder={isEditing ? 'admin@example.com' : 'john@example.com'}
disabled={user?.isSso}
class={user?.isSso ? 'opacity-60' : ''}
/>
</div>
</div>
<div class="space-y-2">
<Label>Display name</Label>
<Input
bind:value={formDisplayName}
placeholder={isEditing ? 'Administrator' : 'John Doe'}
disabled={user?.isSso}
class={user?.isSso ? 'opacity-60' : ''}
/>
</div>
</div>
<!-- Password Section -->
{#if !user?.isSso}
<div class="space-y-4">
<h3 class="text-sm font-medium flex items-center gap-2 text-muted-foreground">
<KeyRound class="w-4 h-4" />
Password
</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
{#if isEditing}
<Label>New password <span class="text-muted-foreground text-xs">(leave blank to keep current)</span></Label>
{:else}
<Label>Password <span class="text-destructive">*</span></Label>
{/if}
<Input
type="password"
bind:value={formPassword}
placeholder={isEditing ? 'Enter new password' : 'Enter password'}
autocomplete="new-password"
class={formErrors.password ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.password = undefined}
/>
<PasswordStrengthIndicator password={formPassword} />
{#if formErrors.password}
<p class="text-xs text-destructive">{formErrors.password}</p>
{/if}
</div>
<div class="space-y-2">
{#if isEditing}
<Label>Confirm password</Label>
{:else}
<Label>Confirm password <span class="text-destructive">*</span></Label>
{/if}
<Input
type="password"
bind:value={formPasswordRepeat}
placeholder={isEditing ? 'Repeat new password' : 'Repeat password'}
autocomplete="new-password"
class={formErrors.passwordRepeat ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => formErrors.passwordRepeat = undefined}
/>
{#if formErrors.passwordRepeat}
<p class="text-xs text-destructive">{formErrors.passwordRepeat}</p>
{/if}
</div>
</div>
</div>
{/if}
<!-- MFA Section (Enterprise only, editing existing user with MFA enabled) -->
{#if isEnterprise && isEditing && user && !user.isSso}
<div class="space-y-3">
<h3 class="text-sm font-medium flex items-center gap-2 text-muted-foreground">
<Smartphone class="w-4 h-4" />
Two-factor authentication
</h3>
<div class="flex items-center justify-between p-3 border rounded-lg">
<div>
<p class="text-sm font-medium">MFA status</p>
<p class="text-xs text-muted-foreground">
{#if user.mfaEnabled}
User has MFA configured
{:else}
User has not configured MFA
{/if}
</p>
</div>
<TogglePill
checked={user.mfaEnabled}
disabled={!user.mfaEnabled || mfaDisabling}
onchange={handleMfaToggle}
/>
</div>
</div>
{/if}
<!-- Role Assignment Section -->
{#if isEnterprise}
{@const systemRoles = roles.filter(r => r.isSystem)}
{@const customRoles = roles.filter(r => !r.isSystem)}
<div class="space-y-3">
<div>
<Label class="text-sm">Roles</Label>
<p class="text-xs text-muted-foreground">Assign roles to this user. Environment scope is configured on the role itself.</p>
</div>
<div class="border rounded-lg divide-y max-h-[240px] overflow-y-auto">
<!-- System Roles -->
{#if systemRoles.length > 0}
<div class="p-3 bg-muted/30">
<p class="text-xs font-medium text-muted-foreground mb-2 flex items-center gap-1.5">
<Shield class="w-3.5 h-3.5" />
System roles
</p>
<div class="grid grid-cols-3 gap-2">
{#each systemRoles as role}
{@const isAssigned = formRoleAssignments.some(a => a.roleId === role.id)}
{@const RoleIcon = getRoleIcon(role.name)}
<button
type="button"
class="flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-all {isAssigned ? 'bg-primary text-primary-foreground border-primary shadow-sm' : 'bg-background hover:bg-muted border-border'}"
onclick={() => toggleRole(role.id, !isAssigned, role.isSystem)}
>
{#if isAssigned}
<Check class="w-4 h-4 flex-shrink-0" />
{:else}
<RoleIcon class="w-4 h-4 flex-shrink-0 opacity-50" />
{/if}
<span class="truncate">{role.name}</span>
</button>
{/each}
</div>
</div>
{/if}
<!-- Custom Roles -->
{#if customRoles.length > 0}
<div class="p-3">
<p class="text-xs font-medium text-muted-foreground mb-2 flex items-center gap-1.5">
<Globe class="w-3.5 h-3.5" />
Custom roles
</p>
<div class="grid grid-cols-2 gap-2">
{#each customRoles as role}
{@const isAssigned = formRoleAssignments.some(a => a.roleId === role.id)}
{@const envCount = role.environmentIds?.length ?? 0}
{@const isGlobal = role.environmentIds === null}
{@const RoleIcon = getRoleIcon(role.name)}
<button
type="button"
class="flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-all text-left {isAssigned ? 'bg-primary text-primary-foreground border-primary shadow-sm' : 'bg-background hover:bg-muted border-border'}"
onclick={() => toggleRole(role.id, !isAssigned, role.isSystem)}
>
{#if isAssigned}
<Check class="w-4 h-4 flex-shrink-0" />
{:else}
<RoleIcon class="w-4 h-4 flex-shrink-0 opacity-50" />
{/if}
<div class="flex-1 min-w-0">
<span class="truncate block">{role.name}</span>
<span class="text-2xs opacity-70 flex items-center gap-1">
{#if isGlobal}
<Globe class="w-2.5 h-2.5" />
All environments
{:else}
{envCount} environment{envCount !== 1 ? 's' : ''}
{/if}
</span>
</div>
</button>
{/each}
</div>
</div>
{/if}
{#if roles.length === 0}
<div class="p-4 text-center text-sm text-muted-foreground">
No roles defined yet
</div>
{/if}
</div>
</div>
{:else}
<div class="space-y-1">
<p class="text-xs text-muted-foreground">
All users have full access to all environments.
</p>
<p class="text-xs text-muted-foreground flex items-center gap-1">
<Crown class="w-3 h-3 text-amber-500" />
Upgrade to Enterprise for role-based access control.
</p>
</div>
{/if}
</div>
<Dialog.Footer>
{#if isEditing}
<Button variant="outline" type="button" onclick={handleClose}>Cancel</Button>
<Button type="submit" disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
{/if}
Save
</Button>
{:else}
<Button variant="outline" type="button" onclick={handleClose}>Cancel</Button>
<Button type="submit" disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<UserPlus class="w-4 h-4 mr-1" />
{/if}
Create user
</Button>
{/if}
</Dialog.Footer>
</form>
</Dialog.Content>
</Dialog.Root>
@@ -0,0 +1,490 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import * as Dialog from '$lib/components/ui/dialog';
import { Badge } from '$lib/components/ui/badge';
import { Input } from '$lib/components/ui/input';
import {
Users,
User,
Pencil,
Trash2,
RefreshCw,
Shield,
ShieldCheck,
UserPlus,
AlertTriangle,
Crown,
Wrench,
Eye,
Tag,
KeyRound,
Network,
Search,
ArrowUpDown,
ArrowUp,
ArrowDown
} from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { EmptyState } from '$lib/components/ui/empty-state';
import { canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import UserModal from './UserModal.svelte';
const MAX_VISIBLE_ROLES = 5;
// Search and sort state
type SortField = 'username' | 'email' | 'provider';
type SortDirection = 'asc' | 'desc';
let searchQuery = $state('');
let sortField = $state<SortField>('username');
let sortDirection = $state<SortDirection>('asc');
interface UserRole {
id: number;
name: string;
environmentId?: number | null;
}
interface LocalUser {
id: number;
username: string;
email?: string;
displayName?: string;
mfaEnabled: boolean;
isAdmin: boolean;
isActive: boolean;
isSso: boolean;
authProvider?: string;
lastLogin?: string;
createdAt: string;
roles?: UserRole[];
}
interface Role {
id: number;
name: string;
description?: string;
isSystem: boolean;
permissions: any;
createdAt: string;
}
interface Props {
roles: Role[];
}
let { roles }: Props = $props();
// Local users state
let localUsers = $state<LocalUser[]>([]);
let usersLoading = $state(true);
let showUserModal = $state(false);
let editingUser = $state<LocalUser | null>(null);
let confirmDeleteUserId = $state<number | null>(null);
let showLastAdminWarning = $state(false);
let lastAdminDeleteUserId = $state<number | null>(null);
async function fetchUsers() {
usersLoading = true;
try {
const response = await fetch('/api/users');
if (response.ok) {
localUsers = await response.json();
}
} catch (error) {
console.error('Failed to fetch users:', error);
toast.error('Failed to fetch users');
} finally {
usersLoading = false;
}
}
function openUserModal(user: LocalUser | null) {
editingUser = user;
showUserModal = true;
}
function handleUserModalClose() {
showUserModal = false;
editingUser = null;
}
async function handleUserModalSaved() {
showUserModal = false;
editingUser = null;
await fetchUsers();
}
async function deleteLocalUser(userId: number, confirmDisableAuth = false) {
try {
const url = confirmDisableAuth
? `/api/users/${userId}?confirmDisableAuth=true`
: `/api/users/${userId}`;
const response = await fetch(url, { method: 'DELETE' });
if (response.ok) {
const data = await response.json();
await fetchUsers();
if (data.authDisabled) {
toast.success('User deleted. Authentication has been disabled.');
} else {
toast.success('User deleted');
}
showLastAdminWarning = false;
lastAdminDeleteUserId = null;
} else if (response.status === 409) {
// Check if this is the last admin warning
const data = await response.json();
if (data.isLastAdmin) {
// Show last admin warning dialog
lastAdminDeleteUserId = userId;
showLastAdminWarning = true;
} else {
toast.error(data.error || 'Failed to delete user');
}
} else {
const data = await response.json();
toast.error(data.error || 'Failed to delete user');
}
} catch (error) {
console.error('Failed to delete user:', error);
toast.error('Failed to delete user');
} finally {
confirmDeleteUserId = null;
}
}
function confirmLastAdminDelete() {
if (lastAdminDeleteUserId) {
deleteLocalUser(lastAdminDeleteUserId, true);
}
}
function cancelLastAdminDelete() {
showLastAdminWarning = false;
lastAdminDeleteUserId = null;
}
// Get icon component for a role based on its name
function getRoleIcon(roleName: string): typeof Crown {
const name = roleName.toLowerCase();
if (name.includes('admin')) return Crown;
if (name.includes('operator')) return Wrench;
if (name.includes('viewer') || name.includes('view') || name.includes('read')) return Eye;
return Tag;
}
// Get provider display info
function getProviderInfo(user: LocalUser): { icon: typeof KeyRound; label: string; class: string; sortKey: string } {
if (!user.isSso) {
return { icon: KeyRound, label: 'Local', class: 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/30', sortKey: 'local' };
}
const providerParts = user.authProvider?.split(':') || [];
const providerType = providerParts[0]?.toLowerCase() || 'sso';
const providerName = providerParts[1] || '';
if (providerType === 'ldap') {
return { icon: Network, label: providerName || 'LDAP', class: 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30', sortKey: 'ldap' };
}
return { icon: ShieldCheck, label: providerName || 'OIDC', class: 'bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/30', sortKey: 'oidc' };
}
// Filter and sort users
const filteredAndSortedUsers = $derived.by(() => {
let result = localUsers;
// Filter by search query
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
result = result.filter(user =>
user.username.toLowerCase().includes(query) ||
(user.email?.toLowerCase().includes(query)) ||
(user.displayName?.toLowerCase().includes(query)) ||
(user.roles?.some(r => r.name.toLowerCase().includes(query)))
);
}
// Sort
result = [...result].sort((a, b) => {
let aVal: string, bVal: string;
switch (sortField) {
case 'username':
aVal = a.username.toLowerCase();
bVal = b.username.toLowerCase();
break;
case 'email':
aVal = (a.email || '').toLowerCase();
bVal = (b.email || '').toLowerCase();
break;
case 'provider':
aVal = getProviderInfo(a).sortKey;
bVal = getProviderInfo(b).sortKey;
break;
default:
aVal = a.username.toLowerCase();
bVal = b.username.toLowerCase();
}
const cmp = aVal.localeCompare(bVal);
return sortDirection === 'asc' ? cmp : -cmp;
});
return result;
});
function toggleSort(field: SortField) {
if (sortField === field) {
sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
} else {
sortField = field;
sortDirection = 'asc';
}
}
onMount(() => {
fetchUsers();
});
</script>
<div class="flex flex-col flex-1 min-h-0">
<Card.Root class="flex flex-col flex-1 min-h-0">
<Card.Header class="flex-shrink-0 py-3">
<div class="flex items-center justify-between">
<div>
<Card.Title class="text-sm font-medium flex items-center gap-2">
<Users class="w-4 h-4" />
Users
</Card.Title>
<p class="text-xs text-muted-foreground mt-1">Manage user accounts for local authentication, SSO, and LDAP.</p>
</div>
{#if $canAccess('users', 'create')}
<Button size="sm" onclick={() => openUserModal(null)}>
<UserPlus class="w-4 h-4 mr-1" />
Add user
</Button>
{/if}
</div>
</Card.Header>
<Card.Content class="flex-1 flex flex-col min-h-0">
{#if usersLoading}
<div class="flex items-center justify-center py-4">
<RefreshCw class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
{:else if localUsers.length === 0}
<EmptyState
icon={Users}
title="No users configured"
description="Create the first user to enable login"
/>
{:else}
<!-- Filter bar -->
<div class="flex items-center gap-2 mb-3">
<div class="relative flex-1 max-w-xs">
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
<Input
type="text"
placeholder="Search users..."
bind:value={searchQuery}
class="pl-8 h-8 text-sm"
/>
</div>
<div class="flex items-center gap-1 text-xs text-muted-foreground ml-auto">
<span>{filteredAndSortedUsers.length} of {localUsers.length} users</span>
</div>
</div>
<!-- Table -->
<div class="flex-1 min-h-0 overflow-auto rounded-lg border">
<table class="w-full text-sm">
<thead class="bg-muted sticky top-0 z-10">
<tr class="border-b">
<th class="text-left py-1.5 px-3 font-medium w-[25%]">
<button
type="button"
class="flex items-center gap-1 hover:text-foreground transition-colors"
onclick={() => toggleSort('username')}
>
User
{#if sortField === 'username'}
{#if sortDirection === 'asc'}<ArrowUp class="w-3 h-3" />{:else}<ArrowDown class="w-3 h-3" />{/if}
{:else}
<ArrowUpDown class="w-3 h-3 opacity-30" />
{/if}
</button>
</th>
<th class="text-left py-1.5 px-3 font-medium w-[25%]">
<button
type="button"
class="flex items-center gap-1 hover:text-foreground transition-colors"
onclick={() => toggleSort('email')}
>
Email
{#if sortField === 'email'}
{#if sortDirection === 'asc'}<ArrowUp class="w-3 h-3" />{:else}<ArrowDown class="w-3 h-3" />{/if}
{:else}
<ArrowUpDown class="w-3 h-3 opacity-30" />
{/if}
</button>
</th>
<th class="text-left py-1.5 px-3 font-medium w-[8%]">MFA</th>
{#if $licenseStore.isEnterprise}
<th class="text-left py-1.5 px-3 font-medium w-[25%]">Roles</th>
{/if}
<th class="text-left py-1.5 px-3 font-medium w-[15%]">
<button
type="button"
class="flex items-center gap-1 hover:text-foreground transition-colors"
onclick={() => toggleSort('provider')}
>
Provider
{#if sortField === 'provider'}
{#if sortDirection === 'asc'}<ArrowUp class="w-3 h-3" />{:else}<ArrowDown class="w-3 h-3" />{/if}
{:else}
<ArrowUpDown class="w-3 h-3 opacity-30" />
{/if}
</button>
</th>
<th class="text-right py-1.5 px-3 font-medium w-[10%]"></th>
</tr>
</thead>
<tbody>
{#each filteredAndSortedUsers as user}
{@const provider = getProviderInfo(user)}
{@const ProviderIcon = provider.icon}
{@const visibleRoles = user.roles?.slice(0, MAX_VISIBLE_ROLES) || []}
{@const hiddenRolesCount = (user.roles?.length || 0) - MAX_VISIBLE_ROLES}
<tr class="border-b border-muted hover:bg-muted/30 transition-colors">
<!-- User -->
<td class="py-2 px-3">
<div class="flex items-center gap-2">
<div class="w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
<User class="w-3 h-3 text-primary" />
</div>
<div class="flex items-center gap-1.5">
<span class="font-medium">{user.username}</span>
{#if !user.isActive}
<Badge variant="destructive" class="text-2xs px-1 py-0 h-4">Disabled</Badge>
{/if}
</div>
</div>
</td>
<!-- Email -->
<td class="py-2 px-3">
<span class="text-muted-foreground truncate block">{user.email || '—'}</span>
</td>
<!-- MFA -->
<td class="py-2 px-3">
{#if user.mfaEnabled}
<Badge variant="outline" class="text-2xs px-1.5 py-0 h-4 gap-1 rounded-sm bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/30">
<Shield class="w-2.5 h-2.5" />
Enabled
</Badge>
{:else}
<span class="text-muted-foreground">—</span>
{/if}
</td>
<!-- Roles (Enterprise only) -->
{#if $licenseStore.isEnterprise}
<td class="py-2 px-3">
{#if user.roles && user.roles.length > 0}
<div class="flex items-center gap-1 flex-wrap">
{#each visibleRoles as role}
{@const RoleIcon = getRoleIcon(role.name)}
<Badge variant="outline" class="text-2xs px-1.5 py-0 h-4 gap-1 rounded-sm bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/30">
<RoleIcon class="w-2.5 h-2.5" />
{role.name}
</Badge>
{/each}
{#if hiddenRolesCount > 0}
<span class="text-2xs text-muted-foreground">+{hiddenRolesCount} more</span>
{/if}
</div>
{:else}
<span class="text-muted-foreground">—</span>
{/if}
</td>
{/if}
<!-- Provider -->
<td class="py-2 px-3">
<Badge variant="outline" class="text-2xs px-1.5 py-0 h-4 gap-1 rounded-sm {provider.class}">
<ProviderIcon class="w-2.5 h-2.5" />
{provider.label}
</Badge>
</td>
<!-- Actions -->
<td class="py-2 px-3 text-right">
<div class="flex items-center justify-end gap-1">
{#if $canAccess('users', 'edit')}
<Button
variant="ghost"
size="sm"
class="h-7 w-7 p-0"
onclick={() => openUserModal(user)}
>
<Pencil class="w-3.5 h-3.5" />
</Button>
{/if}
{#if $canAccess('users', 'delete')}
<ConfirmPopover
open={confirmDeleteUserId === user.id}
action="Delete"
itemType="user"
itemName={user.username}
onConfirm={() => deleteLocalUser(user.id)}
onOpenChange={(open) => { if (!open) confirmDeleteUserId = null; else confirmDeleteUserId = user.id; }}
>
<span class="inline-flex items-center justify-center h-7 w-7 rounded-md hover:bg-accent hover:text-accent-foreground">
<Trash2 class="w-3.5 h-3.5 text-destructive" />
</span>
</ConfirmPopover>
{/if}
</div>
</td>
</tr>
{:else}
<tr>
<td colspan={$licenseStore.isEnterprise ? 6 : 5} class="py-8 text-center text-muted-foreground">
<Search class="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No users found matching "{searchQuery}"</p>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
<UserModal
bind:open={showUserModal}
user={editingUser}
{roles}
isEnterprise={$licenseStore.isEnterprise}
onClose={handleUserModalClose}
onSaved={handleUserModalSaved}
/>
<!-- Last Admin Warning Dialog -->
<Dialog.Root bind:open={showLastAdminWarning}>
<Dialog.Content class="max-w-md">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2 text-destructive">
<AlertTriangle class="w-5 h-5" />
Delete last admin?
</Dialog.Title>
<Dialog.Description class="text-left">
This is the only admin account. Deleting it will <strong>disable authentication</strong> and allow anyone to access Dockhand without logging in.
</Dialog.Description>
</Dialog.Header>
<Dialog.Footer>
<Button variant="outline" onclick={cancelLastAdminDelete}>Cancel</Button>
<Button variant="destructive" onclick={confirmLastAdminDelete}>
<Trash2 class="w-4 h-4 mr-1" />
Delete and disable auth
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>