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

67 lines
1.5 KiB
TypeScript
Raw Normal View History

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