Skip to content

Commit

Permalink
feat: add command to logout of default org (#3428)
Browse files Browse the repository at this point in the history
* feat: add command to logout of default org

* chore: review changes

* chore: display org alias when available
  • Loading branch information
rcoringrato-sfdc authored Jul 23, 2021
1 parent 99d3632 commit b6747f2
Show file tree
Hide file tree
Showing 12 changed files with 407 additions and 12 deletions.
8 changes: 8 additions & 0 deletions packages/salesforcedx-vscode-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,10 @@
"command": "sfdx.force.auth.logout.all",
"when": "sfdx:project_opened"
},
{
"command": "sfdx.force.auth.logout.default",
"when": "sfdx:project_opened && sfdx:has_default_username"
},
{
"command": "sfdx.force.org.create",
"when": "sfdx:project_opened"
Expand Down Expand Up @@ -570,6 +574,10 @@
"command": "sfdx.force.auth.logout.all",
"title": "%force_auth_logout_all_text%"
},
{
"command": "sfdx.force.auth.logout.default",
"title": "%force_auth_logout_default_text%"
},
{
"command": "sfdx.force.org.create",
"title": "%force_org_create_default_scratch_org_text%"
Expand Down
1 change: 1 addition & 0 deletions packages/salesforcedx-vscode-core/package.nls.ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"force_auth_web_login_authorize_org_text": "SFDX: 組織を認証",
"force_auth_access_token_authorize_org_text": "SFDX: Authorize an Org using Session ID",
"force_auth_logout_all_text": "SFDX: すべての認証済み組織からログアウト",
"force_auth_logout_default_text": "SFDX: Log Out from Default Org",
"force_org_create_default_scratch_org_text": "SFDX: デフォルトのスクラッチ組織を作成...",
"force_org_open_default_scratch_org_text": "SFDX: デフォルトの組織を開く",
"force_source_pull_default_scratch_org_text": "SFDX: デフォルトのスクラッチ組織からソースをプル",
Expand Down
1 change: 1 addition & 0 deletions packages/salesforcedx-vscode-core/package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"force_auth_web_login_authorize_org_text": "SFDX: Authorize an Org",
"force_auth_access_token_authorize_org_text": "SFDX: Authorize an Org using Session ID",
"force_auth_logout_all_text": "SFDX: Log Out from All Authorized Orgs",
"force_auth_logout_default_text": "SFDX: Log Out from Default Org",
"force_org_create_default_scratch_org_text": "SFDX: Create a Default Scratch Org...",
"force_org_open_default_scratch_org_text": "SFDX: Open Default Org",
"force_source_pull_default_scratch_org_text": "SFDX: Pull Source from Default Scratch Org",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,33 @@ export class AccessTokenParamsGatherer
};
}
}

export class ScratchOrgLogoutParamsGatherer
implements ParametersGatherer<string> {
public constructor(
public readonly username: string,
public readonly alias?: string
) {}

public async gather(): Promise<CancelResponse | ContinueResponse<string>> {
const prompt = nls.localize(
'auth_logout_scratch_prompt',
this.alias || this.username
);
const logoutResponse = nls.localize('auth_logout_scratch_logout');

const confirm = await vscode.window.showInformationMessage(
prompt,
{ modal: true },
...[logoutResponse]
);
if (confirm !== logoutResponse) {
return { type: 'CANCEL' };
}

return {
type: 'CONTINUE',
data: this.username
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,28 @@
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { AuthRemover } from '@salesforce/core';
import { LibraryCommandletExecutor } from '@salesforce/salesforcedx-utils-vscode/out/src';
import {
Command,
SfdxCommandBuilder
} from '@salesforce/salesforcedx-utils-vscode/out/src/cli';
import { notificationService } from '@salesforce/salesforcedx-utils-vscode/out/src/commands';
import { ContinueResponse } from '@salesforce/salesforcedx-utils-vscode/out/src/types';
import { CancellationToken, Progress } from 'vscode';
import { OUTPUT_CHANNEL } from '../../channels';
import { nls } from '../../messages';
import { telemetryService } from '../../telemetry';
import { OrgAuthInfo } from '../../util';
import { forceConfigSet } from '../forceConfigSet';
import {
EmptyParametersGatherer,
SfdxCommandlet,
SfdxCommandletExecutor,
SfdxWorkspaceChecker
SfdxWorkspaceChecker,
SimpleGatherer
} from '../util';
import { ScratchOrgLogoutParamsGatherer } from './authParamsGatherer';

export class ForceAuthLogoutAll extends SfdxCommandletExecutor<{}> {
public static withoutShowingChannel(): ForceAuthLogoutAll {
Expand Down Expand Up @@ -47,3 +58,81 @@ const commandlet = new SfdxCommandlet(
export async function forceAuthLogoutAll() {
await commandlet.run();
}

export class AuthLogoutDefault extends LibraryCommandletExecutor<string> {
constructor() {
super(
nls.localize('force_auth_logout_default_text'),
'force_auth_logout_default',
OUTPUT_CHANNEL
);
}

public async run(
response: ContinueResponse<string>,
progress?: Progress<{
message?: string | undefined;
increment?: number | undefined;
}>,
token?: CancellationToken
): Promise<boolean> {
try {
await removeUsername(response.data);
} catch (e) {
telemetryService.sendException(e.name, e.message);
return false;
}
return true;
}
}

export async function forceAuthLogoutDefault() {
const { username, isScratch, alias, error } = await resolveDefaultUsername();
if (error) {
telemetryService.sendException(error.name, error.message);
notificationService.showErrorMessage('Logout failed to run');
} else if (username) {
// confirm logout for scratch orgs due to special considerations:
// https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth_logout.htm
const logoutCommandlet = new SfdxCommandlet(
new SfdxWorkspaceChecker(),
isScratch
? new ScratchOrgLogoutParamsGatherer(username, alias)
: new SimpleGatherer<string>(username),
new AuthLogoutDefault()
);
await logoutCommandlet.run();
} else {
notificationService.showInformationMessage(
nls.localize('auth_logout_no_default_org')
);
}
}

async function removeUsername(username: string) {
await forceConfigSet('');
const authRemover = await AuthRemover.create();
await authRemover.removeAuth(username);
}

async function resolveDefaultUsername(): Promise<{
username?: string;
isScratch: boolean;
alias?: string;
error?: Error;
}> {
const usernameOrAlias = await OrgAuthInfo.getDefaultUsernameOrAlias(false);
if (usernameOrAlias) {
const username = await OrgAuthInfo.getUsername(usernameOrAlias);
const alias = username !== usernameOrAlias ? usernameOrAlias : undefined;
let isScratch = false;

try {
isScratch = await OrgAuthInfo.isAScratchOrg(username);
} catch (err) {
return { error: err, isScratch: false };
}
return { username, isScratch, alias };
}
return { isScratch: false };
}
6 changes: 5 additions & 1 deletion packages/salesforcedx-vscode-core/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ export {
turnOffLogging,
ForceStopApexDebugLoggingExecutor
} from './forceStopApexDebugLogging';
export { forceAuthLogoutAll, ForceAuthLogoutAll } from './auth/forceAuthLogout';
export {
forceAuthLogoutAll,
ForceAuthLogoutAll,
forceAuthLogoutDefault
} from './auth/forceAuthLogout';
import { DeveloperLogTraceFlag } from '../traceflag/developerLogTraceFlag';
export const developerLogTraceFlag = DeveloperLogTraceFlag.getInstance();
export { forceConfigSet, ForceConfigSetExecutor } from './forceConfigSet';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export function setWorkspaceOrgTypeWithOrgType(orgType: OrgType) {

export async function setupWorkspaceOrgType(defaultUsernameOrAlias?: string) {
try {
setHasDefaultUsername(!!defaultUsernameOrAlias);
const orgType = await getWorkspaceOrgType(defaultUsernameOrAlias);
setWorkspaceOrgTypeWithOrgType(orgType);
} catch (e) {
Expand Down Expand Up @@ -77,6 +78,14 @@ function setDefaultUsernameHasNoChangeTracking(val: boolean) {
);
}

function setHasDefaultUsername(val: boolean) {
vscode.commands.executeCommand(
'setContext',
'sfdx:has_default_username',
val
);
}

export async function getDefaultUsernameOrAlias(): Promise<string | undefined> {
if (hasRootWorkspace()) {
return await OrgAuthInfo.getDefaultUsernameOrAlias(true);
Expand Down
17 changes: 15 additions & 2 deletions packages/salesforcedx-vscode-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
forceAuthAccessToken,
forceAuthDevHub,
forceAuthLogoutAll,
forceAuthLogoutDefault,
forceAuthWebLogin,
forceConfigList,
forceConfigSet,
Expand Down Expand Up @@ -79,8 +80,15 @@ import {
SfdxCommandletExecutor,
SfdxWorkspaceChecker
} from './commands/util';
import { PersistentStorageService, registerConflictView, setupConflictView } from './conflict';
import { ENABLE_SOBJECT_REFRESH_ON_STARTUP, SFDX_CORE_CONFIGURATION_NAME } from './constants';
import {
PersistentStorageService,
registerConflictView,
setupConflictView
} from './conflict';
import {
ENABLE_SOBJECT_REFRESH_ON_STARTUP,
SFDX_CORE_CONFIGURATION_NAME
} from './constants';
import { getDefaultUsernameOrAlias } from './context';
import { workspaceContext } from './context';
import * as decorators from './decorators';
Expand Down Expand Up @@ -115,6 +123,10 @@ function registerCommands(
'sfdx.force.auth.logout.all',
forceAuthLogoutAll
);
const forceAuthLogoutDefaultCmd = vscode.commands.registerCommand(
'sfdx.force.auth.logout.default',
forceAuthLogoutDefault
);
const forceOrgCreateCmd = vscode.commands.registerCommand(
'sfdx.force.org.create',
forceOrgCreate
Expand Down Expand Up @@ -368,6 +380,7 @@ function registerCommands(
forceAuthWebLoginCmd,
forceAuthDevHubCmd,
forceAuthLogoutAllCmd,
forceAuthLogoutDefaultCmd,
forceDataSoqlQueryInputCmd,
forceDataSoqlQuerySelectionCmd,
forceDiffFile,
Expand Down
5 changes: 5 additions & 0 deletions packages/salesforcedx-vscode-core/src/messages/i18n.ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ export const messages = {
demo_mode_prompt:
'デモモードまたは共有マシンで、ビジネスまたは本番組織を認証することは推奨されません。認証を続ける場合、組織を使用した後、必ず "SFDX: すべての認証済み組織からログアウト" を実行してください。',
force_auth_logout_all_text: 'SFDX: すべての認証済み組織からログアウト',
force_auth_logout_default_text: 'SFDX: Log Out from Default Org',
manifest_editor_title_message: 'マニフェストエディタ',
REST_API: 'REST API',
tooling_API: 'Tooling API',
Expand All @@ -232,6 +233,10 @@ export const messages = {
auth_custom_label: 'カスタム',
auth_custom_detail: 'カスタムログイン URL を入力',
auth_invalid_url: 'URL は http:// か https:// で始める必要があります。',
auth_logout_scratch_prompt:
'Log out of this scratch org?\n\nBefore logging out, ensure that you or someone on your team has a username and password for %s scratch org. Otherwise you might lose all access to this scratch org.',
auth_logout_scratch_logout: 'Logout',
auth_logout_no_default_org: 'No default org to logout from',
error_fetching_auth_info_text:
'保存時のプッシュまたはデプロイ実行中にエラー: デフォルトの組織に接続できませんでした。"SFDX: デフォルトのスクラッチ組織を作成" または "SFDX: 組織を認証" を実行して、保存したソースをプッシュまたはデプロイしてください。もしくは、保存時のプッシュまたはデプロイを無効化するため、VS Code のユーザまたはワークスペース設定で "salesforcedx-vscode-core.push-or-deploy-on-save.enabled" を false に設定してください。',
error_no_package_directories_found_on_setup_text:
Expand Down
5 changes: 5 additions & 0 deletions packages/salesforcedx-vscode-core/src/messages/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ export const messages = {
demo_mode_prompt:
'Authorizing a business or production org is not recommended on a demo or shared machine. If you continue with the authentication, be sure to run "SFDX: Log Out from All Authorized Orgs" when you\'re done using this org.',
force_auth_logout_all_text: 'SFDX: Log Out from All Authorized Orgs',
force_auth_logout_default_text: 'SFDX: Log Out from Default Org',
manifest_editor_title_message: 'Manifest Editor',
REST_API: 'REST API',
tooling_API: 'Tooling API',
Expand All @@ -269,6 +270,10 @@ export const messages = {
auth_custom_label: 'Custom',
auth_custom_detail: 'Enter a custom login URL',
auth_invalid_url: 'URL must begin with http:// or https://',
auth_logout_scratch_prompt:
'Log out of this scratch org?\n\nBefore logging out, ensure that you or someone on your team has a username and password for %s scratch org. Otherwise you might lose all access to this scratch org.',
auth_logout_scratch_logout: 'Logout',
auth_logout_no_default_org: 'No default org to logout from',
error_fetching_auth_info_text:
'Error running push or deploy on save: We couldn\'t connect to your default org. Run "SFDX: Create a Default Scratch Org" or "SFDX: Authorize an Org", then push or deploy the source that you just saved. Or, to disable push or deploy on save, set "salesforcedx-vscode-core.push-or-deploy-on-save.enabled" to false in your user or workspace settings for VS Code.',
error_no_package_directories_found_on_setup_text:
Expand Down
Loading

0 comments on commit b6747f2

Please sign in to comment.