mirror of
https://github.com/documenso/documenso.git
synced 2025-11-13 16:23:06 +10:00
feat: api token functions
This commit is contained in:
34
packages/lib/server-only/public-api/create-api-token.ts
Normal file
34
packages/lib/server-only/public-api/create-api-token.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import crypto from 'crypto';
|
||||||
|
|
||||||
|
import { prisma } from '@documenso/prisma';
|
||||||
|
|
||||||
|
// temporary choice for testing only
|
||||||
|
import { ONE_WEEK } from '../../constants/time';
|
||||||
|
|
||||||
|
type CreateApiTokenInput = {
|
||||||
|
userId: number;
|
||||||
|
tokenName: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createApiToken = async ({ userId, tokenName }: CreateApiTokenInput) => {
|
||||||
|
// quick implementation for testing; it needs double checking
|
||||||
|
const tokenHash = crypto
|
||||||
|
.createHash('sha512')
|
||||||
|
.update(crypto.randomBytes(32).toString('hex'))
|
||||||
|
.digest('hex');
|
||||||
|
|
||||||
|
const token = await prisma.apiToken.create({
|
||||||
|
data: {
|
||||||
|
token: tokenHash,
|
||||||
|
name: tokenName,
|
||||||
|
userId,
|
||||||
|
expires: new Date(Date.now() + ONE_WEEK),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new Error(`Failed to create the API token`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return token;
|
||||||
|
};
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
import { prisma } from '@documenso/prisma';
|
||||||
|
|
||||||
|
export type DeleteTokenByIdOptions = {
|
||||||
|
id: number;
|
||||||
|
userId: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteTokenById = async ({ id, userId }: DeleteTokenByIdOptions) => {
|
||||||
|
return prisma.apiToken.delete({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
15
packages/lib/server-only/public-api/get-api-token-by-id.ts
Normal file
15
packages/lib/server-only/public-api/get-api-token-by-id.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { prisma } from '@documenso/prisma';
|
||||||
|
|
||||||
|
export type GetApiTokenByIdOptions = {
|
||||||
|
id: number;
|
||||||
|
userId: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getApiTokenById = async ({ id, userId }: GetApiTokenByIdOptions) => {
|
||||||
|
return prisma.apiToken.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user