chore: implemented feedback

This commit is contained in:
Catalin Pit
2023-12-21 16:02:02 +02:00
parent 6a56905fea
commit d283cc2d26
4 changed files with 30 additions and 26 deletions

View File

@ -1,9 +1,9 @@
import crypto from 'crypto';
import { prisma } from '@documenso/prisma';
// temporary choice for testing only
import { ONE_YEAR } from '../../constants/time';
import { alphaid } from '../../universal/id';
import { hashString } from '../auth/hash';
type CreateApiTokenInput = {
userId: number;
@ -11,24 +11,25 @@ type CreateApiTokenInput = {
};
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 apiToken = `api_${alphaid(16)}`;
const token = await prisma.apiToken.create({
const hashedToken = hashString(apiToken);
const dbToken = await prisma.apiToken.create({
data: {
token: tokenHash,
token: hashedToken,
name: tokenName,
userId,
expires: new Date(Date.now() + ONE_YEAR),
},
});
if (!token) {
if (!dbToken) {
throw new Error(`Failed to create the API token`);
}
return token;
return {
id: dbToken.id,
token: apiToken,
};
};

View File

@ -1,11 +1,15 @@
import { prisma } from '@documenso/prisma';
export const checkUserFromToken = async ({ token }: { token: string }) => {
import { hashString } from '../auth/hash';
export const getUserByApiToken = async ({ token }: { token: string }) => {
const hashedToken = hashString(token);
const user = await prisma.user.findFirst({
where: {
ApiToken: {
some: {
token: token,
token: hashedToken,
},
},
},
@ -18,7 +22,7 @@ export const checkUserFromToken = async ({ token }: { token: string }) => {
throw new Error('Invalid token');
}
const tokenObject = user.ApiToken.find((apiToken) => apiToken.token === token);
const tokenObject = user.ApiToken.find((apiToken) => apiToken.token === hashedToken);
if (!tokenObject || new Date(tokenObject.expires) < new Date()) {
throw new Error('Expired token');