Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base
feat: add users management
Hugo Richard3c2bc53e4cb3
diff --git a/apps/chat/app/components/ChatModeTabs.vue b/apps/chat/app/components/ChatModeTabs.vueindex fe2a820..241cefd 100644--- a/apps/chat/app/components/ChatModeTabs.vue+++ b/apps/chat/app/components/ChatModeTabs.vue@@ -50,11 +50,11 @@ function onUpdate(value: string) {v-for="item in items":key="item.value"ref="tabRefs"- class="relative flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs transition-colors"+ class="relative flex items-center gap-0.5 px-2 py-1 rounded-md text-xs transition-colors":class="mode === item.value ? 'text-highlighted' : 'text-muted hover:text-highlighted'"@click="onUpdate(item.value)">- <UIcon :name="item.icon" class="size-3" />+ <UIcon :name="item.icon" class="size-4" />{{ item.label }}</button></div>diff --git a/apps/chat/app/components/InstallBotCard.vue b/apps/chat/app/components/InstallBotCard.vueindex 26a1921..038396f 100644--- a/apps/chat/app/components/InstallBotCard.vue+++ b/apps/chat/app/components/InstallBotCard.vue@@ -64,7 +64,7 @@ function onMouseLeave() {class="holo-border-shine":style="{opacity: isHovering ? 1 : 0.3,- background: `radial-gradient(circle at ${shineX}% ${shineY}%, white 0%, oklch(90% 0 0 / 0.5) 30%, transparent 70%)`,+ background: `radial-gradient(circle at ${shineX}% ${shineY}%, var(--holo-border-center) 0%, var(--holo-border-mid) 30%, transparent 70%)`,}"/>@@ -73,7 +73,7 @@ function onMouseLeave() {class="holo-shine":style="{opacity: isHovering ? 1 : 0,- background: `radial-gradient(circle at ${shineX}% ${shineY}%, oklch(100% 0 0 / 0.12) 0%, oklch(95% 0 0 / 0.06) 35%, transparent 70%)`,+ background: `radial-gradient(circle at ${shineX}% ${shineY}%, var(--holo-shine-center) 0%, var(--holo-shine-mid) 35%, transparent 70%)`,}"/>@@ -125,11 +125,25 @@ function onMouseLeave() {<style scoped>.holo-border {- background: oklch(30% 0 0 / 0.6);+ --holo-border-center: oklch(98% 0 0);+ --holo-border-mid: oklch(90% 0 0 / 0.4);+ --holo-shine-center: oklch(100% 0 0 / 0.6);+ --holo-shine-mid: oklch(98% 0 0 / 0.3);++ background: oklch(82% 0 0 / 0.6);transform-style: preserve-3d;will-change: transform;}+:root.dark .holo-border {+ --holo-border-center: white;+ --holo-border-mid: oklch(90% 0 0 / 0.5);+ --holo-shine-center: oklch(100% 0 0 / 0.12);+ --holo-shine-mid: oklch(95% 0 0 / 0.06);++ background: oklch(30% 0 0 / 0.6);+}+.holo-border-shine {position: absolute;inset: 0;diff --git a/apps/chat/app/layouts/default.vue b/apps/chat/app/layouts/default.vueindex d97f03e..62470a1 100644--- a/apps/chat/app/layouts/default.vue+++ b/apps/chat/app/layouts/default.vue@@ -89,6 +89,7 @@ const adminNavigation = [{ label: 'Statistics', icon: 'i-custom-chart', to: '/admin/stats' },{ label: 'Logs', icon: 'i-custom-terminal', to: '/admin/logs' },{ label: 'API Keys', icon: 'i-custom-api-access', to: '/admin/api-keys' },+ { label: 'Users', icon: 'i-lucide-users', to: '/admin/users' },],[{ label: 'Documentation', type: 'label' as const },@@ -219,13 +220,16 @@ defineShortcuts({<template v-if="!collapsed"><UserStats v-if="loggedIn" />- <UButton- label="New chat"- variant="soft"- block+ <NuxtLinkto="/"+ class="block rounded-md p-px bg-linear-to-b from-[#e0dfe3] to-[#d8d7dc] dark:from-[#353539] dark:to-[#2a2a2e] shadow-[0_1px_2px_rgba(0,0,0,0.04)] dark:shadow-[0_1px_2px_rgba(0,0,0,0.3)] hover:brightness-110 active:scale-[0.98] transition-[filter,transform] duration-150"@click="open = false"- />+ >+ <div class="flex items-center gap-1.5 rounded-[calc(var(--radius-md)-1px)] px-2.5 py-1.5 text-sm text-highlighted bg-linear-to-b from-[#f8f7fa] to-[#f2f1f5] dark:from-[#222226] dark:to-[#1f1f23]">+ <UIcon name="i-lucide-plus" class="size-3.5 shrink-0 text-muted" />+ New chat+ </div>+ </NuxtLink></template></template></template>@@ -258,13 +262,15 @@ defineShortcuts({<template v-else><template v-if="collapsed">- <UButton- icon="i-lucide-plus"- variant="soft"- block+ <NuxtLinkto="/"+ class="flex items-center justify-center rounded-md p-px bg-linear-to-b from-[#e0dfe3] to-[#d8d7dc] dark:from-[#353539] dark:to-[#2a2a2e] shadow-[0_1px_2px_rgba(0,0,0,0.04)] dark:shadow-[0_1px_2px_rgba(0,0,0,0.3)] hover:brightness-110 active:scale-[0.98] transition-[filter,transform] duration-150"@click="open = false"- />+ >+ <div class="flex items-center justify-center rounded-[calc(var(--radius-md)-1px)] p-1.5 text-highlighted bg-linear-to-b from-[#f8f7fa] to-[#f2f1f5] dark:from-[#222226] dark:to-[#1f1f23]">+ <UIcon name="i-lucide-plus" class="size-4" />+ </div>+ </NuxtLink><UserMenu v-if="loggedIn" collapsed /><UTooltip v-else text="Sign in"><UButtondiff --git a/apps/chat/app/pages/admin/users.vue b/apps/chat/app/pages/admin/users.vuenew file mode 100644index 0000000..870967c--- /dev/null+++ b/apps/chat/app/pages/admin/users.vue@@ -0,0 +1,260 @@+<script setup lang="ts">+useSeoMeta({ title: 'Users - Admin' })++type UserRole = 'user' | 'admin'++interface AdminUserRow {+ id: string+ name: string | null+ email: string | null+ image: string | null+ role: UserRole+ createdAt: string+ chatCount: number+ messageCount: number+ lastSeenAt: string | null+}++const toast = useToast()+const { user: currentUser } = useUserSession()++const searchQuery = ref('')+const roleFilter = ref<'all' | UserRole>('all')+const savingUserId = ref<string | null>(null)+const draftRoles = ref<Record<string, UserRole>>({})++const roleOptions = [+ { label: 'User', value: 'user' },+ { label: 'Admin', value: 'admin' },+] as const++const filterOptions = [+ { label: 'All roles', value: 'all' },+ { label: 'Admins', value: 'admin' },+ { label: 'Users', value: 'user' },+] as const++const { data: users, refresh, status } = useLazyFetch<AdminUserRow[]>('/api/admin/users')++watch(users, (rows) => {+ if (!rows) return+ draftRoles.value = Object.fromEntries(rows.map(row => [row.id, row.role]))+}, { immediate: true })++const filteredUsers = computed(() => {+ if (!users.value) return []++ const query = searchQuery.value.trim().toLowerCase()++ return users.value.filter((user) => {+ if (roleFilter.value !== 'all' && user.role !== roleFilter.value) {+ return false+ }++ if (!query) return true++ const name = user.name?.toLowerCase() ?? ''+ const email = user.email?.toLowerCase() ?? ''+ return name.includes(query) || email.includes(query)+ })+})++function formatDate(date: string | null): string {+ if (!date) return 'Never'+ return new Date(date).toLocaleDateString()+}++function isCurrentUser(userId: string): boolean {+ return currentUser.value?.id === userId+}++async function saveRole(row: AdminUserRow) {+ const nextRole = draftRoles.value[row.id]+ if (!nextRole || nextRole === row.role) return++ if (isCurrentUser(row.id) && nextRole !== 'admin') {+ toast.add({+ title: 'Not allowed',+ description: 'You cannot remove your own admin role.',+ color: 'error',+ icon: 'i-lucide-alert-circle',+ })+ draftRoles.value[row.id] = row.role+ return+ }++ savingUserId.value = row.id+ try {+ await $fetch(`/api/admin/users/${row.id}`, {+ method: 'PATCH',+ body: { role: nextRole },+ })+ await refresh()+ toast.add({+ title: 'Role updated',+ icon: 'i-lucide-check',+ })+ } catch (error: any) {+ draftRoles.value[row.id] = row.role+ toast.add({+ title: 'Error',+ description: error?.data?.message || error?.message || 'Failed to update role',+ color: 'error',+ icon: 'i-lucide-alert-circle',+ })+ } finally {+ savingUserId.value = null+ }+}+</script>++<template>+ <div class="px-6 py-8 max-w-4xl mx-auto w-full">+ <header class="mb-8">+ <h1 class="text-lg font-medium text-highlighted mb-1 font-pixel tracking-wide">+ Users+ </h1>+ <p class="text-sm text-muted max-w-lg">+ Manage user access and roles across the platform.+ </p>+ </header>++ <div class="flex flex-col gap-6">+ <section>+ <h2 class="text-[10px] text-muted uppercase tracking-wide mb-3 font-pixel">+ Directory+ </h2>++ <div class="rounded-lg border border-default p-3 mb-3">+ <div class="flex flex-wrap items-center gap-2">+ <UInput+ v-model="searchQuery"+ icon="i-lucide-search"+ placeholder="Search by name or email"+ size="xs"+ class="w-full sm:w-72"+ />+ <USelect+ v-model="roleFilter"+ :items="filterOptions"+ value-key="value"+ size="xs"+ class="w-36"+ />+ <UButton+ color="neutral"+ variant="ghost"+ icon="i-lucide-refresh-cw"+ size="xs"+ :loading="status === 'pending'"+ @click="refresh()"+ >+ Refresh+ </UButton>+ </div>+ </div>++ <div class="rounded-lg border border-default overflow-hidden">+ <div v-if="status === 'pending' && !users" class="px-4 py-3.5">+ <div v-for="i in 3" :key="i" class="flex items-center justify-between" :class="i > 1 && 'mt-3 pt-3 border-t border-default'">+ <div class="flex items-center gap-3">+ <USkeleton class="size-8 rounded-full" />+ <div>+ <USkeleton class="h-4 w-32 mb-1" />+ <USkeleton class="h-3 w-48" />+ </div>+ </div>+ <USkeleton class="h-8 w-36 rounded-md" />+ </div>+ </div>++ <table v-else-if="filteredUsers.length > 0" class="w-full text-sm">+ <thead class="bg-elevated/50 border-b border-default">+ <tr class="text-xs text-muted">+ <th class="text-left font-medium px-4 py-2.5">+ User+ </th>+ <th class="text-right font-medium px-3 py-2.5">+ Chats+ </th>+ <th class="text-right font-medium px-3 py-2.5">+ Messages+ </th>+ <th class="text-left font-medium px-3 py-2.5">+ Last active+ </th>+ <th class="text-left font-medium px-4 py-2.5">+ Role+ </th>+ </tr>+ </thead>+ <tbody class="divide-y divide-default">+ <tr+ v-for="row in filteredUsers"+ :key="row.id"+ class="hover:bg-elevated/30"+ >+ <td class="px-4 py-2.5">+ <div class="flex items-center gap-3 min-w-0">+ <UAvatar :src="row.image || undefined" :alt="row.name || row.email || undefined" size="xs" />+ <div class="min-w-0">+ <div class="flex items-center gap-2">+ <p class="text-highlighted truncate">+ {{ row.name || 'Unnamed user' }}+ </p>+ <UBadge+ v-if="isCurrentUser(row.id)"+ label="You"+ size="xs"+ color="neutral"+ variant="subtle"+ />+ </div>+ <p class="text-xs text-muted truncate">+ {{ row.email || 'No email' }} · Joined {{ formatDate(row.createdAt) }}+ </p>+ </div>+ </div>+ </td>+ <td class="px-3 py-2.5 text-right text-muted tabular-nums">+ {{ row.chatCount.toLocaleString() }}+ </td>+ <td class="px-3 py-2.5 text-right text-muted tabular-nums">+ {{ row.messageCount.toLocaleString() }}+ </td>+ <td class="px-3 py-2.5 text-muted">+ {{ formatDate(row.lastSeenAt) }}+ </td>+ <td class="px-4 py-2.5">+ <div class="flex items-center gap-2">+ <USelect+ v-model="draftRoles[row.id]"+ :items="roleOptions"+ value-key="value"+ class="w-28"+ size="xs"+ :disabled="savingUserId === row.id || isCurrentUser(row.id)"+ />+ <UButton+ label="Save"+ size="xs"+ :disabled="draftRoles[row.id] === row.role || isCurrentUser(row.id)"+ :loading="savingUserId === row.id"+ @click="saveRole(row)"+ />+ </div>+ </td>+ </tr>+ </tbody>+ </table>++ <div v-else class="px-4 py-10 text-center">+ <p class="text-sm text-muted">+ No users match your current filters.+ </p>+ </div>+ </div>+ </section>+ </div>+ </div>+</template>diff --git a/apps/chat/app/pages/index.vue b/apps/chat/app/pages/index.vueindex 78e2ddc..89b6d4f 100644--- a/apps/chat/app/pages/index.vue+++ b/apps/chat/app/pages/index.vue@@ -118,7 +118,7 @@ const quickChats = computed(() => mode.value === 'admin' ? adminQuickChats : cha<template #body><DragDropOverlay :show="isDragging" /><UContainer ref="dropzoneRef" class="flex-1 flex flex-col justify-center gap-4 sm:gap-6 py-8">- <h1 class="text-3xl sm:text-4xl text-highlighted font-bold font-pixel tracking-wide">+ <h1 class="text-3xl sm:text-4xl text-highlighted font-semibold tracking-wide">How can I help you today?</h1>diff --git a/apps/chat/server/api/admin/users.get.ts b/apps/chat/server/api/admin/users.get.tsnew file mode 100644index 0000000..88c3864--- /dev/null+++ b/apps/chat/server/api/admin/users.get.ts@@ -0,0 +1,73 @@+import { db, schema } from '@nuxthub/db'+import { desc } from 'drizzle-orm'++export default defineEventHandler(async (event) => {+ await requireAdmin(event)++ const [users, chats, messages] = await Promise.all([+ db+ .select({+ id: schema.user.id,+ name: schema.user.name,+ email: schema.user.email,+ image: schema.user.image,+ role: schema.user.role,+ createdAt: schema.user.createdAt,+ })+ .from(schema.user)+ .orderBy(desc(schema.user.createdAt)),+ db+ .select({+ id: schema.chats.id,+ userId: schema.chats.userId,+ createdAt: schema.chats.createdAt,+ })+ .from(schema.chats),+ db+ .select({+ chatId: schema.messages.chatId,+ createdAt: schema.messages.createdAt,+ })+ .from(schema.messages),+ ])++ const chatOwnerById = new Map<string, string>()+ const chatCountByUserId = new Map<string, number>()+ const lastSeenByUserId = new Map<string, Date>()++ for (const chat of chats) {+ chatOwnerById.set(chat.id, chat.userId)+ chatCountByUserId.set(chat.userId, (chatCountByUserId.get(chat.userId) ?? 0) + 1)++ const previousLastSeen = lastSeenByUserId.get(chat.userId)+ if (!previousLastSeen || previousLastSeen < chat.createdAt) {+ lastSeenByUserId.set(chat.userId, chat.createdAt)+ }+ }++ const messageCountByUserId = new Map<string, number>()++ for (const message of messages) {+ const userId = chatOwnerById.get(message.chatId)+ if (!userId) continue++ messageCountByUserId.set(userId, (messageCountByUserId.get(userId) ?? 0) + 1)++ const previousLastSeen = lastSeenByUserId.get(userId)+ if (!previousLastSeen || previousLastSeen < message.createdAt) {+ lastSeenByUserId.set(userId, message.createdAt)+ }+ }++ return users.map(user => ({+ id: user.id,+ name: user.name,+ email: user.email,+ image: user.image,+ role: user.role ?? 'user',+ createdAt: user.createdAt,+ chatCount: chatCountByUserId.get(user.id) ?? 0,+ messageCount: messageCountByUserId.get(user.id) ?? 0,+ lastSeenAt: lastSeenByUserId.get(user.id) ?? null,+ }))+})diff --git a/apps/chat/server/api/admin/users/[id].patch.ts b/apps/chat/server/api/admin/users/[id].patch.tsnew file mode 100644index 0000000..cfbffeb--- /dev/null+++ b/apps/chat/server/api/admin/users/[id].patch.ts@@ -0,0 +1,39 @@+import { db, schema } from '@nuxthub/db'+import { eq } from 'drizzle-orm'+import { z } from 'zod'++const bodySchema = z.object({+ role: z.enum(['user', 'admin']),+})++export default defineEventHandler(async (event) => {+ const { user: currentUser } = await requireAdmin(event)++ const id = getRouterParam(event, 'id')+ if (!id) {+ throw createError({ statusCode: 400, message: 'Missing user ID' })+ }++ const body = await readValidatedBody(event, bodySchema.parse)++ if (id === currentUser.id && body.role !== 'admin') {+ throw createError({ statusCode: 400, message: 'You cannot remove your own admin role' })+ }++ const [existingUser] = await db+ .select({ id: schema.user.id })+ .from(schema.user)+ .where(eq(schema.user.id, id))+ .limit(1)++ if (!existingUser) {+ throw createError({ statusCode: 404, message: 'User not found' })+ }++ await db+ .update(schema.user)+ .set({ role: body.role })+ .where(eq(schema.user.id, id))++ return { success: true }+})