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

52 lines
1.1 KiB
TypeScript
Raw Normal View History

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';
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;
tokenName: string;
2024-02-09 11:32:54 +02:00
expirationDate: string | null;
2023-11-24 16:13:09 +02:00
};
2024-02-09 11:32:54 +02:00
export const createApiToken = async ({
userId,
tokenName,
expirationDate,
}: 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;
2023-12-21 16:02:02 +02:00
const dbToken = await prisma.apiToken.create({
2023-11-24 16:13:09 +02:00
data: {
2023-12-21 16:02:02 +02:00
token: hashedToken,
2023-11-24 16:13:09 +02:00
name: tokenName,
userId,
2024-02-09 11:32:54 +02:00
expires: expirationDate
? DateTime.now().plus(timeConstantsRecords[expirationDate]).toJSDate()
: null,
2023-11-24 16:13:09 +02:00
},
});
2023-12-21 16:02:02 +02:00
if (!dbToken) {
throw new Error('Failed to create the API token');
2023-11-24 16:13:09 +02:00
}
2023-12-21 16:02:02 +02:00
return {
id: dbToken.id,
token: apiToken,
};
2023-11-24 16:13:09 +02:00
};