From fa33516f1a9e90bbcf6337dcf9c6637f4545ba5d Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Tue, 4 Jul 2023 18:57:42 +0530 Subject: [PATCH] fix: creation and deletion --- app/hooks/useRequest.ts | 6 +- app/models/Integration.ts | 2 - app/stores/IntegrationsStore.ts | 10 +- plugins/iframely/client/Settings.tsx | 148 ++++++++++-------- server/commands/integrationCreator.ts | 49 +++--- ...3843-add-integration-to-authentications.js | 66 -------- ...-change-authentication-col-integrations.js | 50 ------ server/models/IntegrationAuthentication.ts | 12 -- .../routes/api/integrations/integrations.ts | 12 +- shared/i18n/locales/en_US/translation.json | 13 +- 10 files changed, 140 insertions(+), 228 deletions(-) delete mode 100644 server/migrations/20230510153843-add-integration-to-authentications.js delete mode 100644 server/migrations/20230511121809-change-authentication-col-integrations.js diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts index c68b43d7b1..218d045bcd 100644 --- a/app/hooks/useRequest.ts +++ b/app/hooks/useRequest.ts @@ -7,6 +7,8 @@ type RequestResponse = { error: unknown; /** Whether the request is currently in progress. */ loading: boolean; + /** Whether the request has successfully completed */ + loaded: boolean; /** Function to start the request. */ request: () => Promise; }; @@ -22,6 +24,7 @@ export default function useRequest( ): RequestResponse { const [data, setData] = React.useState(); const [loading, setLoading] = React.useState(false); + const [loaded, setLoaded] = React.useState(false); const [error, setError] = React.useState(); const request = React.useCallback(async () => { @@ -29,6 +32,7 @@ export default function useRequest( try { const response = await requestFn(); setData(response); + setLoaded(true); return response; } catch (err) { setError(err); @@ -39,5 +43,5 @@ export default function useRequest( return undefined; }, [requestFn]); - return { data, loading, error, request }; + return { data, loading, loaded, error, request }; } diff --git a/app/models/Integration.ts b/app/models/Integration.ts index 52bb7f6d49..5799ea78b8 100644 --- a/app/models/Integration.ts +++ b/app/models/Integration.ts @@ -16,8 +16,6 @@ class Integration extends BaseModel { collectionId: string; - authToken?: string | null; - @Field @observable events: string[]; diff --git a/app/stores/IntegrationsStore.ts b/app/stores/IntegrationsStore.ts index ceb36795f1..e0c0cd982f 100644 --- a/app/stores/IntegrationsStore.ts +++ b/app/stores/IntegrationsStore.ts @@ -1,5 +1,5 @@ import { filter } from "lodash"; -import { computed } from "mobx"; +import { action, computed } from "mobx"; import { IntegrationService } from "@shared/types"; import naturalSort from "@shared/utils/naturalSort"; import BaseStore from "~/stores/BaseStore"; @@ -22,6 +22,14 @@ class IntegrationsStore extends BaseStore { service: IntegrationService.Slack, }); } + + @action + async create( + params: Partial, + options?: Record + ) { + return super.create(params, options); + } } export default IntegrationsStore; diff --git a/plugins/iframely/client/Settings.tsx b/plugins/iframely/client/Settings.tsx index 09afbd2801..c543d549e8 100644 --- a/plugins/iframely/client/Settings.tsx +++ b/plugins/iframely/client/Settings.tsx @@ -8,21 +8,37 @@ import Integration from "~/models/Integration"; import Button from "~/components/Button"; import Heading from "~/components/Heading"; import Input from "~/components/Input"; +import LoadingIndicator from "~/components/LoadingIndicator"; import Scene from "~/components/Scene"; +import Text from "~/components/Text"; +import useRequest from "~/hooks/useRequest"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; -import SlackIcon from "./Icon"; +import IframelyIcon from "./Icon"; import SettingRow from "./components/SettingRow"; type FormData = { - url: string; - authToken: string; + baseUrl: string; + apiKey: string; }; function Iframely() { const { integrations } = useStores(); const { t } = useTranslation(); const { showToast } = useToasts(); + const [disconnecting, setDisconnecting] = React.useState(false); + + const { loading, loaded, request } = useRequest(() => + integrations.fetchPage({ + type: IntegrationType.Embed, + }) + ); + + React.useEffect(() => { + if (!loaded && !loading) { + void request(); + } + }, [loaded, loading, request]); const integration = find(integrations.orderedData, { type: IntegrationType.Embed, @@ -36,49 +52,22 @@ function Iframely() { formState, } = useForm({ mode: "all", - - defaultValues: { - url: integration?.settings.url, - authToken: - integration && integration.authToken - ? integration.authToken - : undefined, - }, }); - React.useEffect(() => { - void integrations.fetchPage({ - type: IntegrationType.Embed, - }); - }, [integrations]); - - React.useEffect(() => { - reset({ - url: integration?.settings.url, - authToken: - integration && integration.authToken - ? integration.authToken - : undefined, - }); - }, [integration, reset]); - const handleSubmit = React.useCallback( async (data: FormData) => { try { - if (data.url) { - await integrations.save({ - id: integration?.id, + if (data.baseUrl) { + await integrations.create({ type: IntegrationType.Embed, service: IntegrationService.Iframely, - authToken: data.authToken ? data.authToken : null, - settings: data.url + authToken: data.apiKey ? data.apiKey : null, + settings: data.baseUrl ? { - url: data.url, + url: data.baseUrl, } : undefined, }); - } else { - await integration?.delete(); } showToast(t("Settings saved"), { @@ -93,35 +82,70 @@ function Iframely() { [integrations, integration, t, showToast] ); - return ( - }> - {t("Iframely")} + const disconnect = React.useCallback(async () => { + setDisconnecting(true); + try { + await integration?.delete(); + showToast(t("Integration disconnected"), { + type: "success", + }); + reset(); + } catch (err) { + showToast(err.message, { + type: "error", + }); + } finally { + setDisconnecting(false); + } + }, [integration]); -
- - - - - - - +
+ ) : ( + - + )}
); } diff --git a/server/commands/integrationCreator.ts b/server/commands/integrationCreator.ts index b1f61a5d42..f58a3697ec 100644 --- a/server/commands/integrationCreator.ts +++ b/server/commands/integrationCreator.ts @@ -4,7 +4,7 @@ import { IntegrationSettings, IntegrationType, } from "@shared/types"; -import { User, Integration, IntegrationAuthentication } from "@server/models"; +import { User, Integration } from "@server/models"; import { UserCreatableIntegrationService } from "@server/models/Integration"; type Props = { @@ -30,7 +30,7 @@ export default async function integrationCreator({ events, transaction, }: Props) { - let integration = await Integration.create( + return Integration.create( { userId: user.id, teamId: user.teamId, @@ -39,32 +39,25 @@ export default async function integrationCreator({ collectionId, events, type, + authentication: token + ? { + userId: user.id, + teamId: user.teamId, + service, + scopes: authScopes, + token, + } + : undefined, }, - { transaction } + { + include: token + ? [ + { + association: "authentication", + }, + ] + : undefined, + transaction, + } ); - - let authentication: IntegrationAuthentication | undefined; - if (token) { - authentication = await IntegrationAuthentication.create( - { - userId: user.id, - teamId: user.teamId, - integrationId: integration.id, - service, - scopes: authScopes, - token, - }, - { transaction } - ); - - integration.authenticationId = authentication.id; - await integration.save({ transaction }); - } - - integration = (await Integration.scope("withAuthentication").findByPk( - integration.id, - { transaction } - )) as Integration; - - return integration; } diff --git a/server/migrations/20230510153843-add-integration-to-authentications.js b/server/migrations/20230510153843-add-integration-to-authentications.js deleted file mode 100644 index 68f053fb31..0000000000 --- a/server/migrations/20230510153843-add-integration-to-authentications.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; - -module.exports = { - async up(queryInterface, Sequelize) { - await queryInterface.sequelize.transaction(async (transaction) => { - await queryInterface.addColumn( - "authentications", - "integrationId", - { - type: Sequelize.UUID, - allowNull: true, - onDelete: "cascade", - unique: true, - references: { - model: "integrations", - }, - }, - { transaction } - ); - - const integrations = await queryInterface.sequelize.query( - `SELECT id, "authenticationId" FROM integrations where "authenticationId" is not null`, - { - type: queryInterface.sequelize.QueryTypes.SELECT, - transaction, - } - ); - - for (const integration of integrations) { - await queryInterface.sequelize.query( - `UPDATE authentications SET "integrationId" = :integrationId WHERE id = :authenticationId and "integrationId" is null`, - { - type: queryInterface.sequelize.QueryTypes.UPDATE, - replacements: { - integrationId: integration.id, - authenticationId: integration.authenticationId, - }, - transaction, - } - ); - } - - await queryInterface.sequelize.query( - `DELETE from authentications WHERE "integrationId" is null`, - { - type: queryInterface.sequelize.QueryTypes.DELETE, - transaction, - } - ); - - await queryInterface.changeColumn( - "authentications", - "integrationId", - { - type: Sequelize.UUID, - allowNull: false, - }, - { transaction } - ); - }); - }, - - async down(queryInterface, Sequelize) { - await queryInterface.removeColumn("authentications", "integrationId"); - }, -}; diff --git a/server/migrations/20230511121809-change-authentication-col-integrations.js b/server/migrations/20230511121809-change-authentication-col-integrations.js deleted file mode 100644 index 261dc59ed4..0000000000 --- a/server/migrations/20230511121809-change-authentication-col-integrations.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -module.exports = { - async up(queryInterface, Sequelize) { - await queryInterface.sequelize.transaction(async (transaction) => { - await queryInterface.removeConstraint( - "integrations", - "integrations_authenticationId_fkey", - { transaction } - ); - await queryInterface.changeColumn( - "integrations", - "authenticationId", - { - type: Sequelize.UUID, - allowNull: true, - unique: true, - onDelete: "SET NULL", - references: { - model: "authentications", - }, - }, - { transaction } - ); - }); - }, - - async down(queryInterface, Sequelize) { - await queryInterface.sequelize.transaction(async (transaction) => { - await queryInterface.removeConstraint( - "integrations", - "integrations_authenticationId_fkey", - { transaction } - ); - await queryInterface.changeColumn( - "integrations", - "authenticationId", - { - type: Sequelize.UUID, - allowNull: true, - onDelete: "CASCADE", - references: { - model: "authentications", - }, - }, - { transaction } - ); - }); - }, -}; diff --git a/server/models/IntegrationAuthentication.ts b/server/models/IntegrationAuthentication.ts index d41872fb61..207258affc 100644 --- a/server/models/IntegrationAuthentication.ts +++ b/server/models/IntegrationAuthentication.ts @@ -4,11 +4,8 @@ import { ForeignKey, BelongsTo, Column, - Unique, - AllowNull, } from "sequelize-typescript"; import { IntegrationService } from "@shared/types"; -import Integration from "./Integration"; import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; @@ -52,15 +49,6 @@ class IntegrationAuthentication extends IdModel { @ForeignKey(() => Team) @Column(DataType.UUID) teamId: string; - - @BelongsTo(() => Integration, "integrationId") - integration: Integration; - - @ForeignKey(() => Integration) - @Unique - @AllowNull(false) - @Column(DataType.UUID) - integrationId: string; } export default IntegrationAuthentication; diff --git a/server/routes/api/integrations/integrations.ts b/server/routes/api/integrations/integrations.ts index 76a227f562..669b04027a 100644 --- a/server/routes/api/integrations/integrations.ts +++ b/server/routes/api/integrations/integrations.ts @@ -5,7 +5,7 @@ import integrationUpdater from "@server/commands/integrationUpdater"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { Event, Integration } from "@server/models"; +import { Event, Integration, IntegrationAuthentication } from "@server/models"; import { authorize } from "@server/policies"; import { presentIntegration } from "@server/presenters"; import { APIContext } from "@server/types"; @@ -122,6 +122,16 @@ router.post( authorize(user, "delete", integration); await integration.destroy({ transaction }); + // also remove the corresponding authentication if it exists + if (integration.authenticationId) { + await IntegrationAuthentication.destroy({ + where: { + id: integration.authenticationId, + }, + transaction, + }); + } + await Event.create( { name: "integrations.delete", diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 60dd8c2b89..a21b321bc3 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -861,17 +861,20 @@ "This month": "This month", "Last month": "Last month", "This year": "This year", + "Integration disconnected": "Integration disconnected", "Iframely": "Iframely", - "Iframely url": "Iframely url", - "Add your Iframely url here.": "Add your Iframely url here.", - "Iframely key": "Iframely key", - "Add your Iframely key here.": "Add your Iframely key here.", + "Get rich previews of links in documents": "Get rich previews of links in documents", + "Deployment url": "Deployment url", + "Optionally add your self-hosted Iframely installation url here or leave blank to use the cloud hosted Iframely.": "Optionally add your self-hosted Iframely installation url here or leave blank to use the cloud hosted Iframely.", + "API key": "API key", + "Add your Iframely API key to enable previewing of links.": "Add your Iframely API key to enable previewing of links.", + "Disconnecting": "Disconnecting", + "Disconnect": "Disconnect", "Add to Slack": "Add to Slack", "document published": "document published", "document updated": "document updated", "Posting to the {{ channelName }} channel on": "Posting to the {{ channelName }} channel on", "These events should be posted to Slack": "These events should be posted to Slack", - "Disconnect": "Disconnect", "Whoops, you need to accept the permissions in Slack to connect {{appName}} to your team. Try again?": "Whoops, you need to accept the permissions in Slack to connect {{appName}} to your team. Try again?", "Something went wrong while authenticating your request. Please try logging in again?": "Something went wrong while authenticating your request. Please try logging in again?", "Get rich previews of {{ appName }} links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.": "Get rich previews of {{ appName }} links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.",