Remove window.authType (#437)

This commit is contained in:
Steve Faulkner 2021-02-22 14:43:58 -06:00 committed by GitHub
parent e092e5140f
commit 07474b8271
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 129 additions and 162 deletions

View File

@ -220,7 +220,6 @@ describe("MongoProxyClient", () => {
describe("getEndpoint", () => {
beforeEach(() => {
resetConfigContext();
delete window.authType;
updateUserContext({
databaseAccount,
});
@ -241,7 +240,9 @@ describe("MongoProxyClient", () => {
});
it("returns a guest endpoint", () => {
window.authType = AuthType.EncryptedToken;
updateUserContext({
authType: AuthType.EncryptedToken,
});
const endpoint = getEndpoint();
expect(endpoint).toEqual("https://main.documentdb.ext.azure.com/api/guest/mongo/explorer");
});

View File

@ -20,7 +20,7 @@ const defaultHeaders = {
};
function authHeaders() {
if (window.authType === AuthType.EncryptedToken) {
if (userContext.authType === AuthType.EncryptedToken) {
return { [HttpHeaders.guestAccessToken]: userContext.accessToken };
} else {
return { [HttpHeaders.authorization]: userContext.authorizationToken };
@ -337,7 +337,7 @@ export function createMongoCollectionWithProxy(
export function getEndpoint(): string {
let url = (configContext.MONGO_BACKEND_ENDPOINT || configContext.BACKEND_ENDPOINT) + "/api/mongo/explorer";
if (window.authType === AuthType.EncryptedToken) {
if (userContext.authType === AuthType.EncryptedToken) {
url = url.replace("api/mongo", "api/guest/mongo");
}
return url;

View File

@ -27,13 +27,17 @@ describe("createCollection", () => {
});
it("should call ARM if logged in with AAD", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
await createCollection(createCollectionParams);
expect(armRequest).toHaveBeenCalled();
});
it("should call SDK if not logged in with non-AAD method", async () => {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
(client as jest.Mock).mockReturnValue({
databases: {
createIfNotExists: () => {

View File

@ -35,7 +35,7 @@ export const createCollection = async (params: DataModels.CreateCollectionParams
);
try {
let collection: DataModels.Collection;
if (window.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (userContext.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (params.createNewDatabase) {
const createDatabaseParams: DataModels.CreateDatabaseParams = {
autoPilotMaxThroughput: params.autoPilotMaxThroughput,

View File

@ -34,7 +34,7 @@ export async function createDatabase(params: DataModels.CreateDatabaseParams): P
if (userContext.defaultExperience === DefaultAccountExperienceType.Table) {
throw new Error("Creating database resources is not allowed for tables accounts");
}
const database: DataModels.Database = await (window.authType === AuthType.AAD && !userContext.useSDKOperations
const database: DataModels.Database = await (userContext.authType === AuthType.AAD && !userContext.useSDKOperations
? createDatabaseWithARM(params)
: createDatabaseWithSDK(params));

View File

@ -22,7 +22,7 @@ export async function createStoredProcedure(
const clearMessage = logConsoleProgress(`Creating stored procedure ${storedProcedure.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -19,7 +19,7 @@ export async function createTrigger(
const clearMessage = logConsoleProgress(`Creating trigger ${trigger.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -22,7 +22,7 @@ export async function createUserDefinedFunction(
const clearMessage = logConsoleProgress(`Creating user defined function ${userDefinedFunction.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -20,13 +20,17 @@ describe("deleteCollection", () => {
});
it("should call ARM if logged in with AAD", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
await deleteCollection("database", "collection");
expect(armRequest).toHaveBeenCalled();
});
it("should call SDK if not logged in with non-AAD method", async () => {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
(client as jest.Mock).mockReturnValue({
database: () => {
return {

View File

@ -13,7 +13,7 @@ import { client } from "../CosmosClient";
export async function deleteCollection(databaseId: string, collectionId: string): Promise<void> {
const clearMessage = logConsoleProgress(`Deleting container ${collectionId}`);
try {
if (window.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (userContext.authType === AuthType.AAD && !userContext.useSDKOperations) {
await deleteCollectionWithARM(databaseId, collectionId);
} else {
await client().database(databaseId).container(collectionId).delete();

View File

@ -20,13 +20,17 @@ describe("deleteDatabase", () => {
});
it("should call ARM if logged in with AAD", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
await deleteDatabase("database");
expect(armRequest).toHaveBeenCalled();
});
it("should call SDK if not logged in with non-AAD method", async () => {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
(client as jest.Mock).mockReturnValue({
database: () => {
return {

View File

@ -16,7 +16,7 @@ export async function deleteDatabase(databaseId: string): Promise<void> {
if (userContext.defaultExperience === DefaultAccountExperienceType.Table) {
throw new Error("Deleting database resources is not allowed for tables accounts");
}
if (window.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (userContext.authType === AuthType.AAD && !userContext.useSDKOperations) {
await deleteDatabaseWithARM(databaseId);
} else {
await client().database(databaseId).delete();

View File

@ -14,7 +14,7 @@ export async function deleteStoredProcedure(
const clearMessage = logConsoleProgress(`Deleting stored procedure ${storedProcedureId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -10,7 +10,7 @@ export async function deleteTrigger(databaseId: string, collectionId: string, tr
const clearMessage = logConsoleProgress(`Deleting trigger ${triggerId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -10,7 +10,7 @@ export async function deleteUserDefinedFunction(databaseId: string, collectionId
const clearMessage = logConsoleProgress(`Deleting user defined function ${id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -41,7 +41,7 @@ interface MetricsResponse {
}
export const getCollectionUsageSizeInKB = async (databaseName: string, containerName: string): Promise<number> => {
if (window.authType !== AuthType.AAD) {
if (userContext.authType !== AuthType.AAD) {
return undefined;
}

View File

@ -3,9 +3,10 @@ import { handleError } from "../ErrorHandlingUtils";
import { logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
import * as Constants from "../Constants";
import { AuthType } from "../../AuthType";
import { userContext } from "../../UserContext";
export async function getIndexTransformationProgress(databaseId: string, collectionId: string): Promise<number> {
if (window.authType !== AuthType.AAD) {
if (userContext.authType !== AuthType.AAD) {
return undefined;
}
let indexTransformationPercentage: number;

View File

@ -9,6 +9,7 @@ import { updateUserContext } from "../../UserContext";
describe("readCollection", () => {
beforeAll(() => {
updateUserContext({
authType: AuthType.ResourceToken,
databaseAccount: {
name: "test",
} as DatabaseAccount,
@ -17,7 +18,6 @@ describe("readCollection", () => {
});
it("should call SDK if logged in with resource token", async () => {
window.authType = AuthType.ResourceToken;
(client as jest.Mock).mockReturnValue({
database: () => {
return {

View File

@ -16,7 +16,7 @@ export const readCollectionOffer = async (params: ReadCollectionOfferParams): Pr
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience !== DefaultAccountExperienceType.Table
) {

View File

@ -19,13 +19,17 @@ describe("readCollections", () => {
});
it("should call ARM if logged in with AAD", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
await readCollections("database");
expect(armRequest).toHaveBeenCalled();
});
it("should call SDK if not logged in with non-AAD method", async () => {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
(client as jest.Mock).mockReturnValue({
database: () => {
return {

View File

@ -15,7 +15,7 @@ export async function readCollections(databaseId: string): Promise<DataModels.Co
const clearMessage = logConsoleProgress(`Querying containers for database ${databaseId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience !== DefaultAccountExperienceType.MongoDB &&
userContext.defaultExperience !== DefaultAccountExperienceType.Table

View File

@ -15,7 +15,7 @@ export const readDatabaseOffer = async (params: ReadDatabaseOfferParams): Promis
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience !== DefaultAccountExperienceType.Table
) {

View File

@ -19,13 +19,17 @@ describe("readDatabases", () => {
});
it("should call ARM if logged in with AAD", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
await readDatabases();
expect(armRequest).toHaveBeenCalled();
});
it("should call SDK if not logged in with non-AAD method", async () => {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
(client as jest.Mock).mockReturnValue({
databases: {
readAll: () => {

View File

@ -15,7 +15,7 @@ export async function readDatabases(): Promise<DataModels.Database[]> {
const clearMessage = logConsoleProgress(`Querying databases`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience !== DefaultAccountExperienceType.Table
) {

View File

@ -9,7 +9,7 @@ export async function readMongoDBCollectionThroughRP(
databaseId: string,
collectionId: string
): Promise<MongoDBCollectionResource> {
if (window.authType !== AuthType.AAD) {
if (userContext.authType !== AuthType.AAD) {
return undefined;
}
let collection: MongoDBCollectionResource;

View File

@ -14,7 +14,7 @@ export async function readStoredProcedures(
const clearMessage = logConsoleProgress(`Querying stored procedures for container ${collectionId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -14,7 +14,7 @@ export async function readTriggers(
const clearMessage = logConsoleProgress(`Querying triggers for container ${collectionId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -14,7 +14,7 @@ export async function readUserDefinedFunctions(
const clearMessage = logConsoleProgress(`Querying user defined functions for container ${collectionId}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -41,7 +41,7 @@ export async function updateCollection(
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience !== DefaultAccountExperienceType.MongoDB &&
userContext.defaultExperience !== DefaultAccountExperienceType.Table

View File

@ -58,7 +58,7 @@ export const updateOffer = async (params: UpdateOfferParams): Promise<Offer> =>
const clearMessage = logConsoleProgress(`Updating offer for ${offerResourceText}`);
try {
if (window.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (userContext.authType === AuthType.AAD && !userContext.useSDKOperations) {
if (params.collectionId) {
updatedOffer = await updateCollectionOfferWithARM(params);
} else if (userContext.defaultExperience === DefaultAccountExperienceType.Table) {

View File

@ -22,7 +22,7 @@ export async function updateStoredProcedure(
const clearMessage = logConsoleProgress(`Updating stored procedure ${storedProcedure.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -19,7 +19,7 @@ export async function updateTrigger(
const clearMessage = logConsoleProgress(`Updating trigger ${trigger.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -22,7 +22,7 @@ export async function updateUserDefinedFunction(
const clearMessage = logConsoleProgress(`Updating user defined function ${userDefinedFunction.id}`);
try {
if (
window.authType === AuthType.AAD &&
userContext.authType === AuthType.AAD &&
!userContext.useSDKOperations &&
userContext.defaultExperience === DefaultAccountExperienceType.DocumentDB
) {

View File

@ -371,20 +371,20 @@ export enum TerminalKind {
export interface DataExplorerInputsFrame {
databaseAccount: any;
subscriptionId: string;
resourceGroup: string;
masterKey: string;
hasWriteAccess: boolean;
authorizationToken: string;
features: any;
csmEndpoint: string;
dnsSuffix: string;
serverId: string;
extensionEndpoint: string;
subscriptionType: SubscriptionType;
quotaId: string;
addCollectionDefaultFlight: string;
isTryCosmosDBSubscription: boolean;
subscriptionId?: string;
resourceGroup?: string;
masterKey?: string;
hasWriteAccess?: boolean;
authorizationToken?: string;
features: { [key: string]: string };
csmEndpoint?: string;
dnsSuffix?: string;
serverId?: string;
extensionEndpoint?: string;
subscriptionType?: SubscriptionType;
quotaId?: string;
addCollectionDefaultFlight?: string;
isTryCosmosDBSubscription?: boolean;
loadDatabaseAccountTimestamp?: number;
sharedThroughputMinimum?: number;
sharedThroughputMaximum?: number;

View File

@ -1848,19 +1848,21 @@ export default class Explorer {
this.collectionCreationDefaults = inputs.defaultCollectionThroughput;
}
this.features(inputs.features);
this.serverId(inputs.serverId);
this.serverId(inputs.serverId ?? Constants.ServerIds.productionPortal);
this.databaseAccount(databaseAccount);
this.subscriptionType(inputs.subscriptionType);
this.hasWriteAccess(inputs.hasWriteAccess);
this.flight(inputs.addCollectionDefaultFlight);
this.isTryCosmosDBSubscription(inputs.isTryCosmosDBSubscription);
this.isAuthWithResourceToken(inputs.isAuthWithresourceToken);
this.subscriptionType(inputs.subscriptionType ?? SharedConstants.CollectionCreation.DefaultSubscriptionType);
this.hasWriteAccess(inputs.hasWriteAccess ?? true);
if (inputs.addCollectionDefaultFlight) {
this.flight(inputs.addCollectionDefaultFlight);
}
this.isTryCosmosDBSubscription(inputs.isTryCosmosDBSubscription ?? false);
this.isAuthWithResourceToken(inputs.isAuthWithresourceToken ?? false);
this.setFeatureFlagsFromFlights(inputs.flights);
this.setSelfServeType(inputs);
this._importExplorerConfigComplete = true;
updateConfigContext({
BACKEND_ENDPOINT: inputs.extensionEndpoint || "",
BACKEND_ENDPOINT: inputs.extensionEndpoint || configContext.BACKEND_ENDPOINT,
ARM_ENDPOINT: normalizeArmEndpoint(inputs.csmEndpoint || configContext.ARM_ENDPOINT),
});
@ -2508,7 +2510,7 @@ export default class Explorer {
}
private async _refreshNotebooksEnabledStateForAccount(): Promise<void> {
const authType = window.authType as AuthType;
const authType = userContext.authType;
if (
authType === AuthType.EncryptedToken ||
authType === AuthType.ResourceToken ||
@ -2557,7 +2559,7 @@ export default class Explorer {
public _refreshSparkEnabledStateForAccount = async (): Promise<void> => {
const subscriptionId = userContext.subscriptionId;
const armEndpoint = configContext.ARM_ENDPOINT;
const authType = window.authType as AuthType;
const authType = userContext.authType;
if (!subscriptionId || !armEndpoint || authType === AuthType.EncryptedToken) {
// explorer is not aware of the database account yet
this.isSparkEnabledForAccount(false);
@ -2586,7 +2588,7 @@ export default class Explorer {
public _isAfecFeatureRegistered = async (featureName: string): Promise<boolean> => {
const subscriptionId = userContext.subscriptionId;
const armEndpoint = configContext.ARM_ENDPOINT;
const authType = window.authType as AuthType;
const authType = userContext.authType;
if (!featureName || !subscriptionId || !armEndpoint || authType === AuthType.EncryptedToken) {
// explorer is not aware of the database account yet
return false;

View File

@ -261,7 +261,7 @@ export class CassandraAPIDataClient extends TableDataClient {
const clearMessage =
shouldNotify && NotificationConsoleUtils.logConsoleProgress(`Querying rows for table ${collection.id()}`);
try {
const authType = window.authType;
const authType = userContext.authType;
const apiEndpoint: string =
authType === AuthType.EncryptedToken
? Constants.CassandraBackend.guestQueryApi
@ -425,7 +425,7 @@ export class CassandraAPIDataClient extends TableDataClient {
ConsoleDataType.InProgress,
`Fetching keys for table ${collection.id()}`
);
const authType = window.authType;
const authType = userContext.authType;
const apiEndpoint: string =
authType === AuthType.EncryptedToken
? Constants.CassandraBackend.guestKeysApi
@ -475,7 +475,7 @@ export class CassandraAPIDataClient extends TableDataClient {
ConsoleDataType.InProgress,
`Fetching schema for table ${collection.id()}`
);
const authType = window.authType;
const authType = userContext.authType;
const apiEndpoint: string =
authType === AuthType.EncryptedToken
? Constants.CassandraBackend.guestSchemaApi
@ -519,7 +519,7 @@ export class CassandraAPIDataClient extends TableDataClient {
private createOrDeleteQuery(cassandraEndpoint: string, resourceId: string, query: string): Q.Promise<any> {
const deferred = Q.defer();
const authType = window.authType;
const authType = userContext.authType;
const apiEndpoint: string =
authType === AuthType.EncryptedToken
? Constants.CassandraBackend.guestCreateOrDeleteApi

View File

@ -971,7 +971,7 @@ export default class Collection implements ViewModels.Collection {
public uploadFiles = (fileList: FileList): Promise<UploadDetails> => {
// TODO: right now web worker is not working with AAD flow. Use main thread for upload for now until we have backend upload capability
if (configContext.platform === Platform.Hosted && window.authType === AuthType.AAD) {
if (configContext.platform === Platform.Hosted && userContext.authType === AuthType.AAD) {
return this._uploadFilesCors(fileList);
}
const documentUploader: Worker = new UploadWorker();

View File

@ -87,7 +87,7 @@ const App: React.FunctionComponent = () => {
closeSidePanel,
};
const config = useConfig();
useKnockoutExplorer(config, explorerParams);
useKnockoutExplorer(config?.platform, explorerParams);
return (
<div className="flexContainer">

View File

@ -1,8 +1,10 @@
import { AuthType } from "./AuthType";
import { DatabaseAccount } from "./Contracts/DataModels";
import { SubscriptionType } from "./Contracts/SubscriptionType";
import { DefaultAccountExperienceType } from "./DefaultAccountExperienceType";
interface UserContext {
authType?: AuthType;
masterKey?: string;
subscriptionId?: string;
resourceGroup?: string;

View File

@ -9,8 +9,8 @@ jest.mock("../Explorer/Explorer");
describe("AuthorizationUtils", () => {
describe("getAuthorizationHeader()", () => {
it("should return authorization header if authentication type is AAD", () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
authorizationToken: "some-token",
});
@ -19,8 +19,8 @@ describe("AuthorizationUtils", () => {
});
it("should return guest access header if authentication type is EncryptedToken", () => {
window.authType = AuthType.EncryptedToken;
updateUserContext({
authType: AuthType.EncryptedToken,
accessToken: "some-token",
});

View File

@ -6,7 +6,7 @@ import * as ViewModels from "../Contracts/ViewModels";
import { userContext } from "../UserContext";
export function getAuthorizationHeader(): ViewModels.AuthorizationTokenHeaderMetadata {
if (window.authType === AuthType.EncryptedToken) {
if (userContext.authType === AuthType.EncryptedToken) {
return {
header: Constants.HttpHeaders.guestAccessToken,
token: userContext.accessToken,

View File

@ -10,8 +10,8 @@ interface Global {
((global as unknown) as Global).Headers = ((fetch as unknown) as Global).Headers;
describe("ARM request", () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
authorizationToken: "some-token",
});
@ -57,8 +57,8 @@ describe("ARM request", () => {
});
it("should throw token error", async () => {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
authorizationToken: undefined,
});
const headers = new Headers();

1
src/global.d.ts vendored
View File

@ -3,7 +3,6 @@ import Explorer from "./Explorer/Explorer";
declare global {
interface Window {
authType: AuthType;
dataExplorer: Explorer;
__REACT_DEVTOOLS_GLOBAL_HOOK__: any;
$: any;

View File

@ -1,9 +1,9 @@
import { useEffect } from "react";
import { applyExplorerBindings } from "../applyExplorerBindings";
import { AuthType } from "../AuthType";
import { AccountKind, DefaultAccountExperience, ServerIds } from "../Common/Constants";
import { AccountKind, DefaultAccountExperience } from "../Common/Constants";
import { sendMessage } from "../Common/MessageHandler";
import { configContext, ConfigContext, Platform } from "../ConfigContext";
import { configContext, Platform } from "../ConfigContext";
import { ActionType, DataExplorerAction } from "../Contracts/ActionContracts";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { DataExplorerInputsFrame } from "../Contracts/ViewModels";
@ -23,7 +23,6 @@ import {
getDatabaseAccountPropertiesFromMetadata,
} from "../Platform/Hosted/HostedUtils";
import { SelfServeType } from "../SelfServe/SelfServeUtils";
import { CollectionCreation } from "../Shared/Constants";
import { DefaultExperienceUtility } from "../Shared/DefaultExperienceUtility";
import { updateUserContext } from "../UserContext";
import { listKeys } from "../Utils/arm/generatedClients/2020-04-01/databaseAccounts";
@ -34,32 +33,32 @@ import { isInvalidParentFrameOrigin } from "../Utils/MessageValidation";
// Pleas tread carefully :)
let explorer: Explorer;
export function useKnockoutExplorer(config: ConfigContext, explorerParams: ExplorerParams): Explorer {
export function useKnockoutExplorer(platform: Platform, explorerParams: ExplorerParams): Explorer {
explorer = explorer || new Explorer(explorerParams);
useEffect(() => {
const effect = async () => {
if (config) {
if (config.platform === Platform.Hosted) {
await configureHosted(config);
if (platform) {
if (platform === Platform.Hosted) {
await configureHosted();
applyExplorerBindings(explorer);
} else if (config.platform === Platform.Emulator) {
} else if (platform === Platform.Emulator) {
configureEmulator();
applyExplorerBindings(explorer);
} else if (config.platform === Platform.Portal) {
} else if (platform === Platform.Portal) {
configurePortal();
}
}
};
effect();
}, [config]);
}, [platform]);
return explorer;
}
async function configureHosted(config: ConfigContext) {
async function configureHosted() {
const win = (window as unknown) as HostedExplorerChildFrame;
explorer.selfServeType(SelfServeType.none);
if (win.hostedConfig.authType === AuthType.EncryptedToken) {
configureHostedWithEncryptedToken(win.hostedConfig, config);
configureHostedWithEncryptedToken(win.hostedConfig);
} else if (win.hostedConfig.authType === AuthType.ResourceToken) {
configureHostedWithResourceToken(win.hostedConfig);
} else if (win.hostedConfig.authType === AuthType.ConnectionString) {
@ -70,12 +69,12 @@ async function configureHosted(config: ConfigContext) {
}
async function configureHostedWithAAD(config: AAD) {
window.authType = AuthType.AAD;
const account = config.databaseAccount;
const accountResourceId = account.id;
const subscriptionId = accountResourceId && accountResourceId.split("subscriptions/")[1].split("/")[0];
const resourceGroup = accountResourceId && accountResourceId.split("resourceGroups/")[1].split("/")[0];
updateUserContext({
authType: AuthType.AAD,
authorizationToken: `Bearer ${config.authorizationToken}`,
databaseAccount: config.databaseAccount,
});
@ -85,66 +84,35 @@ async function configureHostedWithAAD(config: AAD) {
subscriptionId,
resourceGroup,
masterKey: keys.primaryMasterKey,
hasWriteAccess: true,
authorizationToken: `Bearer ${config.authorizationToken}`,
features: extractFeatures(),
csmEndpoint: undefined,
dnsSuffix: undefined,
serverId: ServerIds.productionPortal,
extensionEndpoint: configContext.BACKEND_ENDPOINT,
subscriptionType: CollectionCreation.DefaultSubscriptionType,
quotaId: undefined,
addCollectionDefaultFlight: explorer.flight(),
isTryCosmosDBSubscription: explorer.isTryCosmosDBSubscription(),
});
explorer.isAccountReady(true);
}
function configureHostedWithConnectionString(config: ConnectionString) {
// For legacy reasons lots of code expects a connection string login to look and act like an encrypted token login
window.authType = AuthType.EncryptedToken;
// Impossible to tell if this is a try cosmos sub using an encrypted token
explorer.isTryCosmosDBSubscription(false);
updateUserContext({
// For legacy reasons lots of code expects a connection string login to look and act like an encrypted token login
authType: AuthType.EncryptedToken,
accessToken: encodeURIComponent(config.encryptedToken),
});
const apiExperience: string = DefaultExperienceUtility.getDefaultExperienceFromApiKind(
config.encryptedTokenMetadata.apiKind
);
const apiExperience = DefaultExperienceUtility.getDefaultExperienceFromApiKind(config.encryptedTokenMetadata.apiKind);
explorer.configure({
databaseAccount: {
id: "",
// id: Main._databaseAccountId,
name: config.encryptedTokenMetadata.accountName,
kind: getDatabaseAccountKindFromExperience(apiExperience),
properties: getDatabaseAccountPropertiesFromMetadata(config.encryptedTokenMetadata),
tags: [],
tags: {},
},
subscriptionId: undefined,
resourceGroup: undefined,
masterKey: config.masterKey,
hasWriteAccess: true,
authorizationToken: undefined,
features: extractFeatures(),
csmEndpoint: undefined,
dnsSuffix: undefined,
serverId: ServerIds.productionPortal,
extensionEndpoint: configContext.BACKEND_ENDPOINT,
subscriptionType: CollectionCreation.DefaultSubscriptionType,
quotaId: undefined,
addCollectionDefaultFlight: explorer.flight(),
isTryCosmosDBSubscription: explorer.isTryCosmosDBSubscription(),
});
explorer.isAccountReady(true);
}
function configureHostedWithResourceToken(config: ResourceToken) {
window.authType = AuthType.ResourceToken;
// Resource tokens can only be used with SQL API
const apiExperience: string = DefaultAccountExperience.DocumentDB;
const parsedResourceToken = parseResourceTokenConnectionString(config.resourceToken);
updateUserContext({
authType: AuthType.ResourceToken,
resourceToken: parsedResourceToken.resourceToken,
endpoint: parsedResourceToken.accountEndpoint,
});
@ -159,36 +127,20 @@ function configureHostedWithResourceToken(config: ResourceToken) {
name: parsedResourceToken.accountEndpoint,
kind: AccountKind.GlobalDocumentDB,
properties: { documentEndpoint: parsedResourceToken.accountEndpoint },
tags: { defaultExperience: apiExperience },
// Resource tokens can only be used with SQL API
tags: { defaultExperience: DefaultAccountExperience.DocumentDB },
},
subscriptionId: undefined,
resourceGroup: undefined,
masterKey: undefined,
hasWriteAccess: true,
authorizationToken: undefined,
features: extractFeatures(),
csmEndpoint: undefined,
dnsSuffix: undefined,
serverId: ServerIds.productionPortal,
extensionEndpoint: configContext.BACKEND_ENDPOINT,
subscriptionType: CollectionCreation.DefaultSubscriptionType,
quotaId: undefined,
addCollectionDefaultFlight: explorer.flight(),
isTryCosmosDBSubscription: explorer.isTryCosmosDBSubscription(),
isAuthWithresourceToken: true,
});
explorer.isAccountReady(true);
explorer.isRefreshingExplorer(false);
}
function configureHostedWithEncryptedToken(config: EncryptedToken, configContext: ConfigContext) {
window.authType = AuthType.EncryptedToken;
// Impossible to tell if this is a try cosmos sub using an encrypted token
explorer.isTryCosmosDBSubscription(false);
function configureHostedWithEncryptedToken(config: EncryptedToken) {
updateUserContext({
authType: AuthType.EncryptedToken,
accessToken: encodeURIComponent(config.encryptedToken),
});
const apiExperience: string = DefaultExperienceUtility.getDefaultExperienceFromApiKind(
config.encryptedTokenMetadata.apiKind
);
@ -198,35 +150,25 @@ function configureHostedWithEncryptedToken(config: EncryptedToken, configContext
name: config.encryptedTokenMetadata.accountName,
kind: getDatabaseAccountKindFromExperience(apiExperience),
properties: getDatabaseAccountPropertiesFromMetadata(config.encryptedTokenMetadata),
tags: [],
tags: {},
},
subscriptionId: undefined,
resourceGroup: undefined,
masterKey: undefined,
hasWriteAccess: true,
authorizationToken: undefined,
features: extractFeatures(),
csmEndpoint: undefined,
dnsSuffix: undefined,
serverId: ServerIds.productionPortal,
extensionEndpoint: configContext.BACKEND_ENDPOINT,
subscriptionType: CollectionCreation.DefaultSubscriptionType,
quotaId: undefined,
addCollectionDefaultFlight: explorer.flight(),
isTryCosmosDBSubscription: explorer.isTryCosmosDBSubscription(),
});
explorer.isAccountReady(true);
}
function configureEmulator() {
window.authType = AuthType.MasterKey;
updateUserContext({
authType: AuthType.MasterKey,
});
explorer.selfServeType(SelfServeType.none);
explorer.databaseAccount(emulatorAccount);
explorer.isAccountReady(true);
}
function configurePortal() {
window.authType = AuthType.AAD;
updateUserContext({
authType: AuthType.AAD,
});
// In development mode, try to load the iframe message from session storage.
// This allows webpack hot reload to function properly in the portal
if (process.env.NODE_ENV === "development" && !window.location.search.includes("disablePortalInitCache")) {