Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(admin): user listing and search (#692)

Corentin Thomasset7a4a3d4c5b46
diff --git a/apps/papra-client/src/modules/admin/admin.routes.tsx b/apps/papra-client/src/modules/admin/admin.routes.tsx
index acd3f9eb..0ebdfc57 100644
--- a/apps/papra-client/src/modules/admin/admin.routes.tsx
+++ b/apps/papra-client/src/modules/admin/admin.routes.tsx
@@ -13,7 +13,11 @@ export const adminRoutes: RouteDefinition = {
},
{
path: '/users',
- component: lazy(() => import('./pages/list-users.page')),
+ component: lazy(() => import('./users/pages/list-users.page')),
+ },
+ {
+ path: '/users/:userId',
+ component: lazy(() => import('./users/pages/user-detail.page')),
},
{
path: '/analytics',
diff --git a/apps/papra-client/src/modules/admin/pages/list-users.page.tsx b/apps/papra-client/src/modules/admin/pages/list-users.page.tsx
deleted file mode 100644
index 1546fd04..00000000
--- a/apps/papra-client/src/modules/admin/pages/list-users.page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Component } from 'solid-js';
-
-export const AdminListUsersPage: Component = () => {
- return (
- <div class="p-6 text-muted-foreground">
- Not implemented yet.
- </div>
- );
-};
-
-export default AdminListUsersPage;
diff --git a/apps/papra-client/src/modules/admin/users/pages/list-users.page.tsx b/apps/papra-client/src/modules/admin/users/pages/list-users.page.tsx
new file mode 100644
index 00000000..74b5a950
--- /dev/null
+++ b/apps/papra-client/src/modules/admin/users/pages/list-users.page.tsx
@@ -0,0 +1,243 @@
+import type { Component } from 'solid-js';
+import { A } from '@solidjs/router';
+import { useQuery } from '@tanstack/solid-query';
+import { createSolidTable, flexRender, getCoreRowModel, getPaginationRowModel } from '@tanstack/solid-table';
+import { createSignal, For, Show } from 'solid-js';
+import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
+import { Badge } from '@/modules/ui/components/badge';
+import { Button } from '@/modules/ui/components/button';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
+import { TextField, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { listUsers } from '../users.services';
+
+export const AdminListUsersPage: Component = () => {
+ const [search, setSearch] = createSignal('');
+ const [pagination, setPagination] = createSignal({ pageIndex: 0, pageSize: 25 });
+
+ const query = useQuery(() => ({
+ queryKey: ['admin', 'users', search(), pagination()],
+ queryFn: () => listUsers({
+ search: search() || undefined,
+ ...pagination(),
+ }),
+ }));
+
+ const table = createSolidTable({
+ get data() {
+ return query.data?.users ?? [];
+ },
+ columns: [
+ {
+ header: 'ID',
+ accessorKey: 'id',
+ cell: data => (
+ <A
+ href={`/admin/users/${data.getValue<string>()}`}
+ class="font-mono hover:underline text-primary"
+ >
+ {data.getValue<string>()}
+ </A>
+ ),
+ },
+ {
+ header: 'Email',
+ accessorKey: 'email',
+ cell: data => (
+ <div class="font-medium">
+ {data.getValue<string>()}
+ </div>
+ ),
+ },
+ {
+ header: 'Name',
+ accessorKey: 'name',
+ cell: data => (
+ <div class="text-muted-foreground">
+ {data.getValue<string | null>() || '-'}
+ </div>
+ ),
+ },
+ {
+ header: 'Status',
+ accessorKey: 'emailVerified',
+ cell: data => (
+ <Badge variant={data.getValue<boolean>() ? 'default' : 'outline'}>
+ {data.getValue<boolean>() ? 'Verified' : 'Unverified'}
+ </Badge>
+ ),
+ },
+ {
+ header: 'Orgs',
+ accessorKey: 'organizationCount',
+ cell: data => (
+ <div class="text-center">
+ {data.getValue<number>()}
+ </div>
+ ),
+ },
+ {
+ header: 'Created',
+ accessorKey: 'createdAt',
+ cell: data => <RelativeTime class="text-muted-foreground text-sm" date={new Date(data.getValue<string>())} />,
+ },
+ ],
+ get rowCount() {
+ return query.data?.totalCount ?? 0;
+ },
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onPaginationChange: setPagination,
+ state: {
+ get pagination() {
+ return pagination();
+ },
+ },
+ manualPagination: true,
+ });
+
+ const handleSearch = (e: Event) => {
+ const target = e.target as HTMLInputElement;
+ setSearch(target.value);
+ setPagination({ pageIndex: 0, pageSize: pagination().pageSize });
+ };
+
+ return (
+ <div class="p-6 mt-4">
+ <div class="border-b mb-6 pb-4">
+ <h1 class="text-xl font-bold mb-1">
+ User Management
+ </h1>
+ <p class="text-sm text-muted-foreground">
+ Manage and view all users in the system
+ </p>
+ </div>
+
+ <div class="mb-4">
+ <TextFieldRoot class="max-w-sm">
+ <TextField
+ type="text"
+ placeholder="Search by name, email, or ID..."
+ value={search()}
+ onInput={handleSearch}
+ />
+ </TextFieldRoot>
+ </div>
+
+ <Show
+ when={!query.isLoading}
+ fallback={<div class="text-center py-8 text-muted-foreground">Loading users...</div>}
+ >
+ <Show
+ when={(query.data?.users.length ?? 0) > 0}
+ fallback={(
+ <div class="text-center py-8 text-muted-foreground">
+ {search() ? 'No users found matching your search.' : 'No users found.'}
+ </div>
+ )}
+ >
+ <div class="border-y">
+ <Table>
+ <TableHeader>
+ <For each={table.getHeaderGroups()}>
+ {headerGroup => (
+ <TableRow>
+ <For each={headerGroup.headers}>
+ {header => (
+ <TableHead>
+ {flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ )}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </TableHeader>
+ <TableBody>
+ <For each={table.getRowModel().rows}>
+ {row => (
+ <TableRow>
+ <For each={row.getVisibleCells()}>
+ {cell => (
+ <TableCell>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ )}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </TableBody>
+ </Table>
+ </div>
+
+ <div class="flex items-center justify-between mt-4">
+ <div class="text-sm text-muted-foreground">
+ Showing
+ {' '}
+ {table.getState().pagination.pageIndex * table.getState().pagination.pageSize + 1}
+ {' '}
+ to
+ {' '}
+ {Math.min((table.getState().pagination.pageIndex + 1) * table.getState().pagination.pageSize, query.data?.totalCount ?? 0)}
+ {' '}
+ of
+ {' '}
+ {query.data?.totalCount ?? 0}
+ {' '}
+ users
+ </div>
+ <div class="flex items-center space-x-2">
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.setPageIndex(0)}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <div class="size-4 i-tabler-chevrons-left" />
+ </Button>
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <div class="size-4 i-tabler-chevron-left" />
+ </Button>
+ <div class="text-sm whitespace-nowrap">
+ Page
+ {' '}
+ {table.getState().pagination.pageIndex + 1}
+ {' '}
+ of
+ {' '}
+ {table.getPageCount()}
+ </div>
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ <div class="size-4 i-tabler-chevron-right" />
+ </Button>
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}
+ disabled={!table.getCanNextPage()}
+ >
+ <div class="size-4 i-tabler-chevrons-right" />
+ </Button>
+ </div>
+ </div>
+ </Show>
+ </Show>
+ </div>
+ );
+};
+
+export default AdminListUsersPage;
diff --git a/apps/papra-client/src/modules/admin/users/pages/user-detail.page.tsx b/apps/papra-client/src/modules/admin/users/pages/user-detail.page.tsx
new file mode 100644
index 00000000..64c2579e
--- /dev/null
+++ b/apps/papra-client/src/modules/admin/users/pages/user-detail.page.tsx
@@ -0,0 +1,154 @@
+import type { Component } from 'solid-js';
+import { A, useParams } from '@solidjs/router';
+import { useQuery } from '@tanstack/solid-query';
+import { For, Show } from 'solid-js';
+import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
+import { Badge } from '@/modules/ui/components/badge';
+import { Button } from '@/modules/ui/components/button';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/modules/ui/components/card';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
+import { getUserDetail } from '../users.services';
+
+export const AdminUserDetailPage: Component = () => {
+ const params = useParams<{ userId: string }>();
+
+ const query = useQuery(() => ({
+ queryKey: ['admin', 'users', params.userId],
+ queryFn: () => getUserDetail({ userId: params.userId }),
+ }));
+
+ return (
+ <div class="p-6 max-w-screen-lg mx-auto mt-4">
+ <div class="mb-6">
+ <Button as={A} href="/admin/users" variant="ghost" size="sm" class="mb-4">
+ <div class="i-tabler-arrow-left size-4 mr-2" />
+ Back to Users
+ </Button>
+
+ <Show
+ when={!query.isLoading && query.data}
+ fallback={<div class="text-center py-8 text-muted-foreground">Loading user details...</div>}
+ >
+ {data => (
+ <div class="space-y-6">
+ <div class="border-b pb-4">
+ <h1 class="text-2xl font-bold flex items-center gap-3">
+ {data().user.name || 'Unnamed User'}
+ </h1>
+ <p class="text-muted-foreground mt-1">{data().user.email}</p>
+ </div>
+
+ <div class="grid gap-6 md:grid-cols-2">
+ <Card>
+ <CardHeader>
+ <CardTitle>User Information</CardTitle>
+ <CardDescription>Basic user details and account information</CardDescription>
+ </CardHeader>
+ <CardContent class="space-y-3">
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">User ID</span>
+ <span class="font-mono text-xs">{data().user.id}</span>
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Email</span>
+ <span class="text-sm font-medium">{data().user.email}</span>
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Name</span>
+ <span class="text-sm">{data().user.name || '-'}</span>
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Email Verified</span>
+ <Badge variant={data().user.emailVerified ? 'default' : 'outline'} class="text-xs">
+ {data().user.emailVerified ? 'Yes' : 'No'}
+ </Badge>
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Max Organizations</span>
+ <span class="text-sm">{data().user.maxOrganizationCount ?? 'Unlimited'}</span>
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Created</span>
+ <RelativeTime class="text-sm" date={new Date(data().user.createdAt)} />
+ </div>
+ <div class="flex justify-between items-start">
+ <span class="text-sm text-muted-foreground">Last Updated</span>
+ <RelativeTime class="text-sm" date={new Date(data().user.updatedAt)} />
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Roles & Permissions</CardTitle>
+ <CardDescription>User roles and access levels</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Show
+ when={data().roles.length > 0}
+ fallback={<p class="text-sm text-muted-foreground">No roles assigned</p>}
+ >
+ <div class="flex flex-wrap gap-2">
+ <For each={data().roles}>
+ {role => (
+ <Badge variant="secondary" class="font-mono">
+ {role}
+ </Badge>
+ )}
+ </For>
+ </div>
+ </Show>
+ </CardContent>
+ </Card>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Organizations (
+ {data().organizations.length}
+ )
+ </CardTitle>
+ <CardDescription>Organizations this user belongs to</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Show
+ when={data().organizations.length > 0}
+ fallback={<p class="text-sm text-muted-foreground">Not a member of any organizations</p>}
+ >
+ <div class="rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>ID</TableHead>
+ <TableHead>Name</TableHead>
+ <TableHead>Created</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <For each={data().organizations}>
+ {org => (
+ <TableRow>
+ <TableCell>{org.id}</TableCell>
+ <TableCell class="font-medium">{org.name}</TableCell>
+ <TableCell>
+ <RelativeTime class="text-muted-foreground text-sm" date={new Date(org.createdAt)} />
+ </TableCell>
+ </TableRow>
+ )}
+ </For>
+ </TableBody>
+ </Table>
+ </div>
+ </Show>
+ </CardContent>
+ </Card>
+ </div>
+ )}
+ </Show>
+ </div>
+ </div>
+ );
+};
+
+export default AdminUserDetailPage;
diff --git a/apps/papra-client/src/modules/admin/users/users.services.ts b/apps/papra-client/src/modules/admin/users/users.services.ts
new file mode 100644
index 00000000..83d38eb9
--- /dev/null
+++ b/apps/papra-client/src/modules/admin/users/users.services.ts
@@ -0,0 +1,33 @@
+import type { Organization } from '@/modules/organizations/organizations.types';
+import type { User } from '@/modules/users/users.types';
+import { apiClient } from '@/modules/shared/http/api-client';
+
+export type UserWithOrganizationCount = User & { organizationCount: number };
+
+export async function listUsers({ search, pageIndex = 0, pageSize = 25 }: { search?: string; pageIndex?: number; pageSize?: number }) {
+ const { totalCount, users } = await apiClient<{
+ users: UserWithOrganizationCount[];
+ totalCount: number;
+ pageIndex: number;
+ pageSize: number;
+ }>({
+ method: 'GET',
+ path: '/api/admin/users',
+ query: { search, pageIndex, pageSize },
+ });
+
+ return { pageIndex, pageSize, totalCount, users };
+}
+
+export async function getUserDetail({ userId }: { userId: string }) {
+ const { organizations, roles, user } = await apiClient<{
+ user: User;
+ organizations: Organization[];
+ roles: string[];
+ }>({
+ method: 'GET',
+ path: `/api/admin/users/${userId}`,
+ });
+
+ return { organizations, roles, user };
+}
diff --git a/apps/papra-client/src/modules/users/users.types.ts b/apps/papra-client/src/modules/users/users.types.ts
index 5d01f53b..b2fba5a3 100644
--- a/apps/papra-client/src/modules/users/users.types.ts
+++ b/apps/papra-client/src/modules/users/users.types.ts
@@ -1,21 +1,13 @@
-export type UserMe = {
- id: string;
- email: string;
- planId: string;
- name: string;
- permissions: string[];
-};
-
export type User = {
id: string;
email: string;
name: string;
createdAt: Date;
updatedAt: Date;
- provider: string;
- maxApiKeys: number;
- apiKeysCount: number;
- isEmailVerified: boolean;
- customerId: string | null;
- planId: string;
+ emailVerified: boolean;
+ maxOrganizationCount: number | null;
+};
+
+export type UserMe = User & {
+ permissions: string[];
};
diff --git a/apps/papra-server/src/modules/admin/admin.routes.ts b/apps/papra-server/src/modules/admin/admin.routes.ts
index d9c4f743..1d34a518 100644
--- a/apps/papra-server/src/modules/admin/admin.routes.ts
+++ b/apps/papra-server/src/modules/admin/admin.routes.ts
@@ -1,6 +1,8 @@
import type { RouteDefinitionContext } from '../app/server.types';
import { registerAnalyticsRoutes } from './analytics/analytics.routes';
+import { registerUserManagementRoutes } from './users/users.routes';
export function registerAdminRoutes(context: RouteDefinitionContext) {
registerAnalyticsRoutes(context);
+ registerUserManagementRoutes(context);
}
diff --git a/apps/papra-server/src/modules/admin/users/e2e/users.e2e.test.ts b/apps/papra-server/src/modules/admin/users/e2e/users.e2e.test.ts
new file mode 100644
index 00000000..144f36df
--- /dev/null
+++ b/apps/papra-server/src/modules/admin/users/e2e/users.e2e.test.ts
@@ -0,0 +1,236 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../../app/database/database.test-utils';
+import { createServer } from '../../../app/server';
+import { createTestServerDependencies } from '../../../app/server.test-utils';
+import { overrideConfig } from '../../../config/config.test-utils';
+
+describe('admin users routes - permission protection', () => {
+ describe('get /api/admin/users', () => {
+ test('when the user has the VIEW_USERS permission, the request succeeds', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_admin', email: '[email protected]', name: 'Admin User' },
+ { id: 'usr_regular', email: '[email protected]', name: 'Regular User' },
+ ],
+ userRoles: [
+ { userId: 'usr_admin', role: 'admin' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users',
+ { method: 'GET' },
+ { loggedInUserId: 'usr_admin' },
+ );
+
+ expect(response.status).to.eql(200);
+ const body = (await response.json()) as { users: unknown; totalCount: number };
+ expect(body.users).to.have.length(2);
+ expect(body.totalCount).to.eql(2);
+ });
+
+ test('when using search parameter, it filters by email', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_admin', email: '[email protected]', name: 'Admin User' },
+ { id: 'usr_regular', email: '[email protected]', name: 'Regular User' },
+ ],
+ userRoles: [
+ { userId: 'usr_admin', role: 'admin' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users?search=admin',
+ { method: 'GET' },
+ { loggedInUserId: 'usr_admin' },
+ );
+
+ expect(response.status).to.eql(200);
+ const body = await response.json() as { users: { email: string }[]; totalCount: number };
+ expect(body.users).to.have.length(1);
+ expect(body.users[0]?.email).to.eql('[email protected]');
+ });
+
+ test('when using search parameter with user ID, it returns exact match', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_admin', email: '[email protected]', name: 'Admin User' },
+ { id: 'usr_abcdefghijklmnopqrstuvwx', email: '[email protected]', name: 'Regular User' },
+ ],
+ userRoles: [
+ { userId: 'usr_admin', role: 'admin' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users?search=usr_abcdefghijklmnopqrstuvwx',
+ { method: 'GET' },
+ { loggedInUserId: 'usr_admin' },
+ );
+
+ expect(response.status).to.eql(200);
+ const body = await response.json() as { users: { id: string }[]; totalCount: number };
+ expect(body.users).to.have.length(1);
+ expect(body.users[0]?.id).to.eql('usr_abcdefghijklmnopqrstuvwx');
+ });
+
+ test('when the user does not have the VIEW_USERS permission, a 401 error is returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_regular', email: '[email protected]' }],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users',
+ { method: 'GET' },
+ { loggedInUserId: 'usr_regular' },
+ );
+
+ expect(response.status).to.eql(401);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+
+ test('when the user is not authenticated, a 401 error is returned', async () => {
+ const { db } = await createInMemoryDatabase();
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users',
+ { method: 'GET' },
+ );
+
+ expect(response.status).to.eql(401);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+ });
+
+ describe('get /api/admin/users/:userId', () => {
+ test('when the user has the VIEW_USERS permission, the request succeeds and returns user details', async () => {
+ const targetUserId = 'usr_123456789012345678901234';
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_admin', email: '[email protected]', name: 'Admin User' },
+ { id: targetUserId, email: '[email protected]', name: 'Target User' },
+ ],
+ userRoles: [
+ { userId: 'usr_admin', role: 'admin' },
+ ],
+ organizations: [
+ { id: 'org_1', name: 'Organization 1' },
+ ],
+ organizationMembers: [
+ { userId: targetUserId, organizationId: 'org_1', role: 'owner' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ `/api/admin/users/${targetUserId}`,
+ { method: 'GET' },
+ { loggedInUserId: 'usr_admin' },
+ );
+
+ expect(response.status).to.eql(200);
+ const body = await response.json() as {
+ user: { id: string; email: string };
+ organizations: { id: string; name: string }[];
+ roles: string[];
+ };
+ expect(body.user.id).to.eql(targetUserId);
+ expect(body.user.email).to.eql('[email protected]');
+ expect(body.organizations).to.have.length(1);
+ expect(body.organizations[0]?.id).to.eql('org_1');
+ expect(body.roles).to.be.an('array');
+ });
+
+ test('when the user does not exist, a 404 error is returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_admin', email: '[email protected]', name: 'Admin User' },
+ ],
+ userRoles: [
+ { userId: 'usr_admin', role: 'admin' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users/usr_999999999999999999999999',
+ { method: 'GET' },
+ { loggedInUserId: 'usr_admin' },
+ );
+
+ expect(response.status).to.eql(404);
+ });
+
+ test('when the user does not have the VIEW_USERS permission, a 401 error is returned', async () => {
+ const targetUserId = 'usr_123456789012345678901234';
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_regular', email: '[email protected]' },
+ { id: targetUserId, email: '[email protected]' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ `/api/admin/users/${targetUserId}`,
+ { method: 'GET' },
+ { loggedInUserId: 'usr_regular' },
+ );
+
+ expect(response.status).to.eql(401);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+
+ test('when the user is not authenticated, a 401 error is returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_target', email: '[email protected]' },
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));
+
+ const response = await app.request(
+ '/api/admin/users/usr_target',
+ { method: 'GET' },
+ );
+
+ expect(response.status).to.eql(401);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/admin/users/users.routes.ts b/apps/papra-server/src/modules/admin/users/users.routes.ts
new file mode 100644
index 00000000..55f58dd8
--- /dev/null
+++ b/apps/papra-server/src/modules/admin/users/users.routes.ts
@@ -0,0 +1,83 @@
+import type { RouteDefinitionContext } from '../../app/server.types';
+import { z } from 'zod';
+import { createRoleMiddleware, requireAuthentication } from '../../app/auth/auth.middleware';
+import { createOrganizationsRepository } from '../../organizations/organizations.repository';
+import { PERMISSIONS } from '../../roles/roles.constants';
+import { createRolesRepository } from '../../roles/roles.repository';
+import { validateParams, validateQuery } from '../../shared/validation/validation';
+import { createUsersRepository } from '../../users/users.repository';
+import { userIdSchema } from '../../users/users.schemas';
+
+export function registerUserManagementRoutes(context: RouteDefinitionContext) {
+ registerListUsersRoute(context);
+ registerGetUserDetailRoute(context);
+}
+
+function registerListUsersRoute({ app, db }: RouteDefinitionContext) {
+ const { requirePermissions } = createRoleMiddleware({ db });
+
+ app.get(
+ '/api/admin/users',
+ requireAuthentication(),
+ requirePermissions({
+ requiredPermissions: [PERMISSIONS.VIEW_USERS],
+ }),
+ validateQuery(
+ z.object({
+ search: z.string().optional(),
+ pageIndex: z.coerce.number().min(0).int().optional().default(0),
+ pageSize: z.coerce.number().min(1).max(100).int().optional().default(25),
+ }),
+ ),
+ async (context) => {
+ const usersRepository = createUsersRepository({ db });
+
+ const { search, pageIndex, pageSize } = context.req.valid('query');
+
+ const { users, totalCount } = await usersRepository.listUsers({
+ search,
+ pageIndex,
+ pageSize,
+ });
+
+ return context.json({
+ users,
+ totalCount,
+ pageIndex,
+ pageSize,
+ });
+ },
+ );
+}
+
+function registerGetUserDetailRoute({ app, db }: RouteDefinitionContext) {
+ const { requirePermissions } = createRoleMiddleware({ db });
+
+ app.get(
+ '/api/admin/users/:userId',
+ requireAuthentication(),
+ requirePermissions({
+ requiredPermissions: [PERMISSIONS.VIEW_USERS],
+ }),
+ validateParams(z.object({
+ userId: userIdSchema,
+ })),
+ async (context) => {
+ const usersRepository = createUsersRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const rolesRepository = createRolesRepository({ db });
+
+ const { userId } = context.req.valid('param');
+
+ const { user } = await usersRepository.getUserByIdOrThrow({ userId });
+ const { organizations } = await organizationsRepository.getUserOrganizations({ userId });
+ const { roles } = await rolesRepository.getUserRoles({ userId });
+
+ return context.json({
+ user,
+ organizations,
+ roles,
+ });
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/app/auth/auth.middleware.test.ts b/apps/papra-server/src/modules/app/auth/auth.middleware.test.ts
index 3988583d..fdc3eadf 100644
--- a/apps/papra-server/src/modules/app/auth/auth.middleware.test.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.middleware.test.ts
@@ -107,7 +107,7 @@ describe('createRoleMiddleware', () => {
describe('when the user has multiple permissions and one matches', () => {
test('the request is allowed to proceed', async () => {
const extendedPermissionsByRole = {
- admin: [PERMISSIONS.BO_ACCESS, PERMISSIONS.USERS_LIST],
+ admin: [PERMISSIONS.BO_ACCESS, PERMISSIONS.VIEW_USERS],
};
const { db } = await createInMemoryDatabase({
@@ -123,7 +123,7 @@ describe('createRoleMiddleware', () => {
app.get(
'/protected',
- requirePermissions({ requiredPermissions: [PERMISSIONS.USERS_LIST] }),
+ requirePermissions({ requiredPermissions: [PERMISSIONS.VIEW_USERS] }),
async c => c.json({ success: true }),
);
@@ -137,7 +137,7 @@ describe('createRoleMiddleware', () => {
describe('when multiple permissions are required', () => {
test('the request is allowed if the user has all required permissions', async () => {
const extendedPermissionsByRole = {
- admin: [PERMISSIONS.BO_ACCESS, PERMISSIONS.USERS_LIST],
+ admin: [PERMISSIONS.BO_ACCESS, PERMISSIONS.VIEW_USERS],
};
const { db } = await createInMemoryDatabase({
@@ -153,7 +153,7 @@ describe('createRoleMiddleware', () => {
app.get(
'/protected',
- requirePermissions({ requiredPermissions: [PERMISSIONS.BO_ACCESS, PERMISSIONS.USERS_LIST] }),
+ requirePermissions({ requiredPermissions: [PERMISSIONS.BO_ACCESS, PERMISSIONS.VIEW_USERS] }),
async c => c.json({ success: true }),
);
@@ -181,7 +181,7 @@ describe('createRoleMiddleware', () => {
app.get(
'/protected',
- requirePermissions({ requiredPermissions: [PERMISSIONS.BO_ACCESS, PERMISSIONS.USERS_LIST] }),
+ requirePermissions({ requiredPermissions: [PERMISSIONS.BO_ACCESS, PERMISSIONS.VIEW_USERS] }),
async c => c.json({ success: true }),
);
diff --git a/apps/papra-server/src/modules/roles/roles.constants.ts b/apps/papra-server/src/modules/roles/roles.constants.ts
index 203d9371..a8b25888 100644
--- a/apps/papra-server/src/modules/roles/roles.constants.ts
+++ b/apps/papra-server/src/modules/roles/roles.constants.ts
@@ -1,12 +1,12 @@
export const PERMISSIONS = {
BO_ACCESS: 'bo:access',
- USERS_LIST: 'users:list',
+ VIEW_USERS: 'users:view',
VIEW_ANALYTICS: 'analytics:view',
} as const;
export const PERMISSIONS_BY_ROLE = {
admin: [
- PERMISSIONS.USERS_LIST,
+ PERMISSIONS.VIEW_USERS,
PERMISSIONS.BO_ACCESS,
PERMISSIONS.VIEW_ANALYTICS,
],
diff --git a/apps/papra-server/src/modules/users/users.repository.models.test.ts b/apps/papra-server/src/modules/users/users.repository.models.test.ts
new file mode 100644
index 00000000..f0768241
--- /dev/null
+++ b/apps/papra-server/src/modules/users/users.repository.models.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, test } from 'vitest';
+import { escapeLikeWildcards } from './users.repository.models';
+
+describe('users repository models', () => {
+ describe('escapeLikeWildcards', () => {
+ test('escape % and _ characters by prefixing them with a backslash', () => {
+ expect(escapeLikeWildcards('100%_sure')).to.eql('100\\%\\_sure');
+
+ expect(escapeLikeWildcards('hello')).to.eql('hello');
+ expect(escapeLikeWildcards(' ')).to.eql(' ');
+ });
+
+ test('backslashes are also escaped', () => {
+ expect(escapeLikeWildcards('C:\\path\\to\\file_%')).to.eql('C:\\\\path\\\\to\\\\file\\_\\%');
+ expect(escapeLikeWildcards('\\%_')).to.eql('\\\\\\%\\_');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/users/users.repository.models.ts b/apps/papra-server/src/modules/users/users.repository.models.ts
new file mode 100644
index 00000000..d48b1641
--- /dev/null
+++ b/apps/papra-server/src/modules/users/users.repository.models.ts
@@ -0,0 +1,28 @@
+import { eq, like, or } from 'drizzle-orm';
+import { isNilOrEmptyString } from '../shared/utils';
+import { USER_ID_REGEX } from './users.constants';
+import { usersTable } from './users.table';
+
+export function escapeLikeWildcards(input: string) {
+ return input.replace(/\\/g, '\\\\').replace(/[%_]/g, '\\$&');
+}
+
+export function createSearchUserWhereClause({ search }: { search?: string }) {
+ const trimmedSearch = search?.trim();
+
+ if (isNilOrEmptyString(trimmedSearch)) {
+ return undefined;
+ }
+
+ if (USER_ID_REGEX.test(trimmedSearch)) {
+ return eq(usersTable.id, trimmedSearch);
+ }
+
+ const escapedSearch = escapeLikeWildcards(trimmedSearch);
+ const likeSearch = `%${escapedSearch}%`;
+
+ return or(
+ like(usersTable.email, likeSearch),
+ like(usersTable.name, likeSearch),
+ );
+}
diff --git a/apps/papra-server/src/modules/users/users.repository.test.ts b/apps/papra-server/src/modules/users/users.repository.test.ts
index 8c598a96..2cfb9deb 100644
--- a/apps/papra-server/src/modules/users/users.repository.test.ts
+++ b/apps/papra-server/src/modules/users/users.repository.test.ts
@@ -44,4 +44,164 @@ describe('users repository', () => {
expect(userCount).to.equal(3);
});
});
+
+ describe('listUsers', () => {
+ test('when no users exist, an empty list is returned', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({});
+
+ expect(result).to.deep.equal({
+ users: [],
+ totalCount: 0,
+ pageIndex: 0,
+ pageSize: 25,
+ });
+ });
+
+ test('when multiple users exist, all users are returned with organization counts', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'Alice' },
+ { id: 'usr_2', email: '[email protected]', name: 'Bob' },
+ ],
+ organizations: [
+ { id: 'org_1', name: 'Org 1' },
+ ],
+ organizationMembers: [
+ { userId: 'usr_1', organizationId: 'org_1', role: 'owner' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({});
+
+ expect(result.users).to.have.length(2);
+ expect(result.totalCount).to.equal(2);
+ expect(result.pageIndex).to.equal(0);
+ expect(result.pageSize).to.equal(25);
+
+ expect(
+ result.users.map(u => ({
+ id: u.id,
+ email: u.email,
+ organizationCount: u.organizationCount,
+ })),
+ ).to.deep.equal([
+ { id: 'usr_1', email: '[email protected]', organizationCount: 1 },
+ { id: 'usr_2', email: '[email protected]', organizationCount: 0 },
+ ]);
+ });
+
+ test('when searching by user ID, only the exact matching user is returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_123456789012345678901234', email: '[email protected]', name: 'Alice' },
+ { id: 'usr_abcdefghijklmnopqrstuvwx', email: '[email protected]', name: 'Bob' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({ search: 'usr_abcdefghijklmnopqrstuvwx' });
+
+ expect(result.users).to.have.length(1);
+ expect(result.users[0]?.id).to.equal('usr_abcdefghijklmnopqrstuvwx');
+ expect(result.totalCount).to.equal(1);
+ });
+
+ test('when searching by partial email, matching users are returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'Alice' },
+ { id: 'usr_2', email: '[email protected]', name: 'Bob' },
+ { id: 'usr_3', email: '[email protected]', name: 'Alice Smith' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({ search: 'alice' });
+
+ expect(result.users).to.have.length(2);
+ expect(result.totalCount).to.equal(2);
+ expect(result.users.map(u => u.email)).to.deep.equal([
+ ]);
+ });
+
+ test('when searching by partial name, matching users are returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'Alice Johnson' },
+ { id: 'usr_2', email: '[email protected]', name: 'Bob Smith' },
+ { id: 'usr_3', email: '[email protected]', name: 'Charlie Johnson' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({ search: 'Johnson' });
+
+ expect(result.users).to.have.length(2);
+ expect(result.totalCount).to.equal(2);
+ expect(result.users.map(u => u.name)).to.deep.equal([
+ 'Alice Johnson',
+ 'Charlie Johnson',
+ ]);
+ });
+
+ test('when searching with an empty string, all users are returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'Alice' },
+ { id: 'usr_2', email: '[email protected]', name: 'Bob' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({ search: ' ' });
+
+ expect(result.users).to.have.length(2);
+ expect(result.totalCount).to.equal(2);
+ });
+
+ test('when using pagination, only the requested page is returned', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'User 1' },
+ { id: 'usr_2', email: '[email protected]', name: 'User 2' },
+ { id: 'usr_3', email: '[email protected]', name: 'User 3' },
+ { id: 'usr_4', email: '[email protected]', name: 'User 4' },
+ { id: 'usr_5', email: '[email protected]', name: 'User 5' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const firstPage = await listUsers({ pageIndex: 0, pageSize: 2 });
+ const secondPage = await listUsers({ pageIndex: 1, pageSize: 2 });
+
+ expect(firstPage.users).to.have.length(2);
+ expect(firstPage.totalCount).to.equal(5);
+ expect(secondPage.users).to.have.length(2);
+ expect(secondPage.totalCount).to.equal(5);
+ expect(firstPage.users[0]?.id).to.not.equal(secondPage.users[0]?.id);
+ });
+
+ test('when searching with pagination, the total count reflects the search results', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]', name: 'Alice 1' },
+ { id: 'usr_2', email: '[email protected]', name: 'Alice 2' },
+ { id: 'usr_3', email: '[email protected]', name: 'Alice 3' },
+ { id: 'usr_4', email: '[email protected]', name: 'Bob' },
+ ],
+ });
+ const { listUsers } = createUsersRepository({ db });
+
+ const result = await listUsers({ search: 'alice', pageIndex: 0, pageSize: 2 });
+
+ expect(result.users).to.have.length(2);
+ expect(result.totalCount).to.equal(3);
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/users/users.repository.ts b/apps/papra-server/src/modules/users/users.repository.ts
index b952e9a5..40c6bbeb 100644
--- a/apps/papra-server/src/modules/users/users.repository.ts
+++ b/apps/papra-server/src/modules/users/users.repository.ts
@@ -1,9 +1,12 @@
import type { Database } from '../app/database/database.types';
import type { DbInsertableUser } from './users.types';
import { injectArguments } from '@corentinth/chisels';
-import { count, eq } from 'drizzle-orm';
+import { count, desc, eq, getTableColumns } from 'drizzle-orm';
+import { organizationMembersTable } from '../organizations/organizations.table';
import { isUniqueConstraintError } from '../shared/db/constraints.models';
+import { withPagination } from '../shared/db/pagination';
import { createUserAlreadyExistsError, createUsersNotFoundError } from './users.errors';
+import { createSearchUserWhereClause } from './users.repository.models';
import { usersTable } from './users.table';
export { createUsersRepository };
@@ -19,6 +22,7 @@ function createUsersRepository({ db }: { db: Database }) {
getUserByIdOrThrow,
updateUser,
getUserCount,
+ listUsers,
},
{ db },
);
@@ -81,3 +85,49 @@ export async function getUserCount({ db }: { db: Database }) {
userCount,
};
}
+
+async function listUsers({
+ db,
+ search,
+ pageIndex = 0,
+ pageSize = 25,
+}: {
+ db: Database;
+ search?: string;
+ pageIndex?: number;
+ pageSize?: number;
+}) {
+ const searchWhereClause = createSearchUserWhereClause({ search });
+
+ const query = db
+ .select({
+ ...getTableColumns(usersTable),
+ organizationCount: count(organizationMembersTable.id),
+ })
+ .from(usersTable)
+ .leftJoin(
+ organizationMembersTable,
+ eq(usersTable.id, organizationMembersTable.userId),
+ )
+ .where(searchWhereClause)
+ .groupBy(usersTable.id)
+ .$dynamic();
+
+ const users = await withPagination(query, {
+ orderByColumn: desc(usersTable.createdAt),
+ pageIndex,
+ pageSize,
+ });
+
+ const [{ totalCount = 0 } = {}] = await db
+ .select({ totalCount: count() })
+ .from(usersTable)
+ .where(searchWhereClause);
+
+ return {
+ users,
+ totalCount,
+ pageIndex,
+ pageSize,
+ };
+}