UNPKG

7.29 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright (c) 2020, salesforce.com, inc.
4 * All rights reserved.
5 * Licensed under the BSD 3-Clause license.
6 * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7 */
8Object.defineProperty(exports, "__esModule", { value: true });
9exports.AuthRemover = void 0;
10const kit_1 = require("@salesforce/kit");
11const configAggregator_1 = require("../config/configAggregator");
12const logger_1 = require("../logger");
13const messages_1 = require("../messages");
14const stateAggregator_1 = require("../stateAggregator");
15const orgConfigProperties_1 = require("./orgConfigProperties");
16messages_1.Messages.importMessagesDirectory(__dirname);
17const messages = messages_1.Messages.load('@salesforce/core', 'auth', ['targetOrgNotSet']);
18/**
19 * Handles the removing of authorizations, which includes deleting the auth file
20 * in the global .sfdx folder, deleting any configs that are associated with the username/alias,
21 * and deleting any aliases associated with the username
22 *
23 * ```
24 * const remover = await AuthRemover.create();
25 * await remover.removeAuth('example@mycompany.com');
26 * ```
27 *
28 * ```
29 * const remover = await AuthRemover.create();
30 * await remover.removeAllAuths();
31 * ```
32 *
33 * ```
34 * const remover = await AuthRemover.create();
35 * const auth = await remover.findAuth(
36 * example@mycompany.com
37 * );
38 * await remover.removeAuth(auth.username);
39 * ```
40 */
41class AuthRemover extends kit_1.AsyncOptionalCreatable {
42 /**
43 * Removes the authentication and any configs or aliases associated with it
44 *
45 * @param usernameOrAlias the username or alias that you want to remove
46 */
47 async removeAuth(usernameOrAlias) {
48 const username = await this.resolveUsername(usernameOrAlias);
49 this.logger.debug(`Removing authorization for user ${username}`);
50 await this.unsetConfigValues(username);
51 await this.unsetAliases(username);
52 await this.unsetTokens(username);
53 await this.stateAggregator.orgs.remove(username);
54 }
55 /**
56 * Removes all authentication files and any configs or aliases associated with them
57 */
58 async removeAllAuths() {
59 const auths = this.findAllAuths();
60 const usernames = Object.keys(auths);
61 for (const username of usernames) {
62 // prevent ConfigFile collision bug
63 // eslint-disable-next-line no-await-in-loop
64 await this.removeAuth(username);
65 }
66 }
67 /**
68 * Finds authorization files for username/alias in the global .sfdx folder
69 * **Throws** *{@link SfError}{ name: 'TargetOrgNotSetError' }* if no target-org
70 * **Throws** *{@link SfError}{ name: 'NamedOrgNotFoundError' }* if specified user is not found
71 *
72 * @param usernameOrAlias username or alias of the auth you want to find, defaults to the configured target-org
73 * @returns {Promise<SfOrg>}
74 */
75 async findAuth(usernameOrAlias) {
76 const username = await this.resolveUsername(usernameOrAlias ?? this.getTargetOrg());
77 return this.stateAggregator.orgs.get(username, false, true);
78 }
79 /**
80 * Finds all org authorizations in the global info file (.sf/sf.json)
81 *
82 * @returns {Record<string, AuthFields>}
83 */
84 findAllAuths() {
85 const orgs = this.stateAggregator.orgs.getAll();
86 return orgs.reduce((x, y) =>
87 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
88 ({ ...x, [y.username]: y }), {});
89 }
90 async init() {
91 this.logger = await logger_1.Logger.child(this.constructor.name);
92 this.config = await configAggregator_1.ConfigAggregator.create();
93 this.stateAggregator = await stateAggregator_1.StateAggregator.getInstance();
94 await this.stateAggregator.orgs.readAll();
95 }
96 /**
97 * Returns the username for a given alias if the alias exists.
98 *
99 * @param usernameOrAlias username or alias
100 * @returns {Promise<string>}
101 */
102 // eslint-disable-next-line @typescript-eslint/require-await
103 async resolveUsername(usernameOrAlias) {
104 return this.stateAggregator.aliases.resolveUsername(usernameOrAlias);
105 }
106 /**
107 * @returns {string}
108 */
109 getTargetOrg() {
110 const targetOrg = this.config.getInfo(orgConfigProperties_1.OrgConfigProperties.TARGET_ORG).value;
111 if (!targetOrg) {
112 throw messages.createError('targetOrgNotSet');
113 }
114 return targetOrg;
115 }
116 /**
117 * Returns aliases for provided username
118 *
119 * @param username username that's been aliased
120 * @returns {Promise<string[]>}
121 */
122 getAliases(username) {
123 return this.stateAggregator.aliases.getAll(username);
124 }
125 /**
126 * Unsets any configured values (both global and local) for provided username
127 *
128 * @param username username that you want to remove from config files
129 */
130 async unsetConfigValues(username) {
131 const aliases = this.getAliases(username);
132 this.logger.debug(`Clearing config keys for username ${username} and aliases: ${aliases.join(',')}`);
133 const configs = [this.config.getGlobalConfig(), this.config.getLocalConfig()];
134 for (const config of configs) {
135 if (config) {
136 const keysWithUsername = config.getKeysByValue(username) || [];
137 const keysWithAlias = aliases
138 .map((alias) => config.getKeysByValue(alias))
139 .filter((k) => !!k)
140 .reduce((x, y) => x.concat(y), []);
141 const allKeys = keysWithUsername.concat(keysWithAlias);
142 this.logger.debug(`Found these config keys to remove: ${allKeys.join(',')}`);
143 allKeys.forEach((key) => {
144 try {
145 config.unset(key);
146 }
147 catch {
148 this.logger.debug(`Failed to remove ${key}`);
149 }
150 });
151 // prevent ConfigFile collision bug
152 // eslint-disable-next-line no-await-in-loop
153 await config.write();
154 }
155 }
156 }
157 /**
158 * Unsets any aliases for provided username
159 *
160 * @param username username that you want to remove from aliases
161 */
162 async unsetAliases(username) {
163 this.logger.debug(`Clearing aliases for username: ${username}`);
164 const existingAliases = this.stateAggregator.aliases.getAll(username);
165 if (existingAliases.length === 0)
166 return;
167 this.logger.debug(`Found these aliases to remove: ${existingAliases.join(',')}`);
168 existingAliases.forEach((alias) => this.stateAggregator.aliases.unset(alias));
169 await this.stateAggregator.aliases.write();
170 }
171 async unsetTokens(username) {
172 this.logger.debug(`Clearing tokens for username: ${username}`);
173 const tokens = this.stateAggregator.tokens.getAll();
174 for (const [key, token] of Object.entries(tokens)) {
175 if (token.user === username) {
176 this.stateAggregator.tokens.unset(key);
177 }
178 }
179 await this.stateAggregator.tokens.write();
180 }
181}
182exports.AuthRemover = AuthRemover;
183//# sourceMappingURL=authRemover.js.map
\No newline at end of file