2023-11-24 16:13:09 +02:00
|
|
|
import { prisma } from '@documenso/prisma';
|
|
|
|
|
|
|
|
|
|
// temporary choice for testing only
|
2023-12-11 14:33:30 +02:00
|
|
|
import { ONE_YEAR } 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
|
|
|
|
|
|
|
|
type CreateApiTokenInput = {
|
|
|
|
|
userId: number;
|
|
|
|
|
tokenName: string;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const createApiToken = async ({ userId, tokenName }: 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
|
|
|
|
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,
|
2023-12-11 14:33:30 +02:00
|
|
|
expires: new Date(Date.now() + ONE_YEAR),
|
2023-11-24 16:13:09 +02:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2023-12-21 16:02:02 +02:00
|
|
|
if (!dbToken) {
|
2024-01-17 12:44:25 +02:00
|
|
|
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
|
|
|
};
|