feat: watchlist (#17947)

* lock users on signup if their email is in blacklist

* add to turbo env list

* prevent locked user or blocked email domain from using API

* Refactored to only run 1 query to find the user

* Fixing tests

* WIP

* WIP

* WIP

* Discard changes to turbo.json

* Fixed tests

* Update isLockedOrBlocked.test.ts

* Update isAdmin.integration-test.ts

* Update tsconfig.json

* chore: rename to watchlist

Signed-off-by: Omar López <[email protected]>

---------

Signed-off-by: Omar López <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-12-03 18:43:01 +01:00
1 parent 59993891b8
commit 1d8326ed83
16 files changed
+382 -34

No files matched your search

@@ -6,6 +6,7 @@ import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
import { checkIfEmailInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getLocaleFromRequest } from "@calcom/lib/getLocaleFromRequest";
import { HttpError } from "@calcom/lib/http-error";
@@ -38,6 +39,8 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
})
.parse(req.body);
const shouldLockByDefault = await checkIfEmailInWatchlistController(_email);
log.debug("handler", { email: _email });
let username: string | null = req.usernameStatus.requestedUserName;
@@ -191,6 +194,7 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
data: {
username,
email,
locked: shouldLockByDefault,
password: { create: { hash: hashedPassword } },
metadata: {
stripeCustomerId: customer.id,
@@ -0,0 +1,33 @@
import { startSpan } from "@sentry/nextjs";
import type { Watchlist } from "../watchlist.model";
import { WatchlistRepository } from "../watchlist.repository";
/**
* Controllers use Presenters to convert the data to a UI-friendly format just before
* returning it to the "consumer". This helps us ship less JavaScript to the client (logic
* and libraries to convert the data), helps prevent leaking any sensitive properties, like
* emails or hashed passwords, and also helps us slim down the amount of data we're sending
* back to the client.
*/
function presenter(watchlistedEmail: Watchlist | null) {
return startSpan({ name: "checkIfEmailInWatchlist Presenter", op: "serialize" }, () => {
return !!watchlistedEmail;
});
}
/**
* Controllers perform authentication checks and input validation before passing the input
* to the specific use cases. Controllers orchestrate Use Cases. They don't implement any
* logic, but define the whole operations using use cases.
*/
export async function checkIfEmailInWatchlistController(
email: string
): Promise<ReturnType<typeof presenter>> {
return await startSpan({ name: "checkIfEmailInWatchlist Controller" }, async () => {
const lowercasedEmail = email.toLowerCase();
const watchlistRepository = new WatchlistRepository();
const watchlistedEmail = await watchlistRepository.getEmailInWatchlist(lowercasedEmail);
return presenter(watchlistedEmail);
});
}
@@ -0,0 +1,22 @@
import type { z } from "zod";
import { _WatchlistModel } from "@calcom/prisma/zod/watchlist";
export const WatchlistModelSchema = _WatchlistModel.pick({
id: true,
type: true,
value: true,
description: true,
createdAt: true,
createdById: true,
updatedAt: true,
updatedById: true,
});
export type Watchlist = z.infer<typeof WatchlistModelSchema>;
export const insertWatchlistSchema = WatchlistModelSchema.pick({
type: true,
value: true,
description: true,
});
@@ -0,0 +1,5 @@
import type { Watchlist } from "./watchlist.model";
export interface IWatchlistRepository {
getEmailInWatchlist(email: string): Promise<Watchlist | null>;
}
@@ -0,0 +1,19 @@
import { WatchlistType } from "@calcom/prisma/enums";
import type { IWatchlistRepository } from "./watchlist.repository.interface";
export class MockFeaturesRepository implements IWatchlistRepository {
async getEmailInWatchlist(email: string) {
if (email !== "[email protected]") return null;
return {
id: "1",
type: WatchlistType.EMAIL,
value: "[email protected]",
description: "This is a watchlisted email",
createdAt: new Date(),
createdById: 1,
updatedAt: new Date(),
updatedById: 1,
};
}
}
@@ -0,0 +1,26 @@
import { captureException } from "@sentry/nextjs";
import db from "@calcom/prisma";
import { WatchlistType } from "@calcom/prisma/enums";
import type { IWatchlistRepository } from "./watchlist.repository.interface";
export class WatchlistRepository implements IWatchlistRepository {
async getEmailInWatchlist(email: string) {
const [, domain] = email.split("@");
try {
const emailInWatchlist = await db.watchlist.findFirst({
where: {
OR: [
{ type: WatchlistType.EMAIL, value: email },
{ type: WatchlistType.DOMAIN, value: domain },
],
},
});
return emailInWatchlist;
} catch (err) {
captureException(err);
throw err;
}
}
}
@@ -0,0 +1,31 @@
-- CreateEnum
CREATE TYPE "WatchlistType" AS ENUM ('EMAIL', 'DOMAIN', 'USERNAME');
-- CreateTable
CREATE TABLE "Watchlist" (
"id" TEXT NOT NULL,
"type" "WatchlistType" NOT NULL,
"value" TEXT NOT NULL,
"description" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdById" INTEGER NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedById" INTEGER,
CONSTRAINT "Watchlist_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Watchlist_id_key" ON "Watchlist"("id");
-- CreateIndex
CREATE INDEX "Watchlist_type_value_idx" ON "Watchlist"("type", "value");
-- CreateIndex
CREATE UNIQUE INDEX "Watchlist_type_value_key" ON "Watchlist"("type", "value");
-- AddForeignKey
ALTER TABLE "Watchlist" ADD CONSTRAINT "Watchlist_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Watchlist" ADD CONSTRAINT "Watchlist_updatedById_fkey" FOREIGN KEY ("updatedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+25
View File
@@ -357,6 +357,8 @@ model User {
reassignedBookings Booking[] @relation("reassignByUser")
createdTranslations EventTypeTranslation[] @relation("CreatedEventTypeTranslations")
updatedTranslations EventTypeTranslation[] @relation("UpdatedEventTypeTranslations")
createdWatchlists Watchlist[] @relation("CreatedWatchlists")
updatedWatchlists Watchlist[] @relation("UpdatedWatchlists")
@@unique([email])
@@unique([email, username])
@@ -1659,3 +1661,26 @@ model EventTypeTranslation {
@@index([eventTypeId, field, targetLang]) // TODO: remove after migration
@@index([eventTypeId, field, targetLocale])
}
enum WatchlistType {
EMAIL
DOMAIN
USERNAME
}
model Watchlist {
id String @id @unique @default(cuid())
type WatchlistType
// The identifier of the Watchlisted entity (email or domain)
value String
description String?
createdAt DateTime @default(now())
createdBy User @relation("CreatedWatchlists", onDelete: Cascade, fields: [createdById], references: [id])
createdById Int
updatedAt DateTime @updatedAt
updatedBy User? @relation("UpdatedWatchlists", onDelete: SetNull, fields: [updatedById], references: [id])
updatedById Int?
@@unique([type, value])
@@index([type, value])
}