PromucFlow_constructor/app/client/src/pages/common/datasourceAuth/index.tsx

307 lines
8.7 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect } from "react";
import styled from "styled-components";
import {
ActionButton,
SaveButtonContainer,
} from "pages/Editor/DataSourceEditor/JSONtoForm";
import EditButton from "components/editorComponents/Button";
import { useDispatch, useSelector } from "react-redux";
import {
getEntities,
getPluginTypeFromDatasourceId,
getIsReconnectingDatasourcesModalOpen,
} from "selectors/entitiesSelector";
import {
testDatasource,
deleteDatasource,
updateDatasource,
redirectAuthorizationCode,
getOAuthAccessToken,
} from "actions/datasourceActions";
import AnalyticsUtil from "utils/AnalyticsUtil";
import { redirectToNewIntegrations } from "actions/apiPaneActions";
2022-08-04 05:40:44 +00:00
import { getQueryParams } from "utils/URLUtils";
import { getCurrentApplicationId } from "selectors/editorSelectors";
import { useParams, useLocation } from "react-router";
import { ExplorerURLParams } from "pages/Editor/Explorer/helpers";
import { getIsGeneratePageInitiator } from "utils/GenerateCrudUtil";
import { ButtonVariantTypes } from "components/constants";
import { AppState } from "@appsmith/reducers";
import {
AuthType,
Datasource,
AuthenticationStatus,
} from "entities/Datasource";
import {
OAUTH_AUTHORIZATION_APPSMITH_ERROR,
OAUTH_AUTHORIZATION_FAILED,
} from "@appsmith/constants/messages";
chore: migrate toast (#17208) * Refactor toast to be passed the dispatch hook externally * Add comments explaining dilemma * use store.dispatch instead of a hook * use alpha version * Change imports * Refactor DebugButton out * update release * fix issue with incorrectly merged package.lock * fix syntax of alpha version * bump ds vesion * copy lock from release * update lock to have alpha * make changes * delete Toast * DS package version updated * import change from release * use new alpha version * update ds version * update ds version * chore: migrate editable text and friends (#17285) * Delete empty components * use alpha for ds * Deleted EditableTextSubComponent, import changes * Delete EditableText, import changes * use ds alpha 10 * Delete EditableTextWrapper.tsx * update ds to use next minor version * use new alpha * fix issue with merge Co-authored-by: Albin <albin@appsmith.com> * chore: migrate file picker v2 (#17308) * use alpha ds * Delete FilePickerV2, import changes * Delete FilePicker, change imports * update alpha version * chore: move copy url form into setting components (#17322) * move CopyUrlForm to src/pages/settings/formgroup * update ds version to use next minor release * feat: Migrate table component to design system (#17329) * feat: Migrate table component to design system * removed commented code in ads index file * fix: table no data hover effect removed Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com> * feat: Banner message component migrated to design system (#17327) * feat: Banner image component migrated to design system * Version update for design system package * design system version updated Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com> * feat: Tabs component migrated to design system (#17321) * feat: Tabs component migrated to design system * design system package version updated * Update app/client/src/components/editorComponents/form/FormDialogComponent.tsx * Update app/client/src/pages/Editor/PropertyPane/PropertyPaneTab.tsx * Tab component expand issue fix Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com> Co-authored-by: Albin <albin@appsmith.com> Co-authored-by: albinAppsmith <87797149+albinAppsmith@users.noreply.github.com>
2022-10-13 20:13:44 +00:00
import { Toaster } from "design-system";
import { Variant } from "components/ads/common";
import {
CONTEXT_DELETE,
CONFIRM_CONTEXT_DELETE,
createMessage,
} from "@appsmith/constants/messages";
import { debounce } from "lodash";
interface Props {
datasource: Datasource;
formData: Datasource;
getSanitizedFormData: () => Datasource;
isInvalid: boolean;
feat: 9754 import work flow (#10453) * updated import application modal design as v2 * updated import flow * added title, description, uploadIcon on filepicker ads component for custom file picker * adding modal of add credential for git import * added "Git Import" modal * added generating ssh key for importing flow * fixed issue of merging * chore: fix import * chore: show old import modal based on feature flag * seperated import api from connect * added datasource list on reconnect credential modal * chore: minor changes * chore: move ssh keys to git sync reducer from applications reducer * chore: minor fixes * chore: fetch datasource config for import * for pulling * for review of displaying of datasource * added reconnect datasources after git import * fix: initialize datasource with default values * fix: initialise redux for after updating datasource with default values * fixed issue of git connection init when importing * if there is a datasource config missing in import, reconnect modal should be opened * updated logic for unconfigured datasources * commented unnecessary code * fixed issue of successful import * updated import app error logic * Add un-configured datasources to Import via file response * Add test * fix * chore: refactors * change per review * fix: reset ssh keys / url * Fix issue with newly created datasources not sent * fix * chore: minor updates * chore: minor fix * WIP * added saas and rest api datasource form * feat: fixes and updates for file import flow * chore: close on upload * Refactor logic ofr finding unconfigured datasources * fix: minor fixes * Fix issue with IsPartialImport * fix * Add PartialImport flag for ImportExport service * refactoring of datasource editor form for both of importing app and editing app * fixed collapse config * Fix tests * Handle redirection back to the /applications for oAuth type * Show reconnect button on the datasources pages if the datasource configuration is skipped * added analytic events for reconnecting datasource modal * Fix the repo limit check for git import * updated test of importing app from json as new work flow * updated exported app json while testing automatically * Add isImport flag for handling OAuth redirection in import flow * WIP * updated card UI for import from git title and message in import app modal * chore: cleanup * chore: lint * fix: add is import query param to get token for oauth * fix * When the user imports the application there should not be any uncommitted changes displayed on the commit icon * Add flag to identify OAuth redirection for git import * Update the variable name * refactoring reconnect datasource modal * close git import modal when repo limit error responded * fixed issue of restoring draft data of datasource form without save on reconnect datasource modal * chore: update query * updated query name of oauth redirection url * Fix duplicate name issue in git import * fixed rest api reconnect issue on reconnect modal * init datasources and plugins after imported app, updated reconnect modal as new design * added unconfigured datasource list logic when importing and updated rest api form delete button visible * removed put default config of datasource and fixed issue on it * Add logic to check isCOnfugred in datasource API * Expose API to get un configured datasources for git import * added fetch unconfigured datasource list api when redirecting form OAuth * Remove sensitive fields from application json during export * update put call response to check for datasourceConfig * chore: use @appsmith for constants/messages * chore: use download icon and Import for Importing application label * chore: move import application text up a bit * Fix bad merge * chore: update skip to application tooltip text * fixed tooltip content of skip to application CTA * init values of datasource when importing * updated ui of git import modal as figma design * fixing padding issue of reconnect datasource modal * fixed cursor issue on import app modal * Fix issue with datasource config * chore: make code compile * chore: sort lines * fixed save button issue of dbform on reconnecting modal * fixed style of import application modal * Fix iisue with wrong value updated to flag * reverted from reconnection form style * fix: update design as per slack discussions on 2022.02.23 * fix: move modal close button to the left * Remove check for the flag and use the one from db * Set siCOnfigured as true for mockdata sets * updated creating datasource with isConfigured as false * Fix NPE while importing * fixed scrollbar issue and text alignment on reconnect datasource modal * fixed style of form container in reconnect datasource and redirecting to app if all are configured * remove unwanted fields from application json * FIx NPE for file import * fix: move close button up in import modal * remove delete button on reconnect datasource modal * Add isConfigured false while creating datasources * fix: add a gap and update color gap between git import dialog title and subtitle update color of subtext to GREY_800 * fix: use git import feature flag * fix: do not use older modal * updated selecting logic of unconfigured datasource in reconnect modal * cleanup: auto format * cleanup: refactor react component * cleanup: refactor some more * cleanup: autoformat * Fix reconnect flag for mockdatasource * During git import set the isConfigured to false for datasources * Remove decrypted field from the applicationJson file * Remove decrypted field from the applicationJson file * Add app slug to remote repo * fixed cypress test related with git * updated json while testing * Changes per review * Update the method name * fixed cypress test related with git * fixed migration cypress test * set is configured field as true on tour app * Fix issue with datasource creation for welcome tour * fixed issue of replay_editor cypress test Co-authored-by: Rishabh Saxena <rishabh@appsmith.com> Co-authored-by: Anagh Hegde <anagh@appsmith.com> Co-authored-by: Anubhav <anubhav@appsmith.com> Co-authored-by: f0c1s <iamanubhavsaini+git@gmail.com>
2022-03-17 10:28:54 +00:00
pageId?: string;
shouldRender: boolean;
datasourceButtonConfiguration: string[] | undefined;
}
export type DatasourceFormButtonTypes = Record<string, string[]>;
enum AuthorizationStatus {
SUCCESS = "success",
APPSMITH_ERROR = "appsmith_error",
}
export enum DatasourceButtonTypeEnum {
DELETE = "DELETE",
SAVE = "SAVE",
TEST = "TEST",
SAVE_AND_AUTHORIZE = "SAVE_AND_AUTHORIZE",
}
export const DatasourceButtonType: Record<
keyof typeof DatasourceButtonTypeEnum,
string
> = {
DELETE: "DELETE",
SAVE: "SAVE",
TEST: "TEST",
SAVE_AND_AUTHORIZE: "SAVE_AND_AUTHORIZE",
};
const StyledButton = styled(EditButton)<{ fluidWidth?: boolean }>`
&&&& {
height: 32px;
width: ${(props) => (props.fluidWidth ? "" : "87px")};
}
`;
const StyledAuthMessage = styled.div`
color: ${(props) => props.theme.colors.error};
margin-top: 15px;
&:after {
content: " *";
color: inherit;
}
`;
function DatasourceAuth({
datasource,
datasourceButtonConfiguration = ["DELETE", "SAVE"],
formData,
getSanitizedFormData,
isInvalid,
pageId: pageIdProp,
shouldRender,
}: Props) {
const authType =
formData &&
formData?.datasourceConfiguration?.authentication?.authenticationType;
const { id: datasourceId } = datasource;
const applicationId = useSelector(getCurrentApplicationId);
// hooks
const dispatch = useDispatch();
const location = useLocation();
const { pageId: pageIdQuery } = useParams<ExplorerURLParams>();
const pageId = (pageIdQuery || pageIdProp) as string;
const [confirmDelete, setConfirmDelete] = useState(false);
useEffect(() => {
if (confirmDelete) {
delayConfirmDeleteToFalse();
}
}, [confirmDelete]);
const delayConfirmDeleteToFalse = debounce(
() => setConfirmDelete(false),
2200,
);
useEffect(() => {
if (authType === AuthType.OAUTH2) {
// When the authorization server redirects a user to the datasource form page, the url contains the "response_status" query parameter .
// Get the access token if response_status is successful else show a toast error
const search = new URLSearchParams(location.search);
const status = search.get("response_status");
const queryIsImport = search.get("importForGit");
const queryDatasourceId = search.get("datasourceId");
const shouldNotify =
!queryIsImport || (queryIsImport && queryDatasourceId === datasourceId);
if (status && shouldNotify) {
const display_message = search.get("display_message");
const variant = Variant.danger;
if (status !== AuthorizationStatus.SUCCESS) {
const message =
status === AuthorizationStatus.APPSMITH_ERROR
? OAUTH_AUTHORIZATION_APPSMITH_ERROR
: OAUTH_AUTHORIZATION_FAILED;
Toaster.show({ text: display_message || message, variant });
} else {
dispatch(getOAuthAccessToken(datasourceId));
}
AnalyticsUtil.logEvent("DATASOURCE_AUTH_COMPLETE", {
applicationId,
datasourceId,
pageId,
});
}
}
}, [authType]);
// selectors
const {
datasources: { isDeleting, isTesting, loading: isSaving },
} = useSelector(getEntities);
const pluginType = useSelector((state: AppState) =>
getPluginTypeFromDatasourceId(state, datasourceId),
);
// to check if saving during import flow
const isReconnectModelOpen: boolean = useSelector(
getIsReconnectingDatasourcesModalOpen,
);
const isAuthorized =
datasource?.datasourceConfiguration?.authentication
?.authenticationStatus === AuthenticationStatus.SUCCESS;
// Button Operations for respective buttons.
// Handles datasource deletion
const handleDatasourceDelete = () => {
dispatch(deleteDatasource({ id: datasourceId }));
};
// Handles datasource testing
const handleDatasourceTest = () => {
AnalyticsUtil.logEvent("TEST_DATA_SOURCE_CLICK", {
pageId: pageId,
appId: applicationId,
});
dispatch(testDatasource(getSanitizedFormData()));
};
// Handles default auth datasource saving
const handleDefaultAuthDatasourceSave = () => {
const isGeneratePageInitiator = getIsGeneratePageInitiator();
AnalyticsUtil.logEvent("SAVE_DATA_SOURCE_CLICK", {
pageId: pageId,
appId: applicationId,
});
// After saving datasource, only redirect to the 'new integrations' page
// if datasource is not used to generate a page
dispatch(
updateDatasource(
getSanitizedFormData(),
!isGeneratePageInitiator && !isReconnectModelOpen
? dispatch(redirectToNewIntegrations(pageId, getQueryParams()))
: undefined,
),
);
};
// Handles Oauth datasource saving
const handleOauthDatasourceSave = () => {
dispatch(
updateDatasource(
getSanitizedFormData(),
pluginType
? redirectAuthorizationCode(pageId, datasourceId, pluginType)
: undefined,
),
);
};
const datasourceButtonsComponentMap = (buttonType: string): JSX.Element => {
return {
[DatasourceButtonType.DELETE]: (
<ActionButton
buttonStyle="DANGER"
buttonVariant={ButtonVariantTypes.PRIMARY}
// accent="error"
className="t--delete-datasource"
loading={isDeleting}
onClick={() => {
confirmDelete ? handleDatasourceDelete() : setConfirmDelete(true);
}}
text={
confirmDelete
? createMessage(CONFIRM_CONTEXT_DELETE)
: createMessage(CONTEXT_DELETE)
}
/>
),
[DatasourceButtonType.TEST]: (
<ActionButton
// accent="secondary"
buttonStyle="PRIMARY"
buttonVariant={ButtonVariantTypes.SECONDARY}
className="t--test-datasource"
loading={isTesting}
onClick={handleDatasourceTest}
text="Test"
/>
),
[DatasourceButtonType.SAVE]: (
<StyledButton
className="t--save-datasource"
disabled={isInvalid}
filled
intent="primary"
loading={isSaving}
onClick={handleDefaultAuthDatasourceSave}
size="small"
text="Save"
/>
),
[DatasourceButtonType.SAVE_AND_AUTHORIZE]: (
<StyledButton
className="t--save-datasource"
disabled={isInvalid}
filled
fluidWidth
intent="primary"
loading={isSaving}
onClick={handleOauthDatasourceSave}
size="small"
text={isAuthorized ? "Save and Re-authorize" : "Save and Authorize"}
/>
),
}[buttonType];
};
return (
<>
{authType === AuthType.OAUTH2 && !isAuthorized && (
<StyledAuthMessage>Datasource not authorized</StyledAuthMessage>
)}
{shouldRender && (
<SaveButtonContainer>
{datasourceButtonConfiguration?.map((btnConfig) =>
datasourceButtonsComponentMap(btnConfig),
)}
</SaveButtonContainer>
)}
{""}
</>
);
}
export default DatasourceAuth;