documenso/packages/lib/server-only/public-api/create-api-token.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-02-09 09:32:54 +00:00
import type { Duration } from 'luxon';
import { DateTime } from 'luxon';
2023-11-24 14:13:09 +00:00
import { prisma } from '@documenso/prisma';
2025-06-10 01:49:52 +00:00
import { TEAM_MEMBER_ROLE_PERMISSIONS_MAP } from '../../constants/teams';
2023-11-24 14:13:09 +00:00
// temporary choice for testing only
2024-02-09 09:32:54 +00:00
import * as timeConstants from '../../constants/time';
import { AppError, AppErrorCode } from '../../errors/app-error';
2023-12-21 14:02:02 +00:00
import { alphaid } from '../../universal/id';
2025-06-10 01:49:52 +00:00
import { buildTeamWhereQuery } from '../../utils/teams';
2023-12-21 14:02:02 +00:00
import { hashString } from '../auth/hash';
2023-11-24 14:13:09 +00:00
2024-02-09 09:32:54 +00:00
type TimeConstants = typeof timeConstants & {
[key: string]: number | Duration;
};
2023-11-24 14:13:09 +00:00
type CreateApiTokenInput = {
userId: number;
2025-06-10 01:49:52 +00:00
teamId: number;
2023-11-24 14:13:09 +00:00
tokenName: string;
2024-02-22 02:39:34 +00:00
expiresIn: string | null;
2023-11-24 14:13:09 +00:00
};
2024-02-09 09:32:54 +00:00
export const createApiToken = async ({
userId,
2024-02-22 02:39:34 +00:00
teamId,
2024-02-09 09:32:54 +00:00
tokenName,
2024-02-22 02:39:34 +00:00
expiresIn,
2024-02-09 09:32:54 +00:00
}: CreateApiTokenInput) => {
2023-12-21 14:02:02 +00:00
const apiToken = `api_${alphaid(16)}`;
const hashedToken = hashString(apiToken);
2023-11-24 14:13:09 +00:00
2024-02-09 09:32:54 +00:00
const timeConstantsRecords: TimeConstants = timeConstants;
2025-06-10 01:49:52 +00:00
const team = await prisma.team.findFirst({
where: buildTeamWhereQuery({
teamId,
userId,
roles: TEAM_MEMBER_ROLE_PERMISSIONS_MAP['MANAGE_TEAM'],
}),
});
2024-02-22 02:39:34 +00:00
2025-06-10 01:49:52 +00:00
if (!team) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to create a token for this team',
});
2024-02-22 02:39:34 +00:00
}
const storedToken = await prisma.apiToken.create({
2023-11-24 14:13:09 +00:00
data: {
name: tokenName,
2024-02-22 02:39:34 +00:00
token: hashedToken,
expires: expiresIn ? DateTime.now().plus(timeConstantsRecords[expiresIn]).toJSDate() : null,
userId,
2024-02-22 02:39:34 +00:00
teamId,
2023-11-24 14:13:09 +00:00
},
});
2023-12-21 14:02:02 +00:00
return {
2024-02-22 02:39:34 +00:00
id: storedToken.id,
2023-12-21 14:02:02 +00:00
token: apiToken,
};
2023-11-24 14:13:09 +00:00
};