generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.ts
331 lines (294 loc) · 11.9 KB
/
user.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { EOL } from 'node:os';
import fs from 'node:fs';
import {
AuthInfo,
Connection,
DefaultUserFields,
Logger,
Messages,
Org,
REQUIRED_FIELDS,
SfError,
StateAggregator,
User,
UserFields,
} from '@salesforce/core';
import { mapKeys, omit, toBoolean } from '@salesforce/kit';
import { Dictionary, ensureString, getString, JsonMap } from '@salesforce/ts-types';
import {
Flags,
loglevel,
orgApiVersionFlagWithDeprecations,
parseVarArgs,
requiredOrgFlagWithDeprecations,
SfCommand,
} from '@salesforce/sf-plugins-core';
import { Interfaces } from '@oclif/core';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-user', 'create');
type SuccessMsg = {
name: string;
value: string;
};
type FailureMsg = {
name: string;
message: string;
};
export class CreateUserCommand extends SfCommand<CreateUserOutput> {
public static strict = false;
public static readonly deprecateAliases = true;
public static readonly aliases = ['force:user:create'];
public static readonly summary = messages.getMessage('summary');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly flags = {
'set-alias': Flags.string({
char: 'a',
summary: messages.getMessage('flags.set-alias.summary'),
aliases: ['setalias'],
deprecateAliases: true,
}),
'definition-file': Flags.string({
char: 'f',
summary: messages.getMessage('flags.definition-file.summary'),
description: messages.getMessage('flags.definition-file.description'),
aliases: ['definitionfile'],
deprecateAliases: true,
}),
'set-unique-username': Flags.boolean({
char: 's',
summary: messages.getMessage('flags.set-unique-username.summary'),
description: messages.getMessage('flags.set-unique-username.description'),
aliases: ['setuniqueusername'],
deprecateAliases: true,
}),
'target-org': requiredOrgFlagWithDeprecations,
'api-version': orgApiVersionFlagWithDeprecations,
loglevel,
};
private successes: SuccessMsg[] = [];
private failures: FailureMsg[] = [];
// assert! because they're set early in run method
private flags!: Interfaces.InferredFlags<typeof CreateUserCommand.flags>;
private varargs!: Record<string, unknown>;
public async run(): Promise<CreateUserOutput> {
const { flags, argv } = await this.parse(CreateUserCommand);
this.flags = flags;
const logger = await Logger.child(this.constructor.name);
this.varargs = parseVarArgs({}, argv as string[]);
const conn = await getValidatedConnection(flags['target-org'], flags['api-version']);
const defaultUserFields = await DefaultUserFields.create({
templateUser: ensureString(flags['target-org'].getUsername()),
});
const targetOrgUser = await User.create({ org: flags['target-org'] });
// merge defaults with provided values with cli > file > defaults
const fields = await this.aggregateFields(defaultUserFields.getFields(), logger);
const newUserAuthInfo = await getNewUserAuthInfo(targetOrgUser, fields, conn);
if (fields.profileName) await newUserAuthInfo?.save({ userProfileName: fields.profileName });
// Assign permission sets to the created user
if (fields.permsets) {
try {
// permsets can be passed from cli args or file we need to create an array of permset names either way it's passed
// it will either be a comma separated string, or an array, force it into an array
const permsetArray = permsetsStringToArray(fields.permsets);
await targetOrgUser.assignPermissionSets(ensureString(newUserAuthInfo.getFields().userId), permsetArray);
this.successes.push({
name: 'Permission Set Assignment',
value: permsetArray.join(','),
});
} catch (error) {
const err = error as SfError;
this.failures.push({
name: 'Permission Set Assignment',
message: err.message,
});
}
}
// Generate and set a password if specified
if (fields.generatePassword) {
try {
const password = User.generatePasswordUtf8();
await targetOrgUser.assignPassword(newUserAuthInfo, password);
password.value((pass: Buffer) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
newUserAuthInfo.save({ password: pass.toString('utf-8') });
this.successes.push({
name: 'Password Assignment',
value: pass.toString(),
});
});
} catch (error) {
const err = error as SfError;
this.failures.push({
name: 'Password Assignment',
message: err.message,
});
}
}
// Set the alias if specified
if (flags['set-alias']) {
const stateAggregator = await StateAggregator.getInstance();
await stateAggregator.aliases.setAndSave(flags['set-alias'], fields.username);
}
fields.id = ensureString(newUserAuthInfo.getFields().userId);
this.print(fields);
this.setExitCode();
const { permsets, ...fieldsWithoutPermsets } = fields;
return {
orgId: flags['target-org'].getOrgId(),
permissionSetAssignments: permsetsStringToArray(permsets),
fields: { ...mapKeys(fieldsWithoutPermsets, (value, key) => key.toLowerCase()) },
};
}
// this method is pretty rough, so we'll ignore some TS errors
private async aggregateFields(defaultFields: UserFields, logger: Logger): Promise<UserFields & Dictionary<string>> {
// username can be overridden both in the file or varargs, save it to check if it was changed somewhere
const defaultUsername = defaultFields.username;
// start with the default fields, then add the fields from the file, then (possibly overwriting) add the fields from the cli varargs param
if (this.flags['definition-file']) {
const content = JSON.parse(await fs.promises.readFile(this.flags['definition-file'], 'utf-8')) as JsonMap;
Object.entries(content).forEach(([key, value]) => {
// @ts-expect-error cast entries to lowercase to standardize
defaultFields[lowerFirstLetter(key)] = value as keyof typeof REQUIRED_FIELDS;
});
}
if (this.varargs) {
Object.keys(this.varargs).forEach((key) => {
if (key.toLowerCase() === 'generatepassword') {
// @ts-expect-error standardize generatePassword casing
defaultFields['generatePassword'] = toBoolean(this.varargs[key]);
} else if (key.toLowerCase() === 'profilename') {
// @ts-expect-error standardize profileName casing
defaultFields['profileName'] = this.varargs[key];
} else {
// @ts-expect-error all other varargs are left "as is"
defaultFields[lowerFirstLetter(key)] = this.varargs[key];
}
});
}
// check if "username" was passed along with "set-unique-username" flag, if so append org id
if (this.flags['set-unique-username'] && defaultFields.username !== defaultUsername) {
defaultFields.username = `${defaultFields.username}.${this.flags['target-org'].getOrgId().toLowerCase()}`;
}
// @ts-expect-error check if "profileName" was passed, this needs to become a profileId before calling User.create
if (defaultFields['profileName']) {
// @ts-expect-error profileName is not a valid field on UserFields
const name = (defaultFields['profileName'] ?? 'Standard User') as string;
logger.debug(`Querying org for profile name [${name}]`);
const profile = await this.flags['target-org']
.getConnection(this.flags['api-version'])
.singleRecordQuery<{ Id: string }>(`SELECT id FROM profile WHERE name='${name}'`);
defaultFields.profileId = profile.Id;
}
return defaultFields;
}
private print(fields: UserFields): void {
const userCreatedSuccessMsg = messages.getMessage('success', [
fields.username,
fields.id,
this.flags['target-org'].getOrgId(),
EOL,
this.config.bin,
fields.username,
]);
// we initialize to be an empty array to be able to push onto it
// so we need to check that the size is greater than 0 to know we had a failure
if (this.failures.length > 0) {
this.styledHeader('Partial Success');
this.log(userCreatedSuccessMsg);
this.log('');
this.styledHeader('Failures');
this.table({
data: this.failures,
columns: [
{ key: 'name', name: 'Action' },
{ key: 'message', name: 'Error Message' },
],
});
} else {
this.log(userCreatedSuccessMsg);
}
}
private setExitCode(): void {
if (this.failures.length && this.successes.length) {
process.exitCode = 68;
} else if (this.failures.length) {
process.exitCode = 1;
} else if (this.successes.length) {
process.exitCode = 0;
}
}
}
export default CreateUserCommand;
export type CreateUserOutput = {
orgId: string;
permissionSetAssignments: string[];
fields: Record<string, unknown>;
};
const lowerFirstLetter = (word: string): string => word[0].toLowerCase() + word.substr(1);
/**
* removes fields that cause errors in salesforce APIs within sfdx-core's createUser method
*
* @param fields a list of combined fields from varargs and the config file
* @private
*/
const stripInvalidAPIFields = (fields: UserFields & Dictionary<string>): UserFields =>
omit(fields, ['permsets', 'generatepassword', 'generatePassword', 'profileName']);
const getNewUserAuthInfo = async (
targetOrgUser: User,
fields: UserFields & Dictionary<string>,
conn: Connection
): Promise<AuthInfo> => {
try {
return await targetOrgUser.createUser(stripInvalidAPIFields(fields));
} catch (e) {
if (!(e instanceof Error)) {
throw e;
}
return catchCreateUser(e, fields, conn);
}
};
/** will definitely throw, but will throw better error messages than User.createUser was going to */
const catchCreateUser = async (respBody: Error, fields: UserFields, conn: Connection): Promise<never> => {
// For Gacks, the error message is on response.body[0].message but for handled errors
// the error message is on response.body.Errors[0].description.
const errMessage = getString(respBody, 'message') ?? 'Unknown Error';
// Provide a more user friendly error message for certain server errors.
if (errMessage.includes('LICENSE_LIMIT_EXCEEDED')) {
const profile = await conn.singleRecordQuery<{ Name: string }>(
`SELECT name FROM profile WHERE id='${fields.profileId}'`
);
throw new SfError(messages.getMessage('licenseLimitExceeded', [profile.Name]), 'licenseLimitExceeded');
} else if (errMessage.includes('DUPLICATE_USERNAME')) {
throw new SfError(messages.getMessage('duplicateUsername', [fields.username]), 'duplicateUsername');
} else {
throw SfError.wrap(errMessage);
}
};
/** the org must be a scratch org AND not use JWT with hyperforce */
const getValidatedConnection = async (targetOrg: Org, apiVersion?: string): Promise<Connection> => {
if (!(await targetOrg.determineIfScratch())) {
throw messages.createError('error.nonScratchOrg');
}
const conn = targetOrg.getConnection(apiVersion);
if (
conn.getAuthInfo().isJwt() &&
// hyperforce sandbox instances end in S like USA254S
targetOrg.getField<string>(Org.Fields.CREATED_ORG_INSTANCE)?.endsWith('S')
) {
throw messages.createError('error.jwtHyperforce');
}
return conn;
};
const permsetsStringToArray = (fieldsPermsets: string | string[] | undefined): string[] => {
if (!fieldsPermsets) return [];
return Array.isArray(fieldsPermsets)
? fieldsPermsets
: fieldsPermsets.split(',').map((item) => item.replace("'", '').trim());
};