@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
121 lines • 5.52 kB
JavaScript
/*
* 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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermissionSetAssignment = void 0;
const node_os_1 = require("node:os");
const kit_1 = require("@salesforce/kit");
const logger_1 = require("../logger/logger");
const messages_1 = require("../messages");
const sfError_1 = require("../sfError");
;
const messages = new messages_1.Messages('@salesforce/core', 'permissionSetAssignment', new Map([["orgRequired", "An Org instance is required."], ["userIdRequired", "A Salesforce id for the user is required."], ["permSetRequired", "The name of a permission set is required."], ["unexpectedType", "An unexpected response was returned from the permission set assignment."], ["assignCommandPermissionSetNotFoundError", "Permission set \"%s\" not found in target org. Do you need to push source?"], ["assignCommandPermissionSetNotFoundForNSError", "Permission set \"%s\" for namespace \"%s\" not found in target org. Do you need to push source or install the package?"], ["errorsEncounteredCreatingAssignment", "Error(s) were reported."], ["notSuccessfulButNoErrorsReported", "The permission set assignment failed but no errors were reported."]]));
/**
* A class for assigning a Salesforce User to one or more permission sets.
*/
class PermissionSetAssignment {
logger;
org;
constructor(org, logger) {
this.logger = logger;
this.org = org;
}
/**
* Creates a new instance of PermissionSetAssignment.
*
* @param org The target org for the assignment.
*/
static async init(org) {
if (!org) {
throw messages.createError('orgRequired');
}
return new PermissionSetAssignment(org, await logger_1.Logger.child('PermissionSetAssignment'));
}
/**
* Assigns a user to one or more permission sets.
*
* @param id A user id
* @param permSetString An array of permission set names.
*/
async create(id, permSetString) {
if (!id) {
throw messages.createError('userIdRequired');
}
if (!permSetString) {
throw messages.createError('permSetRequired');
}
const { nsPrefix, permSetName } = this.parsePermissionSetString(permSetString);
let query = `SELECT Id FROM PermissionSet WHERE Name='${permSetName}'`;
if (nsPrefix) {
query += ` AND NamespacePrefix='${nsPrefix}'`;
}
const result = await this.org.getConnection().query(query);
const permissionSetId = result?.records[0]?.Id;
if (!permissionSetId) {
if (nsPrefix) {
throw messages.createError('assignCommandPermissionSetNotFoundForNSError', [permSetName, nsPrefix]);
}
else {
throw messages.createError('assignCommandPermissionSetNotFoundError', [permSetName]);
}
}
const assignment = {
assigneeId: id,
permissionSetId,
};
const createResponse = await this.org
.getConnection()
.sobject('PermissionSetAssignment')
.create((0, kit_1.mapKeys)(assignment, (value, key) => (0, kit_1.upperFirst)(key)));
if (createResponse.success === false) {
if (!createResponse.errors?.length) {
throw messages.createError('notSuccessfulButNoErrorsReported');
}
const message = [messages.getMessage('errorsEncounteredCreatingAssignment')]
.concat((createResponse.errors ?? []).map((error) => {
// note: the types for jsforce SaveError don't have "string[]" error,
// but there was a UT for that at https://github.com/forcedotcom/sfdx-core/blob/7412d103703cfe2df2211546fcf2e6d93a689bc0/test/unit/org/permissionSetAssignmentTest.ts#L146
// which could either be hallucination or a real response we've seen, so I'm preserving that behavior.
if (typeof error === 'string')
return error;
return error.fields ? `${error.message} on fields ${error.fields.join(',')}` : error.message;
}))
.join(node_os_1.EOL);
throw new sfError_1.SfError(message, 'errorsEncounteredCreatingAssignment');
}
else {
return assignment;
}
}
/**
* Parses a permission set name based on if it has a namespace or not.
*
* @param permSetString The permission set string.
*/
parsePermissionSetString(permSetString) {
const nsPrefixMatch = RegExp(/(\w+(?=__))(__)(.*)/).exec(permSetString);
let nsPrefix;
let permSetName;
if (nsPrefixMatch) {
try {
nsPrefix = nsPrefixMatch[1];
permSetName = nsPrefixMatch[3];
this.logger.debug(`Using namespacePrefix ${nsPrefix} for permission set ${permSetName}`);
}
catch (e) {
// Don't fail if we parse wrong.
this.logger.debug(e);
}
}
else {
permSetName = permSetString;
}
return { nsPrefix, permSetName };
}
}
exports.PermissionSetAssignment = PermissionSetAssignment;
//# sourceMappingURL=permissionSetAssignment.js.map
;