Skip to content

Commit

Permalink
Fix login in idx
Browse files Browse the repository at this point in the history
  • Loading branch information
hlshen committed May 11, 2024
1 parent d2e1172 commit 9b0bdaf
Show file tree
Hide file tree
Showing 13 changed files with 108 additions and 289 deletions.
3 changes: 3 additions & 0 deletions firebase-vscode/common/messaging/protocol.ts
Expand Up @@ -113,6 +113,9 @@ export interface WebviewToExtensionParamsMap {

// Initialize "result" tab.
getDataConnectResults: void;

// execute terminal tasks
executeLogin: void;
}

export interface DataConnectResults {
Expand Down
4 changes: 2 additions & 2 deletions firebase-vscode/package.json
Expand Up @@ -55,12 +55,12 @@
"properties": {
"firebase.debug": {
"type": "boolean",
"default": false,
"default": true,
"description": "Enable writing debug-level messages to the file provided in firebase.debugLogPath (requires restart)"
},
"firebase.debugLogPath": {
"type": "string",
"default": "",
"default": "/tmp/firebase-plugin.log",
"description": "If firebase.debug is true, appends debug-level messages to the provided file (requires restart)"
},
"firebase.npmPath": {
Expand Down
38 changes: 3 additions & 35 deletions firebase-vscode/scripts/swap-pkg.js
Expand Up @@ -2,42 +2,10 @@ const { writeFileSync } = require("fs");
const path = require("path");
const pkg = require(path.join(__dirname, "../package.json"));

// Swaps package.json config as appropriate for packaging for
// Monospace or VSCE marketplace.

// TODO(chholland): Don't overwrite the real package.json file and
// create a generated one in dist/ - redo .vscodeignore to package
// dist/

let target = "vsce";

process.argv.forEach((arg) => {
if (arg === "vsce" || arg === "monospace") {
target = arg;
}
});

if (target === "vsce") {
delete pkg.extensionDependencies;
console.log(
"Removing google.monospace extensionDependency for VSCE packaging."
);
pkg.contributes.configuration.properties["firebase.debug"].default = false;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"";
console.log("Setting default debug log settings to off for VSCE packaging.");
} else if (target === "monospace") {
pkg.extensionDependencies = ["google.monospace"];
console.log(
"Adding google.monospace extensionDependency for Monospace packaging."
);
pkg.contributes.configuration.properties["firebase.debug"].default = true;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"/tmp/firebase-plugin.log";
console.log(
"Setting default debug log settings to on for Monospace packaging."
);
}
pkg.contributes.configuration.properties["firebase.debug"].default = true;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"/tmp/firebase-plugin.log";

writeFileSync(
path.join(__dirname, "../package.json"),
Expand Down
9 changes: 6 additions & 3 deletions firebase-vscode/src/cli.ts
Expand Up @@ -100,9 +100,11 @@ async function getServiceAccount() {
*/
async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// Try to get global default from configstore. For some reason this is
// often overwritten when restarting the extension.
pluginLogger.debug("requireAuthWrapper");
let account = getGlobalDefaultAccount();
// often overwritten when restarting the extension.
console.log("HAROLD", account);

if (!account) {
// If nothing in configstore top level, grab the first "additionalAccount"
const accounts = getAllAccounts();
Expand Down Expand Up @@ -136,6 +138,7 @@ async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// user
// Priority 3: Google login account exists and there is no selected user
// Clear service account access token from memory in apiv2.
console.log("HAROLD2", account);
setAccessToken();
await requireAuth({ ...commandOptions, ...account });
return true;
Expand All @@ -153,7 +156,7 @@ async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// "error". Usually set on user-triggered actions such as
// init hosting and deploy.
pluginLogger.error(
`requireAuth error: ${e.original?.message || e.message}`
`requireAuth error: ${e.original?.message || e.message}`,
);
vscode.window.showErrorMessage("Not logged in", {
modal: true,
Expand All @@ -164,7 +167,7 @@ async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// but we should log it for debugging purposes.
pluginLogger.debug(
"requireAuth error output: ",
e.original?.message || e.message
e.original?.message || e.message,
);
}
return false;
Expand Down
46 changes: 17 additions & 29 deletions firebase-vscode/src/core/project.ts
Expand Up @@ -6,14 +6,13 @@ import { FirebaseProjectMetadata } from "../types/project";
import { currentUser, isServiceAccount } from "./user";
import { listProjects } from "../cli";
import { pluginLogger } from "../logger-wrapper";
import { selectProjectInMonospace } from "../../../src/monospace";
import { currentOptions } from "../options";
import { globalSignal } from "../utils/globals";
import { firstWhereDefined } from "../utils/signal";

/** Available projects */
export const projects = globalSignal<Record<string, FirebaseProjectMetadata[]>>(
{}
{},
);

/** Currently selected project ID */
Expand All @@ -22,7 +21,7 @@ export const currentProjectId = globalSignal("");
const userScopedProjects = computed<FirebaseProjectMetadata[] | undefined>(
() => {
return projects.value[currentUser.value?.email ?? ""];
}
},
);

/** Gets the currently selected project, fallback to first default project in RC file */
Expand All @@ -41,7 +40,7 @@ export const currentProject = computed<FirebaseProjectMetadata | undefined>(
}

return userScopedProjects.value?.find((p) => p.projectId === wantProjectId);
}
},
);

export function registerProject(broker: ExtensionBrokerImpl): Disposable {
Expand Down Expand Up @@ -90,28 +89,17 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
if (process.env.MONOSPACE_ENV) {
pluginLogger.debug(
"selectProject: found MONOSPACE_ENV, " +
"prompting user using external flow"
"prompting user using CLI",
);
/**
* Monospace case: use Monospace flow
*/
const monospaceExtension =
vscode.extensions.getExtension("google.monospace");
process.env.MONOSPACE_DAEMON_PORT =
monospaceExtension.exports.getMonospaceDaemonPort();
try {
const projectId = await selectProjectInMonospace({
projectRoot: currentOptions.value.cwd,
project: undefined,
isVSCE: true,
});

if (projectId) {
currentProjectId.value = projectId;
}
} catch (e) {
pluginLogger.error(e);
}
try {
const projects = firstWhereDefined(userScopedProjects);

currentProjectId.value =
(await _promptUserForProject(projects)) ?? currentProjectId.value;
} catch (e) {
vscode.window.showErrorMessage(e.message);
}

} else if (isServiceAccount.value) {
return;
} else {
Expand All @@ -124,11 +112,11 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
vscode.window.showErrorMessage(e.message);
}
}
}
},
);

const sub6 = broker.on("selectProject", () =>
vscode.commands.executeCommand("firebase.selectProject")
vscode.commands.executeCommand("firebase.selectProject"),
);

return vscode.Disposable.from(
Expand All @@ -138,7 +126,7 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
{ dispose: sub3 },
{ dispose: sub4 },
{ dispose: sub5 },
{ dispose: sub6 }
{ dispose: sub6 },
);
}

Expand All @@ -149,7 +137,7 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
*/
export async function _promptUserForProject(
projects: Thenable<FirebaseProjectMetadata[]>,
token?: vscode.CancellationToken
token?: vscode.CancellationToken,
): Promise<string | undefined> {
const items = projects.then((projects) => {
return projects.map((p) => ({
Expand Down
15 changes: 10 additions & 5 deletions firebase-vscode/src/core/user.ts
Expand Up @@ -23,7 +23,16 @@ export const isServiceAccount = computed(() => {
return (currentUser.value as ServiceAccountUser)?.type === "service_account";
});

export async function checkLogin() {
const accounts = await getAccounts();
users.value = accounts.reduce(
(cumm, curr) => ({ ...cumm, [curr.user.email]: curr.user }),
{}
);
}

export function registerUser(broker: ExtensionBrokerImpl): Disposable {

const sub1 = effect(() => {
broker.send("notifyUsers", { users: Object.values(users.value) });
});
Expand All @@ -33,11 +42,7 @@ export function registerUser(broker: ExtensionBrokerImpl): Disposable {
});

const sub3 = broker.on("getInitialData", async () => {
const accounts = await getAccounts();
users.value = accounts.reduce(
(cumm, curr) => ({ ...cumm, [curr.user.email]: curr.user }),
{}
);
checkLogin();
});

const sub4 = broker.on("addUser", async () => {
Expand Down
2 changes: 2 additions & 0 deletions firebase-vscode/src/data-connect/index.ts
Expand Up @@ -28,6 +28,7 @@ import { runDataConnectCompiler } from "./core-compiler";
import { Result } from "../result";
import { runEmulatorIssuesStream } from "./emulator-stream";
import { LanguageClient } from "vscode-languageclient/node";
import { registerTerminalTasks } from "./terminal";

class CodeActionsProvider implements vscode.CodeActionProvider {
constructor(
Expand Down Expand Up @@ -221,6 +222,7 @@ export function registerFdc(
registerAdHoc(),
registerConnectors(context, broker, fdcService),
registerFdcDeploy(broker),
registerTerminalTasks(broker),
operationCodeLensProvider,
vscode.languages.registerCodeLensProvider(
// **Hack**: For testing purposes, enable code lenses on all graphql files
Expand Down
54 changes: 52 additions & 2 deletions firebase-vscode/src/data-connect/terminal.ts
@@ -1,6 +1,7 @@
import { TerminalOptions } from "vscode";
import * as vscode from "vscode";

import { ExtensionBrokerImpl } from "../extension-broker";
import vscode, { Disposable } from "vscode";
import { checkLogin } from "../core/user";
const environmentVariables = {};

const terminalOptions: TerminalOptions = {
Expand All @@ -17,3 +18,52 @@ export function runCommand(command: string) {
terminal.show();
terminal.sendText(command);
}

export function runTerminalTask(
taskName: string,
command: string,
): Promise<string> {
const type = "firebase-" + Date.now();
return new Promise(async (resolve, reject) => {
vscode.tasks.onDidEndTaskProcess(async (e) => {
if (e.execution.task.definition.type === type) {
e.execution.terminate();

if (e.exitCode === 0) {
resolve(`Successfully executed ${taskName} with command: ${command}`);
} else {
reject(
new Error(`Failed to execute ${taskName} with command: ${command}`),
);
}
}
});
vscode.tasks.executeTask(
new vscode.Task(
{ type },
vscode.TaskScope.Workspace,
taskName,
"firebase",
new vscode.ShellExecution(command),
),
);
});
}

export function registerTerminalTasks(broker: ExtensionBrokerImpl): Disposable {
const loginTaskBroker = broker.on("executeLogin", () => {
runTerminalTask("firebase login", "firebase login --no-localhost").then(() => {
checkLogin();
});
});

return Disposable.from(
{ dispose: loginTaskBroker },
vscode.commands.registerCommand(
"firebase.dataConnect.runTerminalTask",
(taskName, command) => {
runTerminalTask(taskName, command);
},
),
);
}
5 changes: 3 additions & 2 deletions firebase-vscode/webviews/SidebarApp.tsx
Expand Up @@ -160,7 +160,8 @@ function SidebarContent(props: {
{!!user && (
<ProjectSection userEmail={user.email} projectId={projectId} />
)}
{hostingInitState === "success" &&
{ // TODO: disable hosting completely
/* {hostingInitState === "success" &&
!!user &&
!!projectId &&
env?.isMonospace && (
Expand All @@ -184,7 +185,7 @@ function SidebarContent(props: {
hostingInitState={hostingInitState}
setHostingInitState={setHostingInitState}
/>
)}
)} */}
{
// disable emulator panel for now, as we have an individual emulator panel in the FDC section
}
Expand Down
21 changes: 10 additions & 11 deletions firebase-vscode/webviews/components/AccountSection.tsx
Expand Up @@ -34,9 +34,11 @@ export function AccountSection({
if (usersLoaded && (!allUsers.length || !user)) {
// Users loaded but no user was found
if (isMonospace) {
// Monospace: this is an error, should have found a workspace
// service account
currentUserElement = TEXT.MONOSPACE_LOGIN_FAIL;
currentUserElement = (
<VSCodeLink onClick={() => broker.send("executeLogin")}>
{TEXT.GOOGLE_SIGN_IN}
</VSCodeLink>
);
} else {
// VS Code: prompt user to log in with Google account
currentUserElement = (
Expand All @@ -49,7 +51,11 @@ export function AccountSection({
// Users loaded, at least one user was found
if (user.type === "service_account") {
if (isMonospace) {
currentUserElement = TEXT.MONOSPACE_LOGGED_IN;
currentUserElement = (
<VSCodeLink onClick={() => broker.send("executeLogin")}>
{TEXT.GOOGLE_SIGN_IN}
</VSCodeLink>
);
} else {
currentUserElement = TEXT.VSCE_SERVICE_ACCOUNT_LOGGED_IN;
}
Expand All @@ -63,13 +69,6 @@ export function AccountSection({
{currentUserElement}
</Label>
);
if (user?.type === "service_account" && isMonospace) {
userBoxElement = (
<Label level={4} secondary className={styles.accountRowLabel}>
{currentUserElement}
</Label>
);
}
return (
<div className={styles.accountRow}>
{userBoxElement}
Expand Down

0 comments on commit 9b0bdaf

Please sign in to comment.