masih ngerjain user management
This commit is contained in:
@@ -53,6 +53,8 @@ export interface UpdateUserRequest {
|
||||
email?: string
|
||||
full_name?: string
|
||||
is_active?: boolean
|
||||
roles?: string[]
|
||||
groups?: string[]
|
||||
}
|
||||
|
||||
export const iamApi = {
|
||||
@@ -143,9 +145,47 @@ export const iamApi = {
|
||||
},
|
||||
|
||||
// List all available roles
|
||||
listRoles: async (): Promise<Array<{ name: string; description?: string; is_system: boolean }>> => {
|
||||
const response = await apiClient.get<{ roles: Array<{ name: string; description?: string; is_system: boolean }> }>('/iam/roles')
|
||||
listRoles: async (): Promise<Array<{ id: string; name: string; description?: string; is_system: boolean; user_count?: number; created_at?: string; updated_at?: string }>> => {
|
||||
const response = await apiClient.get<{ roles: Array<{ id: string; name: string; description?: string; is_system: boolean; user_count?: number; created_at?: string; updated_at?: string }> }>('/iam/roles')
|
||||
return response.data.roles
|
||||
},
|
||||
|
||||
getRole: async (id: string): Promise<{ id: string; name: string; description?: string; is_system: boolean; user_count?: number; created_at?: string; updated_at?: string }> => {
|
||||
const response = await apiClient.get<{ id: string; name: string; description?: string; is_system: boolean; user_count?: number; created_at?: string; updated_at?: string }>(`/iam/roles/${id}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
createRole: async (data: { name: string; description?: string }): Promise<{ id: string; name: string }> => {
|
||||
const response = await apiClient.post<{ id: string; name: string }>('/iam/roles', data)
|
||||
return response.data
|
||||
},
|
||||
|
||||
updateRole: async (id: string, data: { name?: string; description?: string }): Promise<void> => {
|
||||
await apiClient.put(`/iam/roles/${id}`, data)
|
||||
},
|
||||
|
||||
deleteRole: async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/iam/roles/${id}`)
|
||||
},
|
||||
|
||||
// Role permissions
|
||||
getRolePermissions: async (roleId: string): Promise<string[]> => {
|
||||
const response = await apiClient.get<{ permissions: string[] }>(`/iam/roles/${roleId}/permissions`)
|
||||
return response.data.permissions
|
||||
},
|
||||
|
||||
assignPermissionToRole: async (roleId: string, permissionName: string): Promise<void> => {
|
||||
await apiClient.post(`/iam/roles/${roleId}/permissions`, { permission_name: permissionName })
|
||||
},
|
||||
|
||||
removePermissionFromRole: async (roleId: string, permissionName: string): Promise<void> => {
|
||||
await apiClient.delete(`/iam/roles/${roleId}/permissions?permission_name=${encodeURIComponent(permissionName)}`)
|
||||
},
|
||||
|
||||
// Permissions
|
||||
listPermissions: async (): Promise<Array<{ id: string; name: string; resource: string; action: string; description?: string }>> => {
|
||||
const response = await apiClient.get<{ permissions: Array<{ id: string; name: string; resource: string; action: string; description?: string }> }>('/iam/permissions')
|
||||
return response.data.permissions
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { ChevronRight, Search, Filter, UserPlus, History, ChevronLeft, MoreVertical, Lock, Verified, Wrench, Eye, HardDrive, Shield, ArrowRight, Network, ChevronRight as ChevronRightIcon, X, Edit, Trash2, User as UserIcon, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -145,6 +145,17 @@ export default function IAM() {
|
||||
<Network size={20} />
|
||||
<span className="text-sm font-bold">Groups</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('roles')}
|
||||
className={`flex items-center gap-2 pb-3 border-b-[3px] transition-colors ${
|
||||
activeTab === 'roles'
|
||||
? 'border-primary text-white'
|
||||
: 'border-transparent text-text-secondary hover:text-white hover:border-slate-600'
|
||||
}`}
|
||||
>
|
||||
<Shield size={20} />
|
||||
<span className="text-sm font-bold">Roles</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('directory')}
|
||||
className={`flex items-center gap-2 pb-3 border-b-[3px] transition-colors ${
|
||||
@@ -403,6 +414,8 @@ export default function IAM() {
|
||||
|
||||
{/* Groups Tab */}
|
||||
{activeTab === 'groups' && <GroupsTab />}
|
||||
{/* Roles Tab */}
|
||||
{activeTab === 'roles' && <RolesTab />}
|
||||
|
||||
{activeTab !== 'users' && activeTab !== 'groups' && (
|
||||
<div className="p-8 text-center text-text-secondary">
|
||||
@@ -655,7 +668,7 @@ function EditUserForm({ user, onClose, onSuccess }: EditUserFormProps) {
|
||||
const unassignedGroups = availableGroups.filter(g => !userGroups.includes(g.name))
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: { email?: string; full_name?: string; is_active?: boolean }) =>
|
||||
mutationFn: (data: { email?: string; full_name?: string; is_active?: boolean; roles?: string[]; groups?: string[] }) =>
|
||||
iamApi.updateUser(user.id, data),
|
||||
onSuccess: async () => {
|
||||
onSuccess()
|
||||
@@ -673,24 +686,42 @@ function EditUserForm({ user, onClose, onSuccess }: EditUserFormProps) {
|
||||
|
||||
const assignRoleMutation = useMutation({
|
||||
mutationFn: (roleName: string) => iamApi.assignRoleToUser(user.id, roleName),
|
||||
onMutate: async (roleName: string) => {
|
||||
// Optimistic update: add role to state immediately
|
||||
setUserRoles(prev => {
|
||||
if (prev.includes(roleName)) return prev
|
||||
return [...prev, roleName]
|
||||
})
|
||||
setSelectedRole('')
|
||||
},
|
||||
onSuccess: async () => {
|
||||
// Verify with server data
|
||||
const updatedUser = await iamApi.getUser(user.id)
|
||||
setUserRoles(updatedUser.roles || [])
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-user', user.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-user', user.id] })
|
||||
setSelectedRole('')
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to assign role:', error)
|
||||
onError: (error: any, roleName: string) => {
|
||||
console.error('Failed to assign role:', error, roleName)
|
||||
// Rollback: remove role from state if API call failed
|
||||
setUserRoles(prev => prev.filter(r => r !== roleName))
|
||||
alert(error.response?.data?.error || error.message || 'Failed to assign role')
|
||||
},
|
||||
})
|
||||
|
||||
const removeRoleMutation = useMutation({
|
||||
mutationFn: (roleName: string) => iamApi.removeRoleFromUser(user.id, roleName),
|
||||
onMutate: async (roleName: string) => {
|
||||
// Store previous state for rollback
|
||||
const previousRoles = userRoles
|
||||
// Optimistic update: remove role from state immediately
|
||||
setUserRoles(prev => prev.filter(r => r !== roleName))
|
||||
return { previousRoles }
|
||||
},
|
||||
onSuccess: async () => {
|
||||
// Verify with server data
|
||||
const updatedUser = await iamApi.getUser(user.id)
|
||||
setUserRoles(updatedUser.roles || [])
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
@@ -698,32 +729,54 @@ function EditUserForm({ user, onClose, onSuccess }: EditUserFormProps) {
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-user', user.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-user', user.id] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
onError: (error: any, _roleName: string, context: any) => {
|
||||
console.error('Failed to remove role:', error)
|
||||
// Rollback: restore previous state if API call failed
|
||||
if (context?.previousRoles) {
|
||||
setUserRoles(context.previousRoles)
|
||||
}
|
||||
alert(error.response?.data?.error || error.message || 'Failed to remove role')
|
||||
},
|
||||
})
|
||||
|
||||
const assignGroupMutation = useMutation({
|
||||
mutationFn: (groupName: string) => iamApi.assignGroupToUser(user.id, groupName),
|
||||
onMutate: async (groupName: string) => {
|
||||
// Optimistic update: add group to state immediately
|
||||
setUserGroups(prev => {
|
||||
if (prev.includes(groupName)) return prev
|
||||
return [...prev, groupName]
|
||||
})
|
||||
setSelectedGroup('')
|
||||
},
|
||||
onSuccess: async () => {
|
||||
// Verify with server data
|
||||
const updatedUser = await iamApi.getUser(user.id)
|
||||
setUserGroups(updatedUser.groups || [])
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-user', user.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-user', user.id] })
|
||||
setSelectedGroup('')
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to assign group:', error)
|
||||
onError: (error: any, groupName: string) => {
|
||||
console.error('Failed to assign group:', error, groupName)
|
||||
// Rollback: remove group from state if API call failed
|
||||
setUserGroups(prev => prev.filter(g => g !== groupName))
|
||||
alert(error.response?.data?.error || error.message || 'Failed to assign group')
|
||||
},
|
||||
})
|
||||
|
||||
const removeGroupMutation = useMutation({
|
||||
mutationFn: (groupName: string) => iamApi.removeGroupFromUser(user.id, groupName),
|
||||
onMutate: async (groupName: string) => {
|
||||
// Store previous state for rollback
|
||||
const previousGroups = userGroups
|
||||
// Optimistic update: remove group from state immediately
|
||||
setUserGroups(prev => prev.filter(g => g !== groupName))
|
||||
return { previousGroups }
|
||||
},
|
||||
onSuccess: async () => {
|
||||
// Verify with server data
|
||||
const updatedUser = await iamApi.getUser(user.id)
|
||||
setUserGroups(updatedUser.groups || [])
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
@@ -731,19 +784,29 @@ function EditUserForm({ user, onClose, onSuccess }: EditUserFormProps) {
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-user', user.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-user', user.id] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
onError: (error: any, _groupName: string, context: any) => {
|
||||
console.error('Failed to remove group:', error)
|
||||
// Rollback: restore previous state if API call failed
|
||||
if (context?.previousGroups) {
|
||||
setUserGroups(context.previousGroups)
|
||||
}
|
||||
alert(error.response?.data?.error || error.message || 'Failed to remove group')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
updateMutation.mutate({
|
||||
const payload = {
|
||||
email: email.trim(),
|
||||
full_name: fullName.trim() || undefined,
|
||||
is_active: isActive,
|
||||
})
|
||||
roles: userRoles,
|
||||
groups: userGroups,
|
||||
}
|
||||
console.log('EditUserForm - Submitting payload:', payload)
|
||||
console.log('EditUserForm - userRoles:', userRoles)
|
||||
console.log('EditUserForm - userGroups:', userGroups)
|
||||
updateMutation.mutate(payload)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -962,6 +1025,9 @@ function GroupsTab() {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [showEditForm, setShowEditForm] = useState(false)
|
||||
const [selectedGroup, setSelectedGroup] = useState<Group | null>(null)
|
||||
const [openActionMenu, setOpenActionMenu] = useState<string | null>(null)
|
||||
|
||||
const { data: groups, isLoading } = useQuery<Group[]>({
|
||||
queryKey: ['iam-groups'],
|
||||
@@ -973,6 +1039,27 @@ function GroupsTab() {
|
||||
(group.description && group.description.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
) || []
|
||||
|
||||
const deleteGroupMutation = useMutation({
|
||||
mutationFn: iamApi.deleteGroup,
|
||||
onSuccess: async () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-groups'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-groups'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
alert('Group deleted successfully!')
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to delete group:', error)
|
||||
alert(error.response?.data?.error || error.message || 'Failed to delete group')
|
||||
},
|
||||
})
|
||||
|
||||
const handleDeleteGroup = (groupId: string, groupName: string) => {
|
||||
if (confirm(`Are you sure you want to delete group "${groupName}"? This action cannot be undone.`)) {
|
||||
deleteGroupMutation.mutate(groupId)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Toolbar */}
|
||||
@@ -1052,9 +1139,54 @@ function GroupsTab() {
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<button className="p-2 text-text-secondary hover:text-white hover:bg-border-dark rounded-lg transition-colors">
|
||||
<MoreVertical size={20} />
|
||||
</button>
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setOpenActionMenu(openActionMenu === group.id ? null : group.id)
|
||||
}}
|
||||
className="p-2 text-text-secondary hover:text-white hover:bg-border-dark rounded-lg transition-colors"
|
||||
>
|
||||
<MoreVertical size={20} />
|
||||
</button>
|
||||
{openActionMenu === group.id && (
|
||||
<>
|
||||
<div
|
||||
className="fixed inset-0 z-10"
|
||||
onClick={() => setOpenActionMenu(null)}
|
||||
/>
|
||||
<div className="absolute right-0 mt-1 w-48 bg-card-dark border border-border-dark rounded-lg shadow-xl z-20">
|
||||
<div className="py-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setSelectedGroup(group)
|
||||
setShowEditForm(true)
|
||||
setOpenActionMenu(null)
|
||||
}}
|
||||
disabled={group.is_system}
|
||||
className="w-full px-4 py-2 text-left text-sm text-white hover:bg-[#233648] flex items-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Edit size={16} />
|
||||
Edit Group
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDeleteGroup(group.id, group.name)
|
||||
setOpenActionMenu(null)
|
||||
}}
|
||||
disabled={group.is_system || deleteGroupMutation.isPending}
|
||||
className="w-full px-4 py-2 text-left text-sm text-red-400 hover:bg-red-500/10 flex items-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
Delete Group
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
@@ -1089,9 +1221,29 @@ function GroupsTab() {
|
||||
{showCreateForm && (
|
||||
<CreateGroupForm
|
||||
onClose={() => setShowCreateForm(false)}
|
||||
onSuccess={() => {
|
||||
onSuccess={async () => {
|
||||
setShowCreateForm(false)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-groups'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-groups'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Edit Group Form Modal */}
|
||||
{showEditForm && selectedGroup && (
|
||||
<EditGroupForm
|
||||
group={selectedGroup}
|
||||
onClose={() => {
|
||||
setShowEditForm(false)
|
||||
setSelectedGroup(null)
|
||||
}}
|
||||
onSuccess={async () => {
|
||||
setShowEditForm(false)
|
||||
setSelectedGroup(null)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-groups'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-groups'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -1208,3 +1360,623 @@ function CreateGroupForm({ onClose, onSuccess }: CreateGroupFormProps) {
|
||||
)
|
||||
}
|
||||
|
||||
// Roles Tab Component
|
||||
function RolesTab() {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [showEditForm, setShowEditForm] = useState(false)
|
||||
const [selectedRole, setSelectedRole] = useState<{ id: string; name: string; description?: string; is_system: boolean } | null>(null)
|
||||
|
||||
const { data: roles, isLoading } = useQuery({
|
||||
queryKey: ['iam-roles'],
|
||||
queryFn: iamApi.listRoles,
|
||||
})
|
||||
|
||||
const filteredRoles = roles?.filter(role =>
|
||||
role.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
(role.description && role.description.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
) || []
|
||||
|
||||
const deleteRoleMutation = useMutation({
|
||||
mutationFn: iamApi.deleteRole,
|
||||
onSuccess: async () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-roles'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
alert('Role deleted successfully!')
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to delete role:', error)
|
||||
alert(error.response?.data?.error || error.message || 'Failed to delete role')
|
||||
},
|
||||
})
|
||||
|
||||
const handleDeleteRole = (roleId: string) => {
|
||||
if (confirm('Are you sure you want to delete this role? This action cannot be undone.')) {
|
||||
deleteRoleMutation.mutate(roleId)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Toolbar */}
|
||||
<div className="flex flex-wrap gap-4 items-center justify-between">
|
||||
<div className="flex flex-1 max-w-xl gap-3">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" size={20} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search roles by name or description..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full bg-card-dark border border-border-dark rounded-lg pl-10 pr-4 py-2.5 text-white placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-sm"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex items-center gap-2 px-4 py-2.5 bg-card-dark border border-border-dark rounded-lg text-text-secondary hover:text-white hover:border-slate-500 transition-colors"
|
||||
>
|
||||
<Filter size={20} />
|
||||
<span className="text-sm font-medium">Filter</span>
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
className="flex items-center gap-2 bg-primary hover:bg-blue-600 text-white px-5 py-2.5 rounded-lg font-bold shadow-lg shadow-blue-500/20 transition-all"
|
||||
>
|
||||
<UserPlus size={20} />
|
||||
<span>Create Role</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Roles Table */}
|
||||
<div className="rounded-xl border border-border-dark bg-[#111a22] overflow-hidden shadow-sm">
|
||||
<div className="overflow-x-auto custom-scrollbar">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="bg-card-dark border-b border-border-dark text-left">
|
||||
<th className="px-6 py-4 text-xs font-bold text-text-secondary uppercase tracking-wider">Name</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-text-secondary uppercase tracking-wider">Description</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-text-secondary uppercase tracking-wider">Users</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-text-secondary uppercase tracking-wider">Type</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-text-secondary uppercase tracking-wider text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border-dark">
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="px-6 py-8 text-center text-text-secondary">
|
||||
Loading roles...
|
||||
</td>
|
||||
</tr>
|
||||
) : filteredRoles.length > 0 ? (
|
||||
filteredRoles.map((role) => (
|
||||
<tr key={role.id} className="group hover:bg-card-dark transition-colors">
|
||||
<td className="px-6 py-4">
|
||||
<span className="text-white font-medium">{role.name}</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-text-secondary text-sm">
|
||||
{role.description || '-'}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-text-secondary text-sm">
|
||||
{role.user_count || 0}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{role.is_system ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-purple-500/10 text-purple-400 text-xs font-medium border border-purple-500/20">
|
||||
<Shield size={12} />
|
||||
System
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-blue-500/10 text-blue-400 text-xs font-medium border border-blue-500/20">
|
||||
Custom
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedRole(role)
|
||||
setShowEditForm(true)
|
||||
}}
|
||||
className="p-2 text-text-secondary hover:text-white hover:bg-border-dark rounded-lg transition-colors"
|
||||
title="Edit role"
|
||||
>
|
||||
<Edit size={16} />
|
||||
</button>
|
||||
{!role.is_system && (
|
||||
<button
|
||||
onClick={() => handleDeleteRole(role.id)}
|
||||
disabled={deleteRoleMutation.isPending}
|
||||
className="p-2 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded-lg transition-colors"
|
||||
title="Delete role"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={5} className="px-6 py-8 text-center text-text-secondary">
|
||||
No roles found
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Create Role Form Modal */}
|
||||
{showCreateForm && (
|
||||
<CreateRoleForm
|
||||
onClose={() => setShowCreateForm(false)}
|
||||
onSuccess={async () => {
|
||||
setShowCreateForm(false)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-roles'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-roles'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Edit Role Form Modal */}
|
||||
{showEditForm && selectedRole && (
|
||||
<EditRoleForm
|
||||
role={selectedRole}
|
||||
onClose={() => {
|
||||
setShowEditForm(false)
|
||||
setSelectedRole(null)
|
||||
}}
|
||||
onSuccess={async () => {
|
||||
setShowEditForm(false)
|
||||
setSelectedRole(null)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-roles'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Create Role Form Component
|
||||
interface CreateRoleFormProps {
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
function CreateRoleForm({ onClose, onSuccess }: CreateRoleFormProps) {
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: { name: string; description?: string }) => iamApi.createRole(data),
|
||||
onSuccess: () => {
|
||||
onSuccess()
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to create role:', error)
|
||||
const errorMessage = error.response?.data?.error || error.message || 'Failed to create role'
|
||||
alert(errorMessage)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
createMutation.mutate({
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||
<div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
|
||||
<div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-white">Create Role</h2>
|
||||
<p className="text-sm text-text-secondary mt-1">Create a new role for access control</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
|
||||
>
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
||||
<div>
|
||||
<label htmlFor="role-name" className="block text-sm font-medium text-white mb-2">
|
||||
Role Name <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="role-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g., operator, auditor"
|
||||
className="w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="role-description" className="block text-sm font-medium text-white mb-2">
|
||||
Description <span className="text-text-secondary text-xs">(Optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="role-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Describe the role's purpose and permissions"
|
||||
rows={3}
|
||||
className="w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-border-dark">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
className="px-6"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={createMutation.isPending}
|
||||
className="px-6 bg-primary hover:bg-blue-600"
|
||||
>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create Role'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit Role Form Component
|
||||
interface EditRoleFormProps {
|
||||
role: { id: string; name: string; description?: string; is_system: boolean }
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
function EditRoleForm({ role, onClose, onSuccess }: EditRoleFormProps) {
|
||||
const [name, setName] = useState(role.name)
|
||||
const [description, setDescription] = useState(role.description || '')
|
||||
const [rolePermissions, setRolePermissions] = useState<string[]>([])
|
||||
const [selectedPermission, setSelectedPermission] = useState('')
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// Fetch role permissions
|
||||
const { data: permissions = [] } = useQuery({
|
||||
queryKey: ['iam-role-permissions', role.id],
|
||||
queryFn: () => iamApi.getRolePermissions(role.id),
|
||||
})
|
||||
|
||||
// Update rolePermissions when permissions data changes
|
||||
useEffect(() => {
|
||||
if (permissions) {
|
||||
setRolePermissions(permissions)
|
||||
}
|
||||
}, [permissions])
|
||||
|
||||
// Fetch all available permissions
|
||||
const { data: availablePermissions = [] } = useQuery({
|
||||
queryKey: ['iam-permissions'],
|
||||
queryFn: iamApi.listPermissions,
|
||||
})
|
||||
|
||||
// Filter out already assigned permissions
|
||||
const unassignedPermissions = availablePermissions.filter(p => !rolePermissions.includes(p.name))
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: { name?: string; description?: string }) => iamApi.updateRole(role.id, data),
|
||||
onSuccess: () => {
|
||||
onSuccess()
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to update role:', error)
|
||||
const errorMessage = error.response?.data?.error || error.message || 'Failed to update role'
|
||||
alert(errorMessage)
|
||||
},
|
||||
})
|
||||
|
||||
const assignPermissionMutation = useMutation({
|
||||
mutationFn: (permissionName: string) => iamApi.assignPermissionToRole(role.id, permissionName),
|
||||
onSuccess: async () => {
|
||||
const updatedPermissions = await iamApi.getRolePermissions(role.id)
|
||||
setRolePermissions(updatedPermissions)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-role-permissions', role.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-role-permissions', role.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
setSelectedPermission('')
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to assign permission:', error)
|
||||
alert(error.response?.data?.error || error.message || 'Failed to assign permission')
|
||||
},
|
||||
})
|
||||
|
||||
const removePermissionMutation = useMutation({
|
||||
mutationFn: (permissionName: string) => iamApi.removePermissionFromRole(role.id, permissionName),
|
||||
onSuccess: async () => {
|
||||
const updatedPermissions = await iamApi.getRolePermissions(role.id)
|
||||
setRolePermissions(updatedPermissions)
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-role-permissions', role.id] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-role-permissions', role.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['iam-users'] })
|
||||
await queryClient.refetchQueries({ queryKey: ['iam-users'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to remove permission:', error)
|
||||
alert(error.response?.data?.error || error.message || 'Failed to remove permission')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
updateMutation.mutate({
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||
<div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
|
||||
<div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-white">Edit Role: {role.name}</h2>
|
||||
<p className="text-sm text-text-secondary mt-1">Modify role details</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
|
||||
>
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
||||
<div>
|
||||
<label htmlFor="edit-role-name" className="block text-sm font-medium text-white mb-2">
|
||||
Role Name <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="edit-role-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={role.is_system}
|
||||
className={`w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors ${
|
||||
role.is_system ? 'cursor-not-allowed opacity-50' : ''
|
||||
}`}
|
||||
required
|
||||
/>
|
||||
{role.is_system && (
|
||||
<p className="text-xs text-text-secondary mt-1">System roles cannot be renamed</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="edit-role-description" className="block text-sm font-medium text-white mb-2">
|
||||
Description <span className="text-text-secondary text-xs">(Optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="edit-role-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Describe the role's purpose and permissions"
|
||||
rows={3}
|
||||
className="w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Permissions Section */}
|
||||
<div className="border-t border-border-dark pt-6">
|
||||
<label className="block text-sm font-medium text-white mb-3">
|
||||
Permissions
|
||||
</label>
|
||||
<div className="flex gap-2 mb-3">
|
||||
<select
|
||||
value={selectedPermission}
|
||||
onChange={(e) => setSelectedPermission(e.target.value)}
|
||||
className="flex-1 px-4 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
|
||||
>
|
||||
<option value="">Select a permission...</option>
|
||||
{unassignedPermissions.map((perm) => (
|
||||
<option key={perm.id} value={perm.name}>
|
||||
{perm.name} {perm.description ? `- ${perm.description}` : `(${perm.resource}:${perm.action})`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (selectedPermission) {
|
||||
assignPermissionMutation.mutate(selectedPermission)
|
||||
}
|
||||
}}
|
||||
disabled={!selectedPermission || assignPermissionMutation.isPending}
|
||||
className="px-4 bg-primary hover:bg-blue-600"
|
||||
>
|
||||
<Plus size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto custom-scrollbar">
|
||||
{rolePermissions.length > 0 ? (
|
||||
rolePermissions.map((perm) => {
|
||||
const permInfo = availablePermissions.find(p => p.name === perm)
|
||||
return (
|
||||
<div
|
||||
key={perm}
|
||||
className="flex items-center justify-between px-4 py-2 bg-[#0f161d] border border-border-dark rounded-lg"
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-white text-sm font-medium">{perm}</span>
|
||||
{permInfo && (
|
||||
<span className="text-text-secondary text-xs">
|
||||
{permInfo.resource}:{permInfo.action}
|
||||
{permInfo.description && ` - ${permInfo.description}`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removePermissionMutation.mutate(perm)}
|
||||
disabled={removePermissionMutation.isPending}
|
||||
className="text-red-400 hover:text-red-300 transition-colors"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<p className="text-text-secondary text-sm text-center py-2">No permissions assigned</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-border-dark">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
className="px-6"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={updateMutation.isPending || role.is_system}
|
||||
className="px-6 bg-primary hover:bg-blue-600"
|
||||
>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit Group Form Component
|
||||
interface EditGroupFormProps {
|
||||
group: Group
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
function EditGroupForm({ group, onClose, onSuccess }: EditGroupFormProps) {
|
||||
const [name, setName] = useState(group.name)
|
||||
const [description, setDescription] = useState(group.description || '')
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: { name?: string; description?: string }) => iamApi.updateGroup(group.id, data),
|
||||
onSuccess: () => {
|
||||
onSuccess()
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error('Failed to update group:', error)
|
||||
const errorMessage = error.response?.data?.error || error.message || 'Failed to update group'
|
||||
alert(errorMessage)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
updateMutation.mutate({
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||
<div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
|
||||
<div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-white">Edit Group: {group.name}</h2>
|
||||
<p className="text-sm text-text-secondary mt-1">Modify group details</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
|
||||
>
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-6">
|
||||
<div>
|
||||
<label htmlFor="edit-group-name" className="block text-sm font-medium text-white mb-2">
|
||||
Group Name <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="edit-group-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={group.is_system}
|
||||
className={`w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors ${
|
||||
group.is_system ? 'cursor-not-allowed opacity-50' : ''
|
||||
}`}
|
||||
required
|
||||
/>
|
||||
{group.is_system && (
|
||||
<p className="text-xs text-text-secondary mt-1">System groups cannot be renamed</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="edit-group-description" className="block text-sm font-medium text-white mb-2">
|
||||
Description <span className="text-text-secondary text-xs">(Optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="edit-group-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Describe the group's purpose"
|
||||
rows={3}
|
||||
className="w-full px-4 py-3 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm placeholder-text-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-border-dark">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
className="px-6"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={updateMutation.isPending || group.is_system}
|
||||
className="px-6 bg-primary hover:bg-blue-600"
|
||||
>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user