Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(api-client): integrated ofetch and cleaned api auth logic (#15)

Corentin THOMASSET9c5df8f183cd
diff --git a/apps/papra-client/package.json b/apps/papra-client/package.json
index 19575431..36c7900f 100644
--- a/apps/papra-client/package.json
+++ b/apps/papra-client/package.json
@@ -44,6 +44,7 @@
"date-fns": "^4.1.0",
"jszip": "^3.10.1",
"lodash-es": "^4.17.21",
+ "ofetch": "^1.4.1",
"solid-js": "^1.8.11",
"solid-sonner": "^0.2.8",
"tailwind-merge": "^2.6.0",
diff --git a/apps/papra-client/src/modules/auth/auth.services.ts b/apps/papra-client/src/modules/auth/auth.services.ts
index af58295b..d5e163f0 100644
--- a/apps/papra-client/src/modules/auth/auth.services.ts
+++ b/apps/papra-client/src/modules/auth/auth.services.ts
@@ -1,6 +1,6 @@
-import { buildUrl } from '@corentinth/chisels';
import { config } from '../config/config';
-import { apiClient } from '../shared/http/http-client';
+import { apiClient } from '../shared/http/api-client';
+import { httpClient } from '../shared/http/http-client';
export { login };
@@ -18,28 +18,16 @@ async function login({ email, password }: { email: string; password: string }) {
}
export async function requestAuthTokensRefresh() {
- // Do not use apiClient here top prevent infinite loop
-
- const url = buildUrl({
+ // Do not use apiClient here top prevent loops since requestAuthTokensRefresh might be called from apiClient
+ const { accessToken } = await httpClient<{ accessToken: string }>({
baseUrl: config.baseApiUrl,
- path: '/api/auth/refresh',
- });
-
- const response = await fetch(url, {
+ url: '/api/auth/refresh',
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- // set http only cookie
+
+ // Required to send the refresh token
credentials: 'include',
});
- if (!response.ok) {
- throw new Error('Failed to refresh tokens');
- }
-
- const { accessToken } = await response.json();
-
return { accessToken };
}
@@ -47,6 +35,7 @@ export async function logout() {
await apiClient({
path: '/api/auth/logout',
method: 'POST',
+ credentials: 'include',
});
}
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index e88d91b3..e4e5a831 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -1,10 +1,10 @@
import type { Document } from './documents.types';
-import { apiClient } from '../shared/http/http-client';
+import { apiClient } from '../shared/http/api-client';
+import { getFormData } from '../shared/http/http-client.models';
export async function uploadDocument({
file,
organizationId,
-
}: {
file: File;
organizationId: string;
@@ -12,9 +12,7 @@ export async function uploadDocument({
const { document } = await apiClient<{ document: Document }>({
method: 'POST',
path: `/api/organizations/${organizationId}/documents`,
- formData: {
- file,
- },
+ body: getFormData({ file }),
});
return {
@@ -41,7 +39,7 @@ export async function fetchOrganizationDocuments({
} = await apiClient<{ documents: Document[]; documentsCount: number }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents`,
- queryParams: {
+ query: {
pageIndex,
pageSize,
},
@@ -98,7 +96,7 @@ export async function fetchDocumentFile({
documentId: string;
organizationId: string;
}) {
- const blob = await apiClient<Blob>({
+ const blob = await apiClient({
method: 'GET',
path: `/api/organizations/${organizationId}/documents/${documentId}/file`,
responseType: 'blob',
@@ -123,7 +121,7 @@ export async function searchDocuments({
} = await apiClient<{ documents: Document[] }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents/search`,
- queryParams: {
+ query: {
searchQuery,
pageIndex,
pageSize,
diff --git a/apps/papra-client/src/modules/organizations/organizations.services.ts b/apps/papra-client/src/modules/organizations/organizations.services.ts
index 74c624a9..2fe61f60 100644
--- a/apps/papra-client/src/modules/organizations/organizations.services.ts
+++ b/apps/papra-client/src/modules/organizations/organizations.services.ts
@@ -1,5 +1,5 @@
import type { Organization } from './organizations.types';
-import { apiClient } from '../shared/http/http-client';
+import { apiClient } from '../shared/http/api-client';
export async function fetchOrganizations() {
const { organizations } = await apiClient<{ organizations: Organization[] }>({
diff --git a/apps/papra-client/src/modules/shared/http/api-client.models.test.ts b/apps/papra-client/src/modules/shared/http/api-client.models.test.ts
new file mode 100644
index 00000000..1fca609d
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/http/api-client.models.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'vitest';
+import { buildAuthHeader, shouldRefreshAuthTokens } from './api-client.models';
+
+describe('api-client models', () => {
+ describe('buildAuthHeader', () => {
+ test('given a auth token the autorization header is a standard bearer token', () => {
+ expect(buildAuthHeader({ accessToken: 'foo' })).to.eql({ Authorization: 'Bearer foo' });
+ });
+
+ test('if no auth token is provided, no headers are built', () => {
+ expect(buildAuthHeader()).to.eql({});
+ expect(buildAuthHeader({})).to.eql({});
+ expect(buildAuthHeader({ accessToken: undefined })).to.eql({});
+ expect(buildAuthHeader({ accessToken: null })).to.eql({});
+ });
+ });
+
+ describe('shouldRefreshAuthTokens', () => {
+ test('the tokens should be refreshed if the api replies with a 401 status code', () => {
+ expect(shouldRefreshAuthTokens({ error: { status: 401 } })).to.eql(true);
+
+ expect(shouldRefreshAuthTokens({ error: { status: 200 } })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: { status: 500 } })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: { status: 404 } })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: { status: 403 } })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: { status: undefined } })).to.eql(false);
+
+ expect(shouldRefreshAuthTokens({ error: undefined })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: null })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: {} })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: { foo: 'bar' } })).to.eql(false);
+ expect(shouldRefreshAuthTokens({ error: 'foo' })).to.eql(false);
+ });
+ });
+});
diff --git a/apps/papra-client/src/modules/shared/http/api-client.models.ts b/apps/papra-client/src/modules/shared/http/api-client.models.ts
new file mode 100644
index 00000000..60ea5cf2
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/http/api-client.models.ts
@@ -0,0 +1,20 @@
+import type { FetchError } from 'ofetch';
+import { get } from 'lodash-es';
+
+export function shouldRefreshAuthTokens({ error }: { error: FetchError | unknown | undefined }) {
+ if (!error) {
+ return false;
+ }
+
+ return get(error, 'status') === 401;
+}
+
+export function buildAuthHeader({ accessToken }: { accessToken?: string | null | undefined } = {}): Record<string, string> {
+ if (!accessToken) {
+ return {};
+ }
+
+ return {
+ Authorization: `Bearer ${accessToken}`,
+ };
+}
diff --git a/apps/papra-client/src/modules/shared/http/api-client.ts b/apps/papra-client/src/modules/shared/http/api-client.ts
new file mode 100644
index 00000000..74f3339b
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/http/api-client.ts
@@ -0,0 +1,62 @@
+import { authStore } from '@/modules/auth/auth.store';
+import { config } from '@/modules/config/config';
+import { safely } from '@corentinth/chisels';
+import { buildAuthHeader, shouldRefreshAuthTokens } from './api-client.models';
+import { httpClient, type HttpClientOptions, type ResponseType } from './http-client';
+
+export async function apiClient<T, R extends ResponseType = 'json'>({
+ path,
+ ...rest
+}: {
+ path: string;
+} & Omit<HttpClientOptions<R>, 'url'>) {
+ const accessToken = authStore.getAccessToken();
+
+ const requestConfig: HttpClientOptions<R> = {
+ baseUrl: config.baseApiUrl,
+ url: path,
+ ...rest,
+ headers: {
+ ...buildAuthHeader({ accessToken }),
+ ...rest.headers,
+ },
+ };
+
+ const [response, error] = await safely(httpClient<T, R>(requestConfig));
+
+ if (shouldRefreshAuthTokens({ error })) {
+ return refreshTokensAndRetry<T, R>({ requestConfig });
+ }
+
+ if (error) {
+ throw error;
+ }
+
+ return response;
+}
+
+async function refreshTokensAndRetry<T, R extends ResponseType = 'json'>({ requestConfig }: { requestConfig: HttpClientOptions<R> }) {
+ try {
+ // If a refresh token refresh request is already in progress, wait for it to finish
+ if (authStore.getIsRefreshTokenInProgress()) {
+ await authStore.waitForRefreshTokenToBeRefreshed();
+ } else {
+ await authStore.refreshToken();
+ }
+
+ const accessToken = authStore.getAccessToken();
+
+ return httpClient<T, R>({
+ ...requestConfig,
+ headers: {
+ ...requestConfig.headers,
+ ...buildAuthHeader({ accessToken }),
+ },
+ });
+ } catch (err) {
+ await authStore.clearAccessToken();
+ window.location.href = '/login';
+ console.error('Refresh token expired or invalid', err);
+ throw err;
+ }
+}
diff --git a/apps/papra-client/src/modules/shared/http/http-client.models.test.ts b/apps/papra-client/src/modules/shared/http/http-client.models.test.ts
index acba4b89..39e22aa2 100644
--- a/apps/papra-client/src/modules/shared/http/http-client.models.test.ts
+++ b/apps/papra-client/src/modules/shared/http/http-client.models.test.ts
@@ -1,30 +1,20 @@
import { describe, expect, test } from 'vitest';
-import { buildAuthHeader, buildImpersonationHeader } from './http-client.models';
+import { getFormData } from './http-client.models';
describe('http-client models', () => {
- describe('buildAuthHeader', () => {
- test('given a auth token the autorization header is a standard bearer token', () => {
- expect(buildAuthHeader({ accessToken: 'foo' })).to.eql({ Authorization: 'Bearer foo' });
- });
-
- test('if no auth token is provided, no headers are built', () => {
- expect(buildAuthHeader()).to.eql({});
- expect(buildAuthHeader({})).to.eql({});
- expect(buildAuthHeader({ accessToken: undefined })).to.eql({});
- expect(buildAuthHeader({ accessToken: null })).to.eql({});
- });
- });
-
- describe('buildImpersonationHeader', () => {
- test('the impersonation user id is added as a x-user-id header', () => {
- expect(buildImpersonationHeader({ impersonatedUserId: 'foo' })).to.eql({ 'x-user-id': 'foo' });
- });
+ describe('getFormData', () => {
+ test('transforms a record into a FormData object', () => {
+ const formData = getFormData({
+ foo: 'bar',
+ baz: 'qux',
+ file1: new Blob(['file1']),
+ file2: new File(['file2'], 'file2.txt'),
+ });
- test('if no impersonation user id is provided, no headers are built', () => {
- expect(buildImpersonationHeader()).to.eql({});
- expect(buildImpersonationHeader({})).to.eql({});
- expect(buildImpersonationHeader({ impersonatedUserId: undefined })).to.eql({});
- expect(buildImpersonationHeader({ impersonatedUserId: null })).to.eql({});
+ expect(formData.get('foo')).to.eql('bar');
+ expect(formData.get('baz')).to.eql('qux');
+ expect(formData.get('file1')).to.be.instanceOf(Blob);
+ expect(formData.get('file2')).to.be.instanceOf(File);
});
});
});
diff --git a/apps/papra-client/src/modules/shared/http/http-client.models.ts b/apps/papra-client/src/modules/shared/http/http-client.models.ts
index 5a91b36a..6441232b 100644
--- a/apps/papra-client/src/modules/shared/http/http-client.models.ts
+++ b/apps/papra-client/src/modules/shared/http/http-client.models.ts
@@ -1,39 +1,5 @@
-export { buildAuthHeader, buildImpersonationHeader, getBody, isFetchResponseJson };
-
-function isFetchResponseJson({ response }: { response: Response }): boolean {
- return Boolean(response.headers.get('content-type')?.includes('application/json'));
-}
-
-function getBody({ response }: { response: Response }): Promise<unknown> {
- try {
- return isFetchResponseJson({ response }) ? response.json() : response.text();
- } catch (_error) {
- return Promise.resolve({});
- }
-}
-
-function buildAuthHeader({ accessToken }: { accessToken?: string | null | undefined } = {}): Record<string, string> {
- if (!accessToken) {
- return {};
- }
-
- return {
- Authorization: `Bearer ${accessToken}`,
- };
-}
-
-function buildImpersonationHeader({ impersonatedUserId }: { impersonatedUserId?: string | null | undefined } = {}): Record<string, string> {
- if (!impersonatedUserId) {
- return {};
- }
-
- return {
- 'x-user-id': impersonatedUserId,
- };
-}
-
-export function getFormData(pojo: Record<string, unknown>): FormData {
+export function getFormData(pojo: Record<string, string | Blob>): FormData {
const formData = new FormData();
- Object.keys(pojo).forEach(key => formData.append(key, pojo[key] as string));
+ Object.entries(pojo).forEach(([key, value]) => formData.append(key, value));
return formData;
}
diff --git a/apps/papra-client/src/modules/shared/http/http-client.ts b/apps/papra-client/src/modules/shared/http/http-client.ts
index ab66b699..b33c1145 100644
--- a/apps/papra-client/src/modules/shared/http/http-client.ts
+++ b/apps/papra-client/src/modules/shared/http/http-client.ts
@@ -1,100 +1,12 @@
-import { authStore } from '@/modules/auth/auth.store';
-import { config } from '@/modules/config/config';
-import { buildUrl } from '@corentinth/chisels';
-import { mapValues } from 'lodash-es';
-import { buildAuthHeader, buildImpersonationHeader, getBody, getFormData } from './http-client.models';
+import type { FetchOptions, ResponseType } from 'ofetch';
+import { ofetch } from 'ofetch';
-export { apiClient };
+export { ResponseType };
+export type HttpClientOptions<R extends ResponseType = 'json'> = Omit<FetchOptions<R>, 'baseURL'> & { url: string; baseUrl?: string };
-async function apiClient<T>({
- path,
- method,
- body,
- formData,
- queryParams,
- impersonatedUserId,
- responseType = 'json',
-}: {
- path: string;
- method: string;
- body?: unknown;
- formData?: Record<string, unknown>;
- queryParams?: Record<string, string | number>;
- impersonatedUserId?: string;
- responseType?: 'json' | 'blob';
-}): Promise<T> {
- const url = buildUrl({
- path,
- baseUrl: config.baseApiUrl,
- queryParams: queryParams ? mapValues(queryParams, String) : undefined,
+export function httpClient<A, R extends ResponseType = 'json'>({ url, baseUrl, ...rest }: HttpClientOptions<R>) {
+ return ofetch<A, R>(url, {
+ baseURL: baseUrl,
+ ...rest,
});
-
- const accessToken = authStore.getAccessToken();
-
- const fetchOptions = {
- method,
- headers: {
- ...(body ? { 'Content-Type': 'application/json' } : {}),
- ...buildAuthHeader({ accessToken }),
- ...buildImpersonationHeader({ impersonatedUserId }),
- },
- body: body ? JSON.stringify(body) : formData ? getFormData(formData) : undefined,
- };
-
- const response = await fetch(url, fetchOptions);
-
- if (!response.ok) {
- if (response.status === 401) {
- return refreshTokensAndRetry<T>({ originalOptions: fetchOptions, url });
- }
-
- const error = new Error(response.statusText);
- Object.assign(error, {
- status: response.status,
- body: await getBody({ response }),
- });
-
- throw error;
- }
-
- if (response.status === 204) {
- return {} as T;
- }
-
- if (responseType === 'blob') {
- return response.blob() as unknown as T;
- }
-
- return response.json();
-}
-
-async function refreshTokensAndRetry<T>({ originalOptions, url }: { originalOptions: RequestInit; url: string }): Promise<T> {
- try {
- if (authStore.getIsRefreshTokenInProgress()) {
- await authStore.waitForRefreshTokenToBeRefreshed();
- } else {
- await authStore.refreshToken();
- }
-
- const accessToken = authStore.getAccessToken();
-
- const response = await fetch(url, {
- ...originalOptions,
- headers: {
- ...originalOptions.headers,
- ...buildAuthHeader({ accessToken }),
- },
- });
-
- if (response.status === 204) {
- return {} as T;
- }
-
- return response.json();
- } catch (err) {
- await authStore.clearAccessToken();
- window.location.href = '/login';
- console.error('Refresh token expired or invalid', err);
- throw err;
- }
}
diff --git a/apps/papra-client/src/modules/shared/http/http-errors.ts b/apps/papra-client/src/modules/shared/http/http-errors.ts
index a73835d7..1777f808 100644
--- a/apps/papra-client/src/modules/shared/http/http-errors.ts
+++ b/apps/papra-client/src/modules/shared/http/http-errors.ts
@@ -3,7 +3,7 @@ import { get } from 'lodash-es';
export { isHttpErrorWithCode, isHttpErrorWithStatusCode, isRateLimitError };
function isHttpErrorWithCode({ error, code }: { error: unknown; code: string }) {
- return get(error, 'body.error.code') === code;
+ return get(error, 'data.error.code') === code;
}
function isHttpErrorWithStatusCode({ error, statusCode }: { error: unknown; statusCode: number }) {
diff --git a/apps/papra-client/src/modules/users/users.services.ts b/apps/papra-client/src/modules/users/users.services.ts
index cbe41ffb..befbd7d3 100644
--- a/apps/papra-client/src/modules/users/users.services.ts
+++ b/apps/papra-client/src/modules/users/users.services.ts
@@ -1,5 +1,5 @@
import type { UserMe } from './users.types';
-import { apiClient } from '../shared/http/http-client';
+import { apiClient } from '../shared/http/api-client';
export async function fetchCurrentUser() {
const { user } = await apiClient<{ user: UserMe }>({
diff --git a/apps/papra-server/src/modules/app/auth/auth.routes.ts b/apps/papra-server/src/modules/app/auth/auth.routes.ts
index 211f8c4c..e4e911a7 100644
--- a/apps/papra-server/src/modules/app/auth/auth.routes.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.routes.ts
@@ -2,6 +2,7 @@ import type { ServerInstance } from '../server.types';
import { getConfig } from '../../config/config.models';
import { createRolesRepository } from '../../roles/roles.repository';
+import { createLogger } from '../../shared/logger/logger';
import { createCookieRepository } from '../cookies/cookies.repository';
import { getDb } from '../database/database.models';
import { createAuthTokensRepository } from './auth-tokens/auth-tokens.repository';
@@ -19,6 +20,8 @@ export function registerAuthPrivateRoutes({ app }: { app: ServerInstance }) {
registerLogoutRoute({ app });
}
+const logger = createLogger({ namespace: 'auth.routes' });
+
function registerLogoutRoute({ app }: { app: ServerInstance }) {
app.post('/api/auth/logout', async (context) => {
const { config } = getConfig({ context });
@@ -31,6 +34,8 @@ function registerLogoutRoute({ app }: { app: ServerInstance }) {
if (refreshToken) {
await authTokenRepository.deleteAuthToken({ token: refreshToken });
await refreshTokenCookieRepository.deleteRefreshTokenCookie();
+ } else {
+ logger.warn('No refresh token found in cookies when trying to logout');
}
return context.body(null, 204);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4bb9559d..561aab7d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -76,6 +76,9 @@ importers:
lodash-es:
specifier: ^4.17.21
version: 4.17.21
+ ofetch:
+ specifier: ^1.4.1
+ version: 1.4.1
solid-js:
specifier: ^1.8.11
version: 1.9.3