Skip to content

The Open Source DocuSign Alternative.

fix(api): replace generic errors with AppError in getApiTokenByToken (#2315)

Catalin Pit4d6389e90157
diff --git a/packages/lib/server-only/public-api/get-api-token-by-token.ts b/packages/lib/server-only/public-api/get-api-token-by-token.ts
index 925230bfd..6f384c34b 100644
--- a/packages/lib/server-only/public-api/get-api-token-by-token.ts
+++ b/packages/lib/server-only/public-api/get-api-token-by-token.ts
@@ -1,5 +1,6 @@
import { prisma } from '@documenso/prisma';
+import { AppError, AppErrorCode } from '../../errors/app-error';
import { hashString } from '../auth/hash';
export const getApiTokenByToken = async ({ token }: { token: string }) => {
@@ -38,11 +39,17 @@ export const getApiTokenByToken = async ({ token }: { token: string }) => {
});
if (!apiToken) {
- throw new Error('Invalid token');
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid token',
+ statusCode: 401,
+ });
}
if (apiToken.expires && apiToken.expires < new Date()) {
- throw new Error('Expired token');
+ throw new AppError(AppErrorCode.EXPIRED_CODE, {
+ message: 'Expired token',
+ statusCode: 401,
+ });
}
// Handle a silly choice from many moons ago
@@ -54,7 +61,10 @@ export const getApiTokenByToken = async ({ token }: { token: string }) => {
// This will never happen but we need to narrow types
if (!user) {
- throw new Error('Invalid token');
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid token',
+ statusCode: 401,
+ });
}
return {
diff --git a/packages/lib/server-only/public-api/get-user-by-token.ts b/packages/lib/server-only/public-api/get-user-by-token.ts
index a8c39f75b..887730b5c 100644
--- a/packages/lib/server-only/public-api/get-user-by-token.ts
+++ b/packages/lib/server-only/public-api/get-user-by-token.ts
@@ -1,5 +1,6 @@
import { prisma } from '@documenso/prisma';
+import { AppError, AppErrorCode } from '../../errors/app-error';
import { hashString } from '../auth/hash';
export const getUserByApiToken = async ({ token }: { token: string }) => {
@@ -19,14 +20,20 @@ export const getUserByApiToken = async ({ token }: { token: string }) => {
});
if (!user) {
- throw new Error('Invalid token');
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid token',
+ statusCode: 401,
+ });
}
const retrievedToken = user.apiTokens.find((apiToken) => apiToken.token === hashedToken);
// This should be impossible but we need to satisfy TypeScript
if (!retrievedToken) {
- throw new Error('Invalid token');
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid token',
+ statusCode: 401,
+ });
}
if (retrievedToken.expires && retrievedToken.expires < new Date()) {