Skip to content

Commit

Permalink
fix: parking orbit plugin-user
Browse files Browse the repository at this point in the history
  • Loading branch information
WillieRuemmele committed Apr 22, 2022
1 parent d5d41fe commit d500413
Show file tree
Hide file tree
Showing 15 changed files with 3,641 additions and 1,403 deletions.
19 changes: 10 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{
"name": "@salesforce/plugin-user",
"description": "Commands to interact with Users and Permission Sets",
"version": "1.7.1",
"version": "2.0.0",
"author": "Salesforce",
"main": "lib/index.js",
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@oclif/config": "^1.18.1",
"@salesforce/command": "^4.2.0",
"@salesforce/core": "^2.31.0",
"@salesforce/kit": "^1.5.18",
"@oclif/core": "^1.7.0",
"@salesforce/command": "^5.0.5",
"@salesforce/core": "^3.13.1",
"@salesforce/kit": "^1.5.38",
"tslib": "^2"
},
"devDependencies": {
"@oclif/dev-cli": "^1",
"@oclif/plugin-command-snapshot": "2.1.1",
"@salesforce/cli-plugins-testkit": "^1.4.17",
"@oclif/plugin-command-snapshot": "3.1.3",
"@salesforce/cli-plugins-testkit": "^1.5.28",
"@salesforce/dev-config": "^3.0.0",
"@salesforce/dev-scripts": "^2.0.0",
"@salesforce/plugin-command-reference": "^1.3.0",
Expand All @@ -39,6 +39,7 @@
"lint-staged": "^11.0.0",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"oclif": "^2.6.3",
"prettier": "^2.3.0",
"pretty-quick": "^3.1.0",
"shx": "0.3.4",
Expand Down Expand Up @@ -114,7 +115,7 @@
"test:command-reference": "./bin/run commandreference:generate --erroronwarnings",
"test:deprecation-policy": "./bin/run snapshot:compare",
"test:nuts": "nyc mocha \"**/*.nut.ts\" --slow 4500 --timeout 600000 --parallel",
"version": "oclif-dev readme"
"version": "oclif readme"
},
"publishConfig": {
"access": "public"
Expand Down
31 changes: 13 additions & 18 deletions src/commands/force/user/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import * as os from 'os';
import * as fse from 'fs-extra';
import {
Aliases,
AuthInfo,
Connection,
DefaultUserFields,
fs,
GlobalInfo,
Logger,
Messages,
REQUIRED_FIELDS,
SfdxError,
SfError,
User,
UserFields,
} from '@salesforce/core';
Expand Down Expand Up @@ -112,7 +112,7 @@ export class UserCreateCommand extends SfdxCommand {
value: permsetArray.join(','),
});
} catch (error) {
const err = error as SfdxError;
const err = error as SfError;
this.failures.push({
name: 'Permission Set Assignment',
message: err.message,
Expand All @@ -134,7 +134,7 @@ export class UserCreateCommand extends SfdxCommand {
});
});
} catch (error) {
const err = error as SfdxError;
const err = error as SfError;
this.failures.push({
name: 'Password Assignment',
message: err.message,
Expand All @@ -144,9 +144,9 @@ export class UserCreateCommand extends SfdxCommand {

// Set the alias if specified
if (this.flags.setalias && typeof this.flags.setalias === 'string') {
const alias: Aliases = await Aliases.create(Aliases.getDefaultOptions());
alias.set(this.flags.setalias, fields.username);
await alias.write();
const globalInfo = await GlobalInfo.getInstance();
globalInfo.aliases.set(this.flags.setalias, fields.username);
await globalInfo.write();
}

fields.id = this.authInfo.getFields().userId;
Expand All @@ -171,11 +171,11 @@ export class UserCreateCommand extends SfdxCommand {
const profile = await conn.singleRecordQuery<{ Name: string }>(
`SELECT name FROM profile WHERE id='${fields.profileId}'`
);
throw SfdxError.create('@salesforce/plugin-user', 'create', 'licenseLimitExceeded', [profile.Name]);
throw new SfError(messages.getMessage('licenseLimitExceeded', [profile.Name]), 'licenseLimitExceeded');
} else if (errMessage.includes('DUPLICATE_USERNAME')) {
throw SfdxError.create('@salesforce/plugin-user', 'create', 'duplicateUsername', [fields.username]);
throw new SfError(messages.getMessage('duplicateUsername', [fields.username]), 'duplicateUsername');
} else {
throw SfdxError.wrap(errMessage);
throw SfError.wrap(errMessage);
}
}

Expand All @@ -190,7 +190,7 @@ export class UserCreateCommand extends SfdxCommand {
// start with the default fields, then add the fields from the file, then (possibly overwritting) add the fields from the cli varargs param
if (this.flags.definitionfile && typeof this.flags.definitionfile === 'string') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call
const content = (await fs.readJson(this.flags.definitionfile)) as UserFields;
const content = (await fse.readJson(this.flags.definitionfile)) as UserFields;
Object.keys(content).forEach((key) => {
// cast entries to lowercase to standardize
defaultFields[this.lowerFirstLetter(key)] = content[key] as keyof typeof REQUIRED_FIELDS;
Expand Down Expand Up @@ -246,12 +246,7 @@ export class UserCreateCommand extends SfdxCommand {
this.ux.log(userCreatedSuccessMsg);
this.ux.log('');
this.ux.styledHeader('Failures');
this.ux.table(this.failures, {
columns: [
{ key: 'name', label: 'Action' },
{ key: 'message', label: 'Error Message' },
],
});
this.ux.table(this.failures, { name: { header: 'Action' }, message: { header: 'Error Message' } });
} else {
this.ux.log(userCreatedSuccessMsg);
}
Expand Down
25 changes: 10 additions & 15 deletions src/commands/force/user/display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { SfdxCommand } from '@salesforce/command';
import { Aliases, AuthFields, AuthInfo, Connection, Logger, Messages, SfdxError, sfdc } from '@salesforce/core';
import { AuthFields, AuthInfo, Connection, Logger, Messages, SfError, sfdc, GlobalInfo } from '@salesforce/core';
import { getString } from '@salesforce/ts-types';

Messages.importMessagesDirectory(__dirname);
Expand All @@ -34,13 +34,13 @@ export class UserDisplayCommand extends SfdxCommand {
public async run(): Promise<UserDisplayResult> {
this.logger = await Logger.child(this.constructor.name);
if (sfdc.matchesAccessToken(this.flags.targetusername as string)) {
throw new SfdxError(messages.getMessage('accessTokenError'), 'accessTokenError', [
throw new SfError(messages.getMessage('accessTokenError'), 'accessTokenErrorError', [
messages.getMessage('accessTokenAction'),
]);
}
const username: string = this.org.getUsername();
const userAuthDataArray: AuthInfo[] = await this.org.readUserAuthFiles();
// userAuthD ataArray contains all of the Org's users AuthInfo, we just need the default or -u, which is in the username variable
// userAuthDataArray contains all of the Org's users AuthInfo, we just need the default or -u, which is in the username variable
const userAuthData: AuthFields = userAuthDataArray
.find((uat) => uat.getFields().username === username)
.getFields(true);
Expand All @@ -50,7 +50,7 @@ export class UserDisplayCommand extends SfdxCommand {
let userId: string = userAuthData.userId;

try {
// the user executing this command may not have access to the Profile sObject.
// the user executing this command may not have access to the Profile sObject.
if (!profileName) {
const PROFILE_NAME_QUERY = `SELECT name FROM Profile WHERE Id IN (SELECT ProfileId FROM User WHERE username='${username}')`;
profileName = getString(await conn.query(PROFILE_NAME_QUERY), 'records[0].Name');
Expand Down Expand Up @@ -84,13 +84,10 @@ export class UserDisplayCommand extends SfdxCommand {
username,
};

// if they passed in a alias and it maps to something we have an Alias.
const alias = await Aliases.create(Aliases.getDefaultOptions());
const aliasContent = alias.getContents().orgs;
if (aliasContent) {
Object.keys(aliasContent).forEach((aliasedName) => {
if (aliasContent[aliasedName] === username) result.alias = aliasedName;
});
const globalInfo = await GlobalInfo.getInstance();
const alias = globalInfo.aliases.get(username);
if (alias) {
result.alias = alias;
}

if (userAuthData.password) {
Expand All @@ -106,10 +103,8 @@ export class UserDisplayCommand extends SfdxCommand {

private print(result: UserDisplayResult): void {
const columns = {
columns: [
{ key: 'key', label: 'key' },
{ key: 'label', label: 'label' },
],
key: { header: 'key' },
label: { header: 'label' },
};

const tableRow = [];
Expand Down
18 changes: 8 additions & 10 deletions src/commands/force/user/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import * as os from 'os';
import { SfdxCommand } from '@salesforce/command';
import { Messages, Connection, Aliases } from '@salesforce/core';
import { Messages, Connection, GlobalInfo } from '@salesforce/core';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-user', 'list');
Expand Down Expand Up @@ -42,13 +42,13 @@ export class UserListCommand extends SfdxCommand {
this.buildUserInfos(),
this.buildProfileInfos(),
this.org.readUserAuthFiles(),
Aliases.create(Aliases.getDefaultOptions()),
(await GlobalInfo.getInstance()).aliases,
]);

const authList: AuthList[] = userAuthData.map((authData) => {
const username = authData.getUsername();
// if they passed in a alias and it maps to something we have an Alias.
const alias = aliases.getKeysByValue(authData.getUsername())?.[0];
const alias = aliases.get(username);
return {
defaultMarker: this.org.getUsername() === username ? '(A)' : '',
alias: alias || '',
Expand All @@ -63,13 +63,11 @@ export class UserListCommand extends SfdxCommand {
});

const columns = {
columns: [
{ key: 'defaultMarker', label: 'Default' },
{ key: 'alias', label: 'Alias' },
{ key: 'username', label: 'Username' },
{ key: 'profileName', label: 'Profile Name' },
{ key: 'userId', label: 'User Id' },
],
defaultMarker: { header: 'Default' },
alias: { header: 'Alias' },
username: { header: 'Username' },
profileName: { header: 'Profile Name' },
userId: { header: 'User Id' },
};

this.ux.styledHeader(`Users in org ${this.org.getOrgId()}`);
Expand Down
22 changes: 10 additions & 12 deletions src/commands/force/user/password/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
*/
import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { Aliases, AuthInfo, Connection, Messages, Org, SfdxError, User } from '@salesforce/core';
import { PasswordConditions } from '@salesforce/core/lib/user';
import { AuthInfo, Connection, GlobalInfo, Messages, Org, SfError, User } from '@salesforce/core';
import { PasswordConditions } from '@salesforce/core/lib/org/user';
import { asNumber } from '@salesforce/ts-types';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-user', 'password.generate');
Expand Down Expand Up @@ -59,7 +59,7 @@ export class UserPasswordGenerateCommand extends SfdxCommand {
try {
// Convert any aliases to usernames
// fetch will return undefined if there's no Alias for that name
const username = (await Aliases.fetch(aliasOrUsername)) || aliasOrUsername;
const username = (await GlobalInfo.getInstance()).aliases.resolveUsername(aliasOrUsername);

const authInfo: AuthInfo = await AuthInfo.create({ username });
const connection: Connection = await Connection.create({ authInfo });
Expand All @@ -83,7 +83,7 @@ export class UserPasswordGenerateCommand extends SfdxCommand {

await authInfo.save();
} catch (e) {
const err = e as SfdxError;
const err = e as SfError;
if (
err.message.includes('Cannot set password for self') ||
err.message.includes('The requested Resource does not exist')
Expand All @@ -93,15 +93,15 @@ export class UserPasswordGenerateCommand extends SfdxCommand {
const connection: Connection = await Connection.create({ authInfo });
const org = await Org.create({ connection });
if (parseInt(await org.retrieveMaxApiVersion(), 10) >= 51) {
throw new SfdxError(
throw new SfError(
messages.getMessage('noSelfSetError'),
'noSelfSetError',
'noSelfSetErrorError',
messages.getMessage('noSelfSetErrorActions').split(os.EOL)
);
}
throw new SfdxError(messages.getMessage('noSelfSetErrorV50'), 'noSelfSetError');
throw new SfError(messages.getMessage('noSelfSetErrorV50'), 'noSelfSetErrorError');
}
throw SfdxError.wrap(err);
throw SfError.wrap(err);
}
}

Expand All @@ -118,10 +118,8 @@ export class UserPasswordGenerateCommand extends SfdxCommand {
} else {
this.ux.log(messages.getMessage('successMultiple', [os.EOL]));
const columnData = {
columns: [
{ key: 'username', label: 'USERNAME' },
{ key: 'password', label: 'PASSWORD' },
],
username: { header: 'USERNAME' },
password: { header: 'PASSWORD' },
};
this.ux.table(this.passwordData, columnData);
}
Expand Down
22 changes: 6 additions & 16 deletions src/commands/force/user/permset/assign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { Aliases, Connection, Messages, Org, SfdxError, User } from '@salesforce/core';
import { Connection, GlobalInfo, Messages, Org, SfError, User } from '@salesforce/core';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-user', 'permset.assign');
Expand Down Expand Up @@ -54,7 +54,7 @@ export class UserPermsetAssignCommand extends SfdxCommand {

for (const aliasOrUsername of aliasOrUsernames) {
// Attempt to convert any aliases to usernames. Not found alias will be **assumed** to be a username
const username = (await Aliases.fetch(aliasOrUsername)) || aliasOrUsername;
const username = (await GlobalInfo.getInstance()).aliases.resolveUsername(aliasOrUsername);
const user: User = await User.create({ org });
// get userId of whomever the permset will be assigned to via query to avoid AuthInfo if remote user
const queryResult = await connection.singleRecordQuery<{ Id: string }>(
Expand All @@ -69,7 +69,7 @@ export class UserPermsetAssignCommand extends SfdxCommand {
value: permsetName,
});
} catch (e) {
const err = e as SfdxError;
const err = e as SfError;
this.failures.push({
name: aliasOrUsername,
message: err.message,
Expand All @@ -79,7 +79,7 @@ export class UserPermsetAssignCommand extends SfdxCommand {
}
} catch (e) {
if (e instanceof Error || typeof e === 'string') {
throw SfdxError.wrap(e);
throw SfError.wrap(e);
}
throw e;
}
Expand All @@ -95,12 +95,7 @@ export class UserPermsetAssignCommand extends SfdxCommand {
private print(): void {
if (this.successes.length > 0) {
this.ux.styledHeader('Permsets Assigned');
this.ux.table(this.successes, {
columns: [
{ key: 'name', label: 'Username' },
{ key: 'value', label: 'Permission Set Assignment' },
],
});
this.ux.table(this.successes, { name: { header: 'Username' }, value: { header: 'Permission Set Assignment' } });
}

if (this.failures.length > 0) {
Expand All @@ -109,12 +104,7 @@ export class UserPermsetAssignCommand extends SfdxCommand {
}

this.ux.styledHeader('Failures');
this.ux.table(this.failures, {
columns: [
{ key: 'name', label: 'Username' },
{ key: 'message', label: 'Error Message' },
],
});
this.ux.table(this.failures, { name: { header: 'Username' }, message: { header: 'Error Message' } });
}
}
}
Loading

0 comments on commit d500413

Please sign in to comment.