From ea9096f1e8cdeac6e6759758fdb87ce5104f9c3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daphn=C3=A9=20Popin?= Date: Tue, 20 Feb 2024 10:43:07 +0100 Subject: [PATCH] =?UTF-8?q?Pok=C3=A9=20-=20search=20by=20email=20(#3809)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- front/lib/models/user.ts | 4 ++ front/pages/api/poke/workspaces/index.ts | 52 ++++++++++++++++++------ 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/front/lib/models/user.ts b/front/lib/models/user.ts index 7b86445899d0..cf7778c93158 100644 --- a/front/lib/models/user.ts +++ b/front/lib/models/user.ts @@ -3,10 +3,12 @@ import type { ForeignKey, InferAttributes, InferCreationAttributes, + NonAttribute, } from "sequelize"; import { DataTypes, Model } from "sequelize"; import { front_sequelize } from "@app/lib/databases"; +import type { Membership } from "@app/lib/models"; export class User extends Model< InferAttributes, @@ -25,6 +27,8 @@ export class User extends Model< declare imageUrl: string | null; declare isDustSuperUser: CreationOptional; + + declare memberships: NonAttribute; } User.init( { diff --git a/front/pages/api/poke/workspaces/index.ts b/front/pages/api/poke/workspaces/index.ts index 53770d89f9ab..a89580fae4f9 100644 --- a/front/pages/api/poke/workspaces/index.ts +++ b/front/pages/api/poke/workspaces/index.ts @@ -4,7 +4,8 @@ import type { FindOptions, WhereOptions } from "sequelize"; import { Op } from "sequelize"; import { Authenticator, getSession } from "@app/lib/auth"; -import { Subscription, Workspace } from "@app/lib/models"; +import { Membership, Subscription, User, Workspace } from "@app/lib/models"; +import { isEmailValid } from "@app/lib/utils"; import { apiError, withLogging } from "@app/logger/withlogging"; export type GetWorkspacesResponseBody = { @@ -109,20 +110,45 @@ async function handler( } if (search) { - conditions.push({ - [Op.or]: [ - { - sId: { - [Op.iLike]: `${search}%`, - }, + let isSearchByEmail = false; + if (isEmailValid(search)) { + const user = await User.findOne({ + where: { + email: search, }, - { - name: { - [Op.iLike]: `${search}%`, + include: [ + { + model: Membership, + attributes: ["workspaceId"], }, - }, - ], - }); + ], + }); + if (user?.memberships) { + conditions.push({ + id: { + [Op.in]: user?.memberships.map((m) => m.workspaceId), + }, + }); + isSearchByEmail = true; + } + } + + if (!isSearchByEmail) { + conditions.push({ + [Op.or]: [ + { + sId: { + [Op.iLike]: `${search}%`, + }, + }, + { + name: { + [Op.iLike]: `${search}%`, + }, + }, + ], + }); + } } const where: FindOptions["where"] = conditions.length