Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Refactor to Use credentialRepository for credential create. #17336

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions apps/api/v1/pages/api/credential-sync/_post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";

import { schemaCredentialPostBody, schemaCredentialPostParams } from "~/lib/validations/credential-sync";
Expand Down Expand Up @@ -88,14 +90,11 @@ async function handler(req: NextApiRequest) {

const appMetadata = appStoreMetadata[app.dirName as keyof typeof appStoreMetadata];

const createdcredential = await prisma.credential.create({
data: {
userId,
appId: appSlug,
key,
type: appMetadata.type,
},
select: credentialForCalendarServiceSelect,
const createdcredential = await CredentialRepository.create({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Prisma.JsonNull handling for key is also a solid choice for cleaner code. Nicely done!

userId,
appId: appSlug,
key: key ? (key as Prisma.InputJsonValue) : Prisma.JsonNull,
type: appMetadata.type,
});
// createdcredential.user.email;
// TODO: ^ Investigate why this select doesn't work.
Expand Down
3 changes: 2 additions & 1 deletion apps/api/v1/pages/api/selected-calendars/_post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { NextApiRequest } from "next";

import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import prisma from "@calcom/prisma";

import {
Expand Down Expand Up @@ -63,7 +64,7 @@ async function postHandler(req: NextApiRequest) {
args.data.userId = bodyUserId;
}

const data = await prisma.selectedCalendar.create(args);
const data = await SelectedCalendarRepository.create(args.data);

return {
selected_calendar: schemaSelectedCalendarPublic.parse(data),
Expand Down
12 changes: 5 additions & 7 deletions apps/web/pages/api/teams/googleworkspace/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { throwIfNotHaveAdminAccessToTeam } from "@calcom/app-store/_utils/throwI
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";

const stateSchema = z.object({
teamId: z.string(),
Expand Down Expand Up @@ -45,12 +45,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)

const credentials = await oAuth2Client.getToken(code);

await prisma.credential.create({
data: {
type: "google_workspace_directory",
key: credentials.res?.data,
userId: session.user.id,
},
await CredentialRepository.create({
type: "google_workspace_directory",
key: credentials.res?.data,
userId: session.user.id,
});

if (!teamId) {
Expand Down
13 changes: 6 additions & 7 deletions apps/web/pages/api/webhook/app-credential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { CREDENTIAL_SYNC_SECRET, CREDENTIAL_SYNC_SECRET_HEADER_NAME } from "@calcom/lib/constants";
import { APP_CREDENTIAL_SHARING_ENABLED } from "@calcom/lib/constants";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

const appCredentialWebhookRequestBodySchema = z.object({
Expand Down Expand Up @@ -78,13 +79,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
});
return res.status(200).json({ message: `Credentials updated for userId: ${reqBody.userId}` });
} else {
await prisma.credential.create({
data: {
key: keys,
userId: reqBody.userId,
appId: appMetadata.slug,
type: appMetadata.type,
},
await CredentialRepository.create({
key: keys,
userId: reqBody.userId,
appId: appMetadata.slug,
type: appMetadata.type,
});
return res.status(200).json({ message: `Credentials created for userId: ${reqBody.userId}` });
}
Expand Down
19 changes: 9 additions & 10 deletions packages/app-store/_utils/installation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Prisma } from "@prisma/client";

import { HttpError } from "@calcom/lib/http-error";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";
import type { UserProfile } from "@calcom/types/UserProfile";

Expand Down Expand Up @@ -40,16 +41,14 @@ export async function createDefaultInstallation({
paymentStatus,
subscriptionId,
}: InstallationArgs) {
const installation = await prisma.credential.create({
data: {
type: appType,
key,
...(teamId ? { teamId } : { userId: user.id }),
appId: slug,
subscriptionId,
paymentStatus,
billingCycleStart,
},
const installation = await CredentialRepository.create({
type: appType,
key,
...(teamId ? { teamId } : { userId: user.id }),
appId: slug,
subscriptionId,
paymentStatus,
billingCycleStart,
});
if (!installation) {
throw new Error(`Unable to create user credential for type ${appType}`);
Expand Down
26 changes: 11 additions & 15 deletions packages/app-store/_utils/oauth/createOAuthAppCredential.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { NextApiRequest } from "next";

import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";

import { decodeOAuthState } from "../oauth/decodeOAuthState";
import { throwIfNotHaveAdminAccessToTeam } from "../throwIfNotHaveAdminAccessToTeam";
Expand Down Expand Up @@ -31,23 +31,19 @@ const createOAuthAppCredential = async (
// Check that the user belongs to the team
await throwIfNotHaveAdminAccessToTeam({ teamId: state?.teamId ?? null, userId });

return await prisma.credential.create({
data: {
type: appData.type,
key: key || {},
teamId: state.teamId,
appId: appData.appId,
},
});
}

return await prisma.credential.create({
data: {
return await CredentialRepository.create({
type: appData.type,
key: key || {},
userId,
teamId: state.teamId,
appId: appData.appId,
},
});
}

return await CredentialRepository.create({
type: appData.type,
key: key || {},
userId,
appId: appData.appId,
});
};

Expand Down
13 changes: 6 additions & 7 deletions packages/app-store/alby/api/add.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next";

import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

import config from "../config.json";
Expand All @@ -19,13 +20,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (alreadyInstalled) {
throw new Error("Already installed");
}
const installation = await prisma.credential.create({
data: {
type: appType,
key: {},
userId: req.session.user.id,
appId: "alby",
},
const installation = await CredentialRepository.create({
type: appType,
key: {},
userId: req.session.user.id,
appId: "alby",
});

if (!installation) {
Expand Down
5 changes: 2 additions & 3 deletions packages/app-store/caldavcalendar/api/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from "next";

import { symmetricEncrypt } from "@calcom/lib/crypto";
import logger from "@calcom/lib/logger";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand Down Expand Up @@ -40,9 +41,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
user: { email: user.email },
});
await dav?.listCalendars();
await prisma.credential.create({
data,
});
await CredentialRepository.create(data);
} catch (e) {
logger.error("Could not add this caldav account", e);
if (e instanceof Error) {
Expand Down
9 changes: 2 additions & 7 deletions packages/app-store/closecom/api/_postAdd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { symmetricEncrypt } from "@calcom/lib/crypto";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";

import checkSession from "../../_utils/auth";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand All @@ -26,12 +26,7 @@ export async function getHandler(req: NextApiRequest, res: NextApiResponse) {
};

try {
await prisma.credential.create({
data,
select: {
id: true,
},
});
await CredentialRepository.create(data);
} catch (reason) {
logger.error("Could not add Close.com app", reason);
return res.status(500).json({ message: "Could not add Close.com app" });
Expand Down
5 changes: 2 additions & 3 deletions packages/app-store/exchange2013calendar/api/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from "zod";
import { symmetricEncrypt } from "@calcom/lib/crypto";
import logger from "@calcom/lib/logger";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand Down Expand Up @@ -46,9 +47,7 @@ async function postHandler(req: NextApiRequest, res: NextApiResponse) {
user: { email: user.email },
});
await dav?.listCalendars();
await prisma.credential.create({
data,
});
await CredentialRepository.create(data);
} catch (reason) {
logger.error("Could not add this exchange account", reason);
return res.status(500).json({ message: "Could not add this exchange account" });
Expand Down
5 changes: 2 additions & 3 deletions packages/app-store/exchange2016calendar/api/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from "zod";
import { symmetricEncrypt } from "@calcom/lib/crypto";
import logger from "@calcom/lib/logger";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand Down Expand Up @@ -46,9 +47,7 @@ async function postHandler(req: NextApiRequest, res: NextApiResponse) {
...data,
});
await dav?.listCalendars();
await prisma.credential.create({
data,
});
await CredentialRepository.create(data);
} catch (reason) {
logger.error("Could not add this exchange account", reason);
return res.status(500).json({ message: "Could not add this exchange account" });
Expand Down
4 changes: 2 additions & 2 deletions packages/app-store/exchangecalendar/api/_postAdd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { symmetricEncrypt } from "@calcom/lib/crypto";
import { emailSchema } from "@calcom/lib/emailSchema";
import logger from "@calcom/lib/logger";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";

import checkSession from "../../_utils/auth";
import { ExchangeAuthentication, ExchangeVersion } from "../enums";
Expand Down Expand Up @@ -39,7 +39,7 @@ export async function getHandler(req: NextApiRequest, res: NextApiResponse) {
try {
const service = new CalendarService({ id: 0, user: { email: session.user.email || "" }, ...data });
await service?.listCalendars();
await prisma.credential.create({ data });
await CredentialRepository.create(data);
} catch (reason) {
logger.info(reason);
if (reason instanceof SoapFaultDetails && reason.message != "") {
Expand Down
26 changes: 12 additions & 14 deletions packages/app-store/feishucalendar/api/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { z } from "zod";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import logger from "@calcom/lib/logger";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import prisma from "@calcom/prisma";

import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand Down Expand Up @@ -67,13 +69,11 @@ async function getHandler(req: NextApiRequest, res: NextApiResponse) {
});

if (!currentCredential) {
await prisma.credential.create({
data: {
type: "feishu_calendar",
key,
userId: req.session?.user.id,
appId: "feishu-calendar",
},
await CredentialRepository.create({
type: "feishu_calendar",
key,
userId: req.session?.user.id,
appId: "feishu-calendar",
});
} else {
await prisma.credential.update({
Expand Down Expand Up @@ -104,13 +104,11 @@ async function getHandler(req: NextApiRequest, res: NextApiResponse) {
const primaryCalendar = await primaryCalendarResponse.json();

if (primaryCalendar.data.calendars.calendar.calendar_id && req.session?.user?.id) {
await prisma.selectedCalendar.create({
data: {
userId: req.session?.user.id,
integration: "feishu_calendar",
externalId: primaryCalendar.data.calendars.calendar.calendar_id as string,
credentialId: currentCredential?.id,
},
await SelectedCalendarRepository.create({
userId: req.session?.user.id,
integration: "feishu_calendar",
externalId: primaryCalendar.data.calendars.calendar.calendar_id as string,
credentialId: currentCredential?.id,
});
}
}
Expand Down
13 changes: 6 additions & 7 deletions packages/app-store/giphy/api/add.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next";

import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";

import getInstalledAppPath from "../../_utils/getInstalledAppPath";
Expand Down Expand Up @@ -32,13 +33,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (alreadyInstalled) {
throw new Error("Already installed");
}
const installation = await prisma.credential.create({
data: {
type: appType,
key: {},
...credentialOwner,
appId: "giphy",
},
const installation = await CredentialRepository.create({
type: appType,
key: {},
...credentialOwner,
appId: "giphy",
});
if (!installation) {
throw new Error("Unable to create user credential for giphy");
Expand Down
Loading
Loading