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

36 lines
790 B
TypeScript
Raw Normal View History

2023-11-24 16:13:09 +02:00
import { prisma } from '@documenso/prisma';
// temporary choice for testing only
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,
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) {
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
};