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

This commit is contained in:
Catalin Pit
2025-12-15 02:47:38 +02:00
committed by GitHub
parent 51e3d5030d
commit 4d6389e901
2 changed files with 22 additions and 5 deletions
@@ -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 {
@@ -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()) {