feat: use improve table for users and audit logs

This commit is contained in:
Elias Schneider
2024-10-16 08:49:19 +02:00
parent 29748cc6c7
commit 11ed661f86
4 changed files with 87 additions and 194 deletions

View File

@@ -18,7 +18,7 @@ func NewOidcController(group *gin.RouterGroup, jwtAuthMiddleware *middleware.Jwt
group.POST("/oidc/authorize", jwtAuthMiddleware.Add(false), oc.authorizeHandler) group.POST("/oidc/authorize", jwtAuthMiddleware.Add(false), oc.authorizeHandler)
group.POST("/oidc/authorize/new-client", jwtAuthMiddleware.Add(false), oc.authorizeNewClientHandler) group.POST("/oidc/authorize/new-client", jwtAuthMiddleware.Add(false), oc.authorizeNewClientHandler)
group.POST("/oidc/token", oc.createIDTokenHandler) group.POST("/oidc/token", oc.createTokensHandler)
group.GET("/oidc/userinfo", oc.userInfoHandler) group.GET("/oidc/userinfo", oc.userInfoHandler)
group.GET("/oidc/clients", jwtAuthMiddleware.Add(true), oc.listClientsHandler) group.GET("/oidc/clients", jwtAuthMiddleware.Add(true), oc.listClientsHandler)
@@ -91,7 +91,7 @@ func (oc *OidcController) authorizeNewClientHandler(c *gin.Context) {
c.JSON(http.StatusOK, response) c.JSON(http.StatusOK, response)
} }
func (oc *OidcController) createIDTokenHandler(c *gin.Context) { func (oc *OidcController) createTokensHandler(c *gin.Context) {
var input dto.OidcIdTokenDto var input dto.OidcIdTokenDto
if err := c.ShouldBind(&input); err != nil { if err := c.ShouldBind(&input); err != nil {

View File

@@ -11,12 +11,14 @@
let { let {
items, items,
selectedIds = $bindable(), selectedIds = $bindable(),
withoutSearch = false,
fetchItems, fetchItems,
columns, columns,
rows rows
}: { }: {
items: Paginated<T>; items: Paginated<T>;
selectedIds?: string[]; selectedIds?: string[];
withoutSearch?: boolean;
fetchItems: (search: string, page: number, limit: number) => Promise<Paginated<T>>; fetchItems: (search: string, page: number, limit: number) => Promise<Paginated<T>>;
columns: (string | { label: string; hidden?: boolean })[]; columns: (string | { label: string; hidden?: boolean })[];
rows: Snippet<[{ item: T }]>; rows: Snippet<[{ item: T }]>;
@@ -65,12 +67,14 @@
</script> </script>
<div class="w-full"> <div class="w-full">
{#if !withoutSearch}
<Input <Input
class="mb-4 max-w-sm" class="mb-4 max-w-sm"
placeholder={'Search...'} placeholder={'Search...'}
type="text" type="text"
oninput={(e) => onSearch((e.target as HTMLInputElement).value)} oninput={(e) => onSearch((e.target as HTMLInputElement).value)}
/> />
{/if}
<Table.Root> <Table.Root>
<Table.Header> <Table.Header>
<Table.Row> <Table.Row>

View File

@@ -1,16 +1,14 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/stores'; import { page } from '$app/stores';
import AdvancedTable from '$lib/components/advanced-table.svelte';
import { openConfirmDialog } from '$lib/components/confirm-dialog/'; import { openConfirmDialog } from '$lib/components/confirm-dialog/';
import { Badge } from '$lib/components/ui/badge/index'; import { Badge } from '$lib/components/ui/badge/index';
import { Button } from '$lib/components/ui/button'; import { Button } from '$lib/components/ui/button';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu'; import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { Input } from '$lib/components/ui/input';
import * as Pagination from '$lib/components/ui/pagination';
import * as Table from '$lib/components/ui/table'; import * as Table from '$lib/components/ui/table';
import UserService from '$lib/services/user-service'; import UserService from '$lib/services/user-service';
import type { Paginated, PaginationRequest } from '$lib/types/pagination.type'; import type { Paginated } from '$lib/types/pagination.type';
import type { User } from '$lib/types/user.type'; import type { User } from '$lib/types/user.type';
import { debounced } from '$lib/utils/debounce-util';
import { axiosErrorToast } from '$lib/utils/error-util'; import { axiosErrorToast } from '$lib/utils/error-util';
import { LucideLink, LucidePencil, LucideTrash } from 'lucide-svelte'; import { LucideLink, LucidePencil, LucideTrash } from 'lucide-svelte';
import Ellipsis from 'lucide-svelte/icons/ellipsis'; import Ellipsis from 'lucide-svelte/icons/ellipsis';
@@ -19,23 +17,17 @@
let { users: initialUsers }: { users: Paginated<User> } = $props(); let { users: initialUsers }: { users: Paginated<User> } = $props();
let users = $state<Paginated<User>>(initialUsers); let users = $state<Paginated<User>>(initialUsers);
let oneTimeLink = $state<string | null>(null);
$effect(() => { $effect(() => {
users = initialUsers; users = initialUsers;
}); });
let oneTimeLink = $state<string | null>(null);
const userService = new UserService(); const userService = new UserService();
let pagination = $state<PaginationRequest>({ function fetchItems(search: string, page: number, limit: number) {
page: 1, return userService.list(search, { page, limit });
limit: 10 }
});
let search = $state('');
const debouncedSearch = debounced(async (searchValue: string) => {
users = await userService.list(searchValue, pagination);
}, 400);
async function deleteUser(user: User) { async function deleteUser(user: User) {
openConfirmDialog({ openConfirmDialog({
@@ -47,7 +39,7 @@
action: async () => { action: async () => {
try { try {
await userService.remove(user.id); await userService.remove(user.id);
users = await userService.list(search, pagination); users = await userService.list();
} catch (e) { } catch (e) {
axiosErrorToast(e); axiosErrorToast(e);
} }
@@ -67,39 +59,26 @@
} }
</script> </script>
<Input <AdvancedTable
type="search" items={users}
placeholder="Search users" {fetchItems}
bind:value={search} columns={[
on:input={(e) => debouncedSearch((e.target as HTMLInputElement).value)} 'First name',
/> 'Last name',
<Table.Root> 'Email',
<Table.Header> 'Username',
<Table.Row> 'Role',
<Table.Head class="hidden md:table-cell">First name</Table.Head> { label: 'Actions', hidden: true }
<Table.Head class="hidden md:table-cell">Last name</Table.Head> ]}
<Table.Head>Email</Table.Head> withoutSearch
<Table.Head>Username</Table.Head> >
<Table.Head class="hidden lg:table-cell">Role</Table.Head> {#snippet rows({ item })}
<Table.Head> <Table.Cell>{item.firstName}</Table.Cell>
<span class="sr-only">Actions</span> <Table.Cell>{item.lastName}</Table.Cell>
</Table.Head> <Table.Cell>{item.email}</Table.Cell>
</Table.Row> <Table.Cell>{item.username}</Table.Cell>
</Table.Header>
<Table.Body>
{#if users.data.length === 0}
<Table.Row>
<Table.Cell colspan={6} class="text-center">No users found</Table.Cell>
</Table.Row>
{:else}
{#each users.data as user}
<Table.Row>
<Table.Cell class="hidden md:table-cell">{user.firstName}</Table.Cell>
<Table.Cell class="hidden md:table-cell">{user.lastName}</Table.Cell>
<Table.Cell>{user.email}</Table.Cell>
<Table.Cell>{user.username}</Table.Cell>
<Table.Cell class="hidden lg:table-cell"> <Table.Cell class="hidden lg:table-cell">
<Badge variant="outline">{user.isAdmin ? 'Admin' : 'User'}</Badge> <Badge variant="outline">{item.isAdmin ? 'Admin' : 'User'}</Badge>
</Table.Cell> </Table.Cell>
<Table.Cell> <Table.Cell>
<DropdownMenu.Root> <DropdownMenu.Root>
@@ -110,62 +89,21 @@
</Button> </Button>
</DropdownMenu.Trigger> </DropdownMenu.Trigger>
<DropdownMenu.Content align="end"> <DropdownMenu.Content align="end">
<DropdownMenu.Item on:click={() => createOneTimeAccessToken(user.id)} <DropdownMenu.Item on:click={() => createOneTimeAccessToken(item.id)}
><LucideLink class="mr-2 h-4 w-4" />One-time link</DropdownMenu.Item ><LucideLink class="mr-2 h-4 w-4" />One-time link</DropdownMenu.Item
> >
<DropdownMenu.Item href="/settings/admin/users/{user.id}" <DropdownMenu.Item href="/settings/admin/users/{item.id}"
><LucidePencil class="mr-2 h-4 w-4" /> Edit</DropdownMenu.Item ><LucidePencil class="mr-2 h-4 w-4" /> Edit</DropdownMenu.Item
> >
<DropdownMenu.Item <DropdownMenu.Item
class="text-red-500 focus:!text-red-700" class="text-red-500 focus:!text-red-700"
on:click={() => deleteUser(user)} on:click={() => deleteUser(item)}
><LucideTrash class="mr-2 h-4 w-4" />Delete</DropdownMenu.Item ><LucideTrash class="mr-2 h-4 w-4" />Delete</DropdownMenu.Item
> >
</DropdownMenu.Content> </DropdownMenu.Content>
</DropdownMenu.Root> </DropdownMenu.Root>
</Table.Cell> </Table.Cell>
</Table.Row> {/snippet}
{/each} </AdvancedTable>
{/if}
</Table.Body>
</Table.Root>
{#if users?.data?.length ?? 0 > 0}
<Pagination.Root
class="mt-5"
count={users.pagination.totalItems}
perPage={pagination.limit}
onPageChange={async (p) =>
(users = await userService.list(search, {
page: p,
limit: pagination.limit
}))}
bind:page={users.pagination.currentPage}
let:pages
let:currentPage
>
<Pagination.Content class="flex justify-end">
<Pagination.Item>
<Pagination.PrevButton />
</Pagination.Item>
{#each pages as page (page.key)}
{#if page.type === 'ellipsis'}
<Pagination.Item>
<Pagination.Ellipsis />
</Pagination.Item>
{:else}
<Pagination.Item>
<Pagination.Link {page} isActive={users.pagination.currentPage === page.value}>
{page.value}
</Pagination.Link>
</Pagination.Item>
{/if}
{/each}
<Pagination.Item>
<Pagination.NextButton />
</Pagination.Item>
</Pagination.Content>
</Pagination.Root>
{/if}
<OneTimeLinkModal {oneTimeLink} /> <OneTimeLinkModal {oneTimeLink} />

View File

@@ -1,20 +1,22 @@
<script lang="ts"> <script lang="ts">
import AdvancedTable from '$lib/components/advanced-table.svelte';
import { Badge } from '$lib/components/ui/badge'; import { Badge } from '$lib/components/ui/badge';
import * as Pagination from '$lib/components/ui/pagination';
import * as Table from '$lib/components/ui/table'; import * as Table from '$lib/components/ui/table';
import AuditLogService from '$lib/services/audit-log-service'; import AuditLogService from '$lib/services/audit-log-service';
import type { AuditLog } from '$lib/types/audit-log.type'; import type { AuditLog } from '$lib/types/audit-log.type';
import type { Paginated, PaginationRequest } from '$lib/types/pagination.type'; import type { Paginated } from '$lib/types/pagination.type';
let { auditLogs: initialAuditLog }: { auditLogs: Paginated<AuditLog> } = $props(); let { auditLogs: initialAuditLog }: { auditLogs: Paginated<AuditLog> } = $props();
let auditLogs = $state<Paginated<AuditLog>>(initialAuditLog); let auditLogs = $state<Paginated<AuditLog>>(initialAuditLog);
const auditLogService = new AuditLogService(); const auditLogService = new AuditLogService();
let pagination = $state<PaginationRequest>({ async function fetchItems(search: string, page: number, limit: number) {
page: 1, return await auditLogService.list({
limit: 15 page,
limit
}); });
}
function toFriendlyEventString(event: string) { function toFriendlyEventString(event: string) {
const words = event.split('_'); const words = event.split('_');
@@ -25,73 +27,22 @@
} }
</script> </script>
<Table.Root> <AdvancedTable
<Table.Header class="whitespace-nowrap"> items={auditLogs}
<Table.Row> {fetchItems}
<Table.Head>Time</Table.Head> columns={['Time', 'Event', 'Approximate Location', 'IP Address', 'Device', 'Client']}
<Table.Head>Event</Table.Head> withoutSearch
<Table.Head>Approximate Location</Table.Head> >
<Table.Head>IP Address</Table.Head> {#snippet rows({ item })}
<Table.Head>Device</Table.Head> <Table.Cell>{new Date(item.createdAt).toLocaleString()}</Table.Cell>
<Table.Head>Client</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body class="whitespace-nowrap">
{#if auditLogs.data.length === 0}
<Table.Row>
<Table.Cell colspan={6} class="text-center">No logs found</Table.Cell>
</Table.Row>
{:else}
{#each auditLogs.data as auditLog}
<Table.Row>
<Table.Cell>{new Date(auditLog.createdAt).toLocaleString()}</Table.Cell>
<Table.Cell> <Table.Cell>
<Badge variant="outline">{toFriendlyEventString(auditLog.event)}</Badge> <Badge variant="outline">{toFriendlyEventString(item.event)}</Badge>
</Table.Cell> </Table.Cell>
<Table.Cell>{auditLog.city && auditLog.country ? `${auditLog.city}, ${auditLog.country}` : 'Unknown'}</Table.Cell> <Table.Cell
<Table.Cell>{auditLog.ipAddress}</Table.Cell> >{item.city && item.country ? `${item.city}, ${item.country}` : 'Unknown'}</Table.Cell
<Table.Cell>{auditLog.device}</Table.Cell>
<Table.Cell>{auditLog.data.clientName}</Table.Cell>
</Table.Row>
{/each}
{/if}
</Table.Body>
</Table.Root>
{#if auditLogs?.data?.length ?? 0 > 0}
<Pagination.Root
class="mt-5"
count={auditLogs.pagination.totalItems}
perPage={pagination.limit}
onPageChange={async (p) =>
(auditLogs = await auditLogService.list({
page: p,
limit: pagination.limit
}))}
bind:page={auditLogs.pagination.currentPage}
let:pages
let:currentPage
> >
<Pagination.Content class="flex justify-end"> <Table.Cell>{item.ipAddress}</Table.Cell>
<Pagination.Item> <Table.Cell>{item.device}</Table.Cell>
<Pagination.PrevButton /> <Table.Cell>{item.data.clientName}</Table.Cell>
</Pagination.Item> {/snippet}
{#each pages as page (page.key)} </AdvancedTable>
{#if page.type === 'ellipsis'}
<Pagination.Item>
<Pagination.Ellipsis />
</Pagination.Item>
{:else}
<Pagination.Item>
<Pagination.Link {page} isActive={auditLogs.pagination.currentPage === page.value}>
{page.value}
</Pagination.Link>
</Pagination.Item>
{/if}
{/each}
<Pagination.Item>
<Pagination.NextButton />
</Pagination.Item>
</Pagination.Content>
</Pagination.Root>
{/if}